@fs/mycroft 0.2.0 → 0.3.0
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.
- package/README.md +23 -0
- package/dist/batch-embedder-6IIWAZPW.js +14 -0
- package/dist/batch-embedder-6IIWAZPW.js.map +1 -0
- package/dist/batch-embedder-7DGZAQKL.js +14 -0
- package/dist/batch-embedder-7DGZAQKL.js.map +1 -0
- package/dist/batch-embedder-IZDBS3IL.js +13 -0
- package/dist/batch-embedder-IZDBS3IL.js.map +1 -0
- package/dist/batch-embedder-LYCZDYI4.js +15 -0
- package/dist/batch-embedder-LYCZDYI4.js.map +1 -0
- package/dist/batch-embedder-RHKD2OJD.js +14 -0
- package/dist/batch-embedder-RHKD2OJD.js.map +1 -0
- package/dist/batch-embedder-VQZUI7R6.js +14 -0
- package/dist/batch-embedder-VQZUI7R6.js.map +1 -0
- package/dist/batch-embedder-ZJZLNLOK.js +14 -0
- package/dist/batch-embedder-ZJZLNLOK.js.map +1 -0
- package/dist/batch-summarizer-7MCT4HJB.js +14 -0
- package/dist/batch-summarizer-7MCT4HJB.js.map +1 -0
- package/dist/batch-summarizer-BMIBVFAE.js +14 -0
- package/dist/batch-summarizer-BMIBVFAE.js.map +1 -0
- package/dist/chunk-35EO53CC.js +8058 -0
- package/dist/chunk-35EO53CC.js.map +1 -0
- package/dist/chunk-57ZGGKEF.js +8060 -0
- package/dist/chunk-57ZGGKEF.js.map +1 -0
- package/dist/chunk-6DLQHHCC.js +249 -0
- package/dist/chunk-6DLQHHCC.js.map +1 -0
- package/dist/chunk-7CO4PMU5.js +92 -0
- package/dist/chunk-7CO4PMU5.js.map +1 -0
- package/dist/chunk-7DUQNGEK.js +253 -0
- package/dist/chunk-7DUQNGEK.js.map +1 -0
- package/dist/chunk-7IPX4MKA.js +4637 -0
- package/dist/chunk-7IPX4MKA.js.map +1 -0
- package/dist/chunk-7NLMBXXY.js +6438 -0
- package/dist/chunk-7NLMBXXY.js.map +1 -0
- package/dist/chunk-BR2PM6D3.js +11047 -0
- package/dist/chunk-BR2PM6D3.js.map +1 -0
- package/dist/chunk-KGG7WEYE.js +162 -0
- package/dist/chunk-KGG7WEYE.js.map +1 -0
- package/dist/chunk-QRDUQX63.js +256 -0
- package/dist/chunk-QRDUQX63.js.map +1 -0
- package/dist/chunk-R3FOJK5A.js +2088 -0
- package/dist/chunk-R3FOJK5A.js.map +1 -0
- package/dist/chunk-XXO66RCF.js +94 -0
- package/dist/chunk-XXO66RCF.js.map +1 -0
- package/dist/cli.js +638 -179
- package/dist/cli.js.map +1 -1
- package/dist/fileFromPath-FLANAQWT.js +128 -0
- package/dist/fileFromPath-FLANAQWT.js.map +1 -0
- package/dist/main-36PRDAPE.js +1857 -0
- package/dist/main-36PRDAPE.js.map +1 -0
- package/dist/main-B3QJZGLU.js +1859 -0
- package/dist/main-B3QJZGLU.js.map +1 -0
- package/package.json +7 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../node_modules/ms/index.js","../node_modules/humanize-ms/index.js","../node_modules/agentkeepalive/lib/constants.js","../node_modules/agentkeepalive/lib/agent.js","../node_modules/agentkeepalive/lib/https_agent.js","../node_modules/agentkeepalive/index.js","../node_modules/event-target-shim/src/event.mjs","../node_modules/event-target-shim/src/event-target.mjs","../node_modules/abort-controller/src/abort-signal.ts","../node_modules/abort-controller/src/abort-controller.ts","../node_modules/openai/src/internal/qs/formats.ts","../node_modules/openai/src/internal/qs/utils.ts","../node_modules/openai/src/internal/qs/stringify.ts","../node_modules/openai/src/version.ts","../node_modules/openai/src/_shims/registry.ts","../node_modules/openai/src/_shims/node-runtime.ts","../node_modules/formdata-node/lib/esm/FormData.js","../node_modules/formdata-node/lib/esm/isBlob.js","../node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js","../node_modules/form-data-encoder/lib/esm/util/createBoundary.js","../node_modules/form-data-encoder/lib/esm/util/isPlainObject.js","../node_modules/form-data-encoder/lib/esm/util/normalizeValue.js","../node_modules/form-data-encoder/lib/esm/util/escapeName.js","../node_modules/form-data-encoder/lib/esm/util/isFunction.js","../node_modules/form-data-encoder/lib/esm/util/isFileLike.js","../node_modules/form-data-encoder/lib/esm/util/isFormData.js","../node_modules/form-data-encoder/lib/esm/FormDataEncoder.js","../node_modules/openai/src/_shims/MultipartBody.ts","../node_modules/openai/_shims/index.mjs","../node_modules/openai/src/error.ts","../node_modules/openai/src/internal/decoders/line.ts","../node_modules/openai/src/internal/stream-utils.ts","../node_modules/openai/src/streaming.ts","../node_modules/openai/src/uploads.ts","../node_modules/openai/src/core.ts","../node_modules/openai/src/pagination.ts","../node_modules/openai/src/resource.ts","../node_modules/openai/src/resources/chat/completions/messages.ts","../node_modules/openai/src/resources/chat/completions/completions.ts","../node_modules/openai/src/resources/chat/chat.ts","../node_modules/openai/src/resources/audio/speech.ts","../node_modules/openai/src/resources/audio/transcriptions.ts","../node_modules/openai/src/resources/audio/translations.ts","../node_modules/openai/src/resources/audio/audio.ts","../node_modules/openai/src/resources/batches.ts","../node_modules/openai/src/lib/EventStream.ts","../node_modules/openai/src/lib/AssistantStream.ts","../node_modules/openai/src/resources/beta/assistants.ts","../node_modules/openai/src/lib/RunnableFunction.ts","../node_modules/openai/src/lib/chatCompletionUtils.ts","../node_modules/openai/src/lib/parser.ts","../node_modules/openai/src/lib/AbstractChatCompletionRunner.ts","../node_modules/openai/src/lib/ChatCompletionRunner.ts","../node_modules/openai/src/_vendor/partial-json-parser/parser.ts","../node_modules/openai/src/lib/ChatCompletionStream.ts","../node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts","../node_modules/openai/src/resources/beta/chat/completions.ts","../node_modules/openai/src/resources/beta/chat/chat.ts","../node_modules/openai/src/resources/beta/realtime/sessions.ts","../node_modules/openai/src/resources/beta/realtime/transcription-sessions.ts","../node_modules/openai/src/resources/beta/realtime/realtime.ts","../node_modules/openai/src/resources/beta/threads/messages.ts","../node_modules/openai/src/resources/beta/threads/runs/steps.ts","../node_modules/openai/src/resources/beta/threads/runs/runs.ts","../node_modules/openai/src/resources/beta/threads/threads.ts","../node_modules/openai/src/resources/beta/beta.ts","../node_modules/openai/src/resources/completions.ts","../node_modules/openai/src/resources/containers/files/content.ts","../node_modules/openai/src/resources/containers/files/files.ts","../node_modules/openai/src/resources/containers/containers.ts","../node_modules/openai/src/resources/embeddings.ts","../node_modules/openai/src/resources/evals/runs/output-items.ts","../node_modules/openai/src/resources/evals/runs/runs.ts","../node_modules/openai/src/resources/evals/evals.ts","../node_modules/openai/src/resources/files.ts","../node_modules/openai/src/resources/fine-tuning/methods.ts","../node_modules/openai/src/resources/fine-tuning/alpha/graders.ts","../node_modules/openai/src/resources/fine-tuning/alpha/alpha.ts","../node_modules/openai/src/resources/fine-tuning/checkpoints/permissions.ts","../node_modules/openai/src/resources/fine-tuning/checkpoints/checkpoints.ts","../node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts","../node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts","../node_modules/openai/src/resources/fine-tuning/fine-tuning.ts","../node_modules/openai/src/resources/graders/grader-models.ts","../node_modules/openai/src/resources/graders/graders.ts","../node_modules/openai/src/resources/images.ts","../node_modules/openai/src/resources/models.ts","../node_modules/openai/src/resources/moderations.ts","../node_modules/openai/src/lib/ResponsesParser.ts","../node_modules/openai/src/resources/responses/input-items.ts","../node_modules/openai/src/lib/responses/ResponseStream.ts","../node_modules/openai/src/resources/responses/responses.ts","../node_modules/openai/src/resources/uploads/parts.ts","../node_modules/openai/src/resources/uploads/uploads.ts","../node_modules/openai/src/lib/Util.ts","../node_modules/openai/src/resources/vector-stores/files.ts","../node_modules/openai/src/resources/vector-stores/file-batches.ts","../node_modules/openai/src/resources/vector-stores/vector-stores.ts","../node_modules/openai/src/index.ts","../src/services/constants.ts","../src/config.ts","../src/commands/io.ts","../src/services/batch-embedder.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/*!\n * humanize-ms - index.js\n * Copyright(c) 2014 dead_horse <dead_horse@qq.com>\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module dependencies.\n */\n\nvar util = require('util');\nvar ms = require('ms');\n\nmodule.exports = function (t) {\n if (typeof t === 'number') return t;\n var r = ms(t);\n if (r === undefined) {\n var err = new Error(util.format('humanize-ms(%j) result undefined', t));\n console.warn(err.stack);\n }\n return r;\n};\n","'use strict';\n\nmodule.exports = {\n // agent\n CURRENT_ID: Symbol('agentkeepalive#currentId'),\n CREATE_ID: Symbol('agentkeepalive#createId'),\n INIT_SOCKET: Symbol('agentkeepalive#initSocket'),\n CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'),\n // socket\n SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'),\n SOCKET_NAME: Symbol('agentkeepalive#socketName'),\n SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'),\n SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'),\n};\n","'use strict';\n\nconst OriginalAgent = require('http').Agent;\nconst ms = require('humanize-ms');\nconst debug = require('util').debuglog('agentkeepalive');\nconst {\n INIT_SOCKET,\n CURRENT_ID,\n CREATE_ID,\n SOCKET_CREATED_TIME,\n SOCKET_NAME,\n SOCKET_REQUEST_COUNT,\n SOCKET_REQUEST_FINISHED_COUNT,\n} = require('./constants');\n\n// OriginalAgent come from\n// - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js\n// - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js\n\n// node <= 10\nlet defaultTimeoutListenerCount = 1;\nconst majorVersion = parseInt(process.version.split('.', 1)[0].substring(1));\nif (majorVersion >= 11 && majorVersion <= 12) {\n defaultTimeoutListenerCount = 2;\n} else if (majorVersion >= 13) {\n defaultTimeoutListenerCount = 3;\n}\n\nfunction deprecate(message) {\n console.log('[agentkeepalive:deprecated] %s', message);\n}\n\nclass Agent extends OriginalAgent {\n constructor(options) {\n options = options || {};\n options.keepAlive = options.keepAlive !== false;\n // default is keep-alive and 4s free socket timeout\n // see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83\n if (options.freeSocketTimeout === undefined) {\n options.freeSocketTimeout = 4000;\n }\n // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout`\n if (options.keepAliveTimeout) {\n deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');\n options.freeSocketTimeout = options.keepAliveTimeout;\n delete options.keepAliveTimeout;\n }\n // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout`\n if (options.freeSocketKeepAliveTimeout) {\n deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead');\n options.freeSocketTimeout = options.freeSocketKeepAliveTimeout;\n delete options.freeSocketKeepAliveTimeout;\n }\n\n // Sets the socket to timeout after timeout milliseconds of inactivity on the socket.\n // By default is double free socket timeout.\n if (options.timeout === undefined) {\n // make sure socket default inactivity timeout >= 8s\n options.timeout = Math.max(options.freeSocketTimeout * 2, 8000);\n }\n\n // support humanize format\n options.timeout = ms(options.timeout);\n options.freeSocketTimeout = ms(options.freeSocketTimeout);\n options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0;\n\n super(options);\n\n this[CURRENT_ID] = 0;\n\n // create socket success counter\n this.createSocketCount = 0;\n this.createSocketCountLastCheck = 0;\n\n this.createSocketErrorCount = 0;\n this.createSocketErrorCountLastCheck = 0;\n\n this.closeSocketCount = 0;\n this.closeSocketCountLastCheck = 0;\n\n // socket error event count\n this.errorSocketCount = 0;\n this.errorSocketCountLastCheck = 0;\n\n // request finished counter\n this.requestCount = 0;\n this.requestCountLastCheck = 0;\n\n // including free socket timeout counter\n this.timeoutSocketCount = 0;\n this.timeoutSocketCountLastCheck = 0;\n\n this.on('free', socket => {\n // https://github.com/nodejs/node/pull/32000\n // Node.js native agent will check socket timeout eqs agent.options.timeout.\n // Use the ttl or freeSocketTimeout to overwrite.\n const timeout = this.calcSocketTimeout(socket);\n if (timeout > 0 && socket.timeout !== timeout) {\n socket.setTimeout(timeout);\n }\n });\n }\n\n get freeSocketKeepAliveTimeout() {\n deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead');\n return this.options.freeSocketTimeout;\n }\n\n get timeout() {\n deprecate('agent.timeout is deprecated, please use agent.options.timeout instead');\n return this.options.timeout;\n }\n\n get socketActiveTTL() {\n deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead');\n return this.options.socketActiveTTL;\n }\n\n calcSocketTimeout(socket) {\n /**\n * return <= 0: should free socket\n * return > 0: should update socket timeout\n * return undefined: not find custom timeout\n */\n let freeSocketTimeout = this.options.freeSocketTimeout;\n const socketActiveTTL = this.options.socketActiveTTL;\n if (socketActiveTTL) {\n // check socketActiveTTL\n const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME];\n const diff = socketActiveTTL - aliveTime;\n if (diff <= 0) {\n return diff;\n }\n if (freeSocketTimeout && diff < freeSocketTimeout) {\n freeSocketTimeout = diff;\n }\n }\n // set freeSocketTimeout\n if (freeSocketTimeout) {\n // set free keepalive timer\n // try to use socket custom freeSocketTimeout first, support headers['keep-alive']\n // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498\n const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout;\n return customFreeSocketTimeout || freeSocketTimeout;\n }\n }\n\n keepSocketAlive(socket) {\n const result = super.keepSocketAlive(socket);\n // should not keepAlive, do nothing\n if (!result) return result;\n\n const customTimeout = this.calcSocketTimeout(socket);\n if (typeof customTimeout === 'undefined') {\n return true;\n }\n if (customTimeout <= 0) {\n debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout);\n return false;\n }\n if (socket.timeout !== customTimeout) {\n socket.setTimeout(customTimeout);\n }\n return true;\n }\n\n // only call on addRequest\n reuseSocket(...args) {\n // reuseSocket(socket, req)\n super.reuseSocket(...args);\n const socket = args[0];\n const req = args[1];\n req.reusedSocket = true;\n const agentTimeout = this.options.timeout;\n if (getSocketTimeout(socket) !== agentTimeout) {\n // reset timeout before use\n socket.setTimeout(agentTimeout);\n debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout);\n }\n socket[SOCKET_REQUEST_COUNT]++;\n debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],\n getSocketTimeout(socket));\n }\n\n [CREATE_ID]() {\n const id = this[CURRENT_ID]++;\n if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0;\n return id;\n }\n\n [INIT_SOCKET](socket, options) {\n // bugfix here.\n // https on node 8, 10 won't set agent.options.timeout by default\n // TODO: need to fix on node itself\n if (options.timeout) {\n const timeout = getSocketTimeout(socket);\n if (!timeout) {\n socket.setTimeout(options.timeout);\n }\n }\n\n if (this.options.keepAlive) {\n // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/\n // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html\n socket.setNoDelay(true);\n }\n this.createSocketCount++;\n if (this.options.socketActiveTTL) {\n socket[SOCKET_CREATED_TIME] = Date.now();\n }\n // don't show the hole '-----BEGIN CERTIFICATE----' key string\n socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0];\n socket[SOCKET_REQUEST_COUNT] = 1;\n socket[SOCKET_REQUEST_FINISHED_COUNT] = 0;\n installListeners(this, socket, options);\n }\n\n createConnection(options, oncreate) {\n let called = false;\n const onNewCreate = (err, socket) => {\n if (called) return;\n called = true;\n\n if (err) {\n this.createSocketErrorCount++;\n return oncreate(err);\n }\n this[INIT_SOCKET](socket, options);\n oncreate(err, socket);\n };\n\n const newSocket = super.createConnection(options, onNewCreate);\n if (newSocket) onNewCreate(null, newSocket);\n return newSocket;\n }\n\n get statusChanged() {\n const changed = this.createSocketCount !== this.createSocketCountLastCheck ||\n this.createSocketErrorCount !== this.createSocketErrorCountLastCheck ||\n this.closeSocketCount !== this.closeSocketCountLastCheck ||\n this.errorSocketCount !== this.errorSocketCountLastCheck ||\n this.timeoutSocketCount !== this.timeoutSocketCountLastCheck ||\n this.requestCount !== this.requestCountLastCheck;\n if (changed) {\n this.createSocketCountLastCheck = this.createSocketCount;\n this.createSocketErrorCountLastCheck = this.createSocketErrorCount;\n this.closeSocketCountLastCheck = this.closeSocketCount;\n this.errorSocketCountLastCheck = this.errorSocketCount;\n this.timeoutSocketCountLastCheck = this.timeoutSocketCount;\n this.requestCountLastCheck = this.requestCount;\n }\n return changed;\n }\n\n getCurrentStatus() {\n return {\n createSocketCount: this.createSocketCount,\n createSocketErrorCount: this.createSocketErrorCount,\n closeSocketCount: this.closeSocketCount,\n errorSocketCount: this.errorSocketCount,\n timeoutSocketCount: this.timeoutSocketCount,\n requestCount: this.requestCount,\n freeSockets: inspect(this.freeSockets),\n sockets: inspect(this.sockets),\n requests: inspect(this.requests),\n };\n }\n}\n\n// node 8 don't has timeout attribute on socket\n// https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408\nfunction getSocketTimeout(socket) {\n return socket.timeout || socket._idleTimeout;\n}\n\nfunction installListeners(agent, socket, options) {\n debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket));\n\n // listener socket events: close, timeout, error, free\n function onFree() {\n // create and socket.emit('free') logic\n // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311\n // no req on the socket, it should be the new socket\n if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return;\n\n socket[SOCKET_REQUEST_FINISHED_COUNT]++;\n agent.requestCount++;\n debug('%s(requests: %s, finished: %s) free',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);\n\n // should reuse on pedding requests?\n const name = agent.getName(options);\n if (socket.writable && agent.requests[name] && agent.requests[name].length) {\n // will be reuse on agent free listener\n socket[SOCKET_REQUEST_COUNT]++;\n debug('%s(requests: %s, finished: %s) will be reuse on agent free event',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);\n }\n }\n socket.on('free', onFree);\n\n function onClose(isError) {\n debug('%s(requests: %s, finished: %s) close, isError: %s',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError);\n agent.closeSocketCount++;\n }\n socket.on('close', onClose);\n\n // start socket timeout handler\n function onTimeout() {\n // onTimeout and emitRequestTimeout(_http_client.js)\n // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711\n const listenerCount = socket.listeners('timeout').length;\n // node <= 10, default listenerCount is 1, onTimeout\n // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout\n // node >= 13, default listenerCount is 3, onTimeout,\n // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333)\n // and emitRequestTimeout\n const timeout = getSocketTimeout(socket);\n const req = socket._httpMessage;\n const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0;\n debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],\n timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount);\n if (debug.enabled) {\n debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', '));\n }\n agent.timeoutSocketCount++;\n const name = agent.getName(options);\n if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) {\n // free socket timeout, destroy quietly\n socket.destroy();\n // Remove it from freeSockets list immediately to prevent new requests\n // from being sent through this socket.\n agent.removeSocket(socket, options);\n debug('%s is free, destroy quietly', socket[SOCKET_NAME]);\n } else {\n // if there is no any request socket timeout handler,\n // agent need to handle socket timeout itself.\n //\n // custom request socket timeout handle logic must follow these rules:\n // 1. Destroy socket first\n // 2. Must emit socket 'agentRemove' event tell agent remove socket\n // from freeSockets list immediately.\n // Otherise you may be get 'socket hang up' error when reuse\n // free socket and timeout happen in the same time.\n if (reqTimeoutListenerCount === 0) {\n const error = new Error('Socket timeout');\n error.code = 'ERR_SOCKET_TIMEOUT';\n error.timeout = timeout;\n // must manually call socket.end() or socket.destroy() to end the connection.\n // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback\n socket.destroy(error);\n agent.removeSocket(socket, options);\n debug('%s destroy with timeout error', socket[SOCKET_NAME]);\n }\n }\n }\n socket.on('timeout', onTimeout);\n\n function onError(err) {\n const listenerCount = socket.listeners('error').length;\n debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s',\n socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT],\n err, listenerCount);\n agent.errorSocketCount++;\n if (listenerCount === 1) {\n // if socket don't contain error event handler, don't catch it, emit it again\n debug('%s emit uncaught error event', socket[SOCKET_NAME]);\n socket.removeListener('error', onError);\n socket.emit('error', err);\n }\n }\n socket.on('error', onError);\n\n function onRemove() {\n debug('%s(requests: %s, finished: %s) agentRemove',\n socket[SOCKET_NAME],\n socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]);\n // We need this function for cases like HTTP 'upgrade'\n // (defined by WebSockets) where we need to remove a socket from the\n // pool because it'll be locked up indefinitely\n socket.removeListener('close', onClose);\n socket.removeListener('error', onError);\n socket.removeListener('free', onFree);\n socket.removeListener('timeout', onTimeout);\n socket.removeListener('agentRemove', onRemove);\n }\n socket.on('agentRemove', onRemove);\n}\n\nmodule.exports = Agent;\n\nfunction inspect(obj) {\n const res = {};\n for (const key in obj) {\n res[key] = obj[key].length;\n }\n return res;\n}\n","'use strict';\n\nconst OriginalHttpsAgent = require('https').Agent;\nconst HttpAgent = require('./agent');\nconst {\n INIT_SOCKET,\n CREATE_HTTPS_CONNECTION,\n} = require('./constants');\n\nclass HttpsAgent extends HttpAgent {\n constructor(options) {\n super(options);\n\n this.defaultPort = 443;\n this.protocol = 'https:';\n this.maxCachedSessions = this.options.maxCachedSessions;\n /* istanbul ignore next */\n if (this.maxCachedSessions === undefined) {\n this.maxCachedSessions = 100;\n }\n\n this._sessionCache = {\n map: {},\n list: [],\n };\n }\n\n createConnection(options, oncreate) {\n const socket = this[CREATE_HTTPS_CONNECTION](options, oncreate);\n this[INIT_SOCKET](socket, options);\n return socket;\n }\n}\n\n// https://github.com/nodejs/node/blob/master/lib/https.js#L89\nHttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;\n\n[\n 'getName',\n '_getSession',\n '_cacheSession',\n // https://github.com/nodejs/node/pull/4982\n '_evictSession',\n].forEach(function(method) {\n /* istanbul ignore next */\n if (typeof OriginalHttpsAgent.prototype[method] === 'function') {\n HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method];\n }\n});\n\nmodule.exports = HttpsAgent;\n","'use strict';\n\nconst HttpAgent = require('./lib/agent');\nmodule.exports = HttpAgent;\nmodule.exports.HttpAgent = HttpAgent;\nmodule.exports.HttpsAgent = require('./lib/https_agent');\nmodule.exports.constants = require('./lib/constants');\n","/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap<Event, PrivateData>}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap<Object, Function>}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap<object, Map<string, ListenerNode>>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map<string, ListenerNode>} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n","import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget<Events, EventAttributes> {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap<AbortSignal, boolean>()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap<AbortController, AbortSignal>()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n","import type { Format } from './types';\n\nexport const default_format: Format = 'RFC3986';\nexport const formatters: Record<Format, (str: PropertyKey) => string> = {\n RFC1738: (v: PropertyKey) => String(v).replace(/%20/g, '+'),\n RFC3986: (v: PropertyKey) => String(v),\n};\nexport const RFC1738 = 'RFC1738';\nexport const RFC3986 = 'RFC3986';\n","import { RFC1738 } from './formats';\nimport type { DefaultEncoder, Format } from './types';\n\nconst has = Object.prototype.hasOwnProperty;\nconst is_array = Array.isArray;\n\nconst hex_table = (() => {\n const array = [];\n for (let i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n\n return array;\n})();\n\nfunction compact_queue<T extends Record<string, any>>(queue: Array<{ obj: T; prop: string }>) {\n while (queue.length > 1) {\n const item = queue.pop();\n if (!item) continue;\n\n const obj = item.obj[item.prop];\n\n if (is_array(obj)) {\n const compacted: unknown[] = [];\n\n for (let j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n\n // @ts-ignore\n item.obj[item.prop] = compacted;\n }\n }\n}\n\nfunction array_to_object(source: any[], options: { plainObjects: boolean }) {\n const obj = options && options.plainObjects ? Object.create(null) : {};\n for (let i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n\n return obj;\n}\n\nexport function merge(\n target: any,\n source: any,\n options: { plainObjects?: boolean; allowPrototypes?: boolean } = {},\n) {\n if (!source) {\n return target;\n }\n\n if (typeof source !== 'object') {\n if (is_array(target)) {\n target.push(source);\n } else if (target && typeof target === 'object') {\n if (\n (options && (options.plainObjects || options.allowPrototypes)) ||\n !has.call(Object.prototype, source)\n ) {\n target[source] = true;\n }\n } else {\n return [target, source];\n }\n\n return target;\n }\n\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n\n let mergeTarget = target;\n if (is_array(target) && !is_array(source)) {\n // @ts-ignore\n mergeTarget = array_to_object(target, options);\n }\n\n if (is_array(target) && is_array(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n const targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n } else {\n target.push(item);\n }\n } else {\n target[i] = item;\n }\n });\n return target;\n }\n\n return Object.keys(source).reduce(function (acc, key) {\n const value = source[key];\n\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n } else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n}\n\nexport function assign_single_source(target: any, source: any) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n}\n\nexport function decode(str: string, _: any, charset: string) {\n const strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n } catch (e) {\n return strWithoutPlus;\n }\n}\n\nconst limit = 1024;\n\nexport const encode: (\n str: any,\n defaultEncoder: DefaultEncoder,\n charset: string,\n type: 'key' | 'value',\n format: Format,\n) => string = (str, _defaultEncoder, charset, _kind, format: Format) => {\n // This code was originally written by Brian White for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n\n let string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n } else if (typeof str !== 'string') {\n string = String(str);\n }\n\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n\n let out = '';\n for (let j = 0; j < string.length; j += limit) {\n const segment = string.length >= limit ? string.slice(j, j + limit) : string;\n const arr = [];\n\n for (let i = 0; i < segment.length; ++i) {\n let c = segment.charCodeAt(i);\n if (\n c === 0x2d || // -\n c === 0x2e || // .\n c === 0x5f || // _\n c === 0x7e || // ~\n (c >= 0x30 && c <= 0x39) || // 0-9\n (c >= 0x41 && c <= 0x5a) || // a-z\n (c >= 0x61 && c <= 0x7a) || // A-Z\n (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n arr[arr.length] = segment.charAt(i);\n continue;\n }\n\n if (c < 0x80) {\n arr[arr.length] = hex_table[c];\n continue;\n }\n\n if (c < 0x800) {\n arr[arr.length] = hex_table[0xc0 | (c >> 6)]! + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n\n if (c < 0xd800 || c >= 0xe000) {\n arr[arr.length] =\n hex_table[0xe0 | (c >> 12)]! + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n\n i += 1;\n c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff));\n\n arr[arr.length] =\n hex_table[0xf0 | (c >> 18)]! +\n hex_table[0x80 | ((c >> 12) & 0x3f)] +\n hex_table[0x80 | ((c >> 6) & 0x3f)] +\n hex_table[0x80 | (c & 0x3f)];\n }\n\n out += arr.join('');\n }\n\n return out;\n};\n\nexport function compact(value: any) {\n const queue = [{ obj: { o: value }, prop: 'o' }];\n const refs = [];\n\n for (let i = 0; i < queue.length; ++i) {\n const item = queue[i];\n // @ts-ignore\n const obj = item.obj[item.prop];\n\n const keys = Object.keys(obj);\n for (let j = 0; j < keys.length; ++j) {\n const key = keys[j]!;\n const val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n\n compact_queue(queue);\n\n return value;\n}\n\nexport function is_regexp(obj: any) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\n\nexport function is_buffer(obj: any) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n}\n\nexport function combine(a: any, b: any) {\n return [].concat(a, b);\n}\n\nexport function maybe_map<T>(val: T[], fn: (v: T) => T) {\n if (is_array(val)) {\n const mapped = [];\n for (let i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]!));\n }\n return mapped;\n }\n return fn(val);\n}\n","import { encode, is_buffer, maybe_map } from './utils';\nimport { default_format, formatters } from './formats';\nimport type { NonNullableProperties, StringifyOptions } from './types';\n\nconst has = Object.prototype.hasOwnProperty;\n\nconst array_prefix_generators = {\n brackets(prefix: PropertyKey) {\n return String(prefix) + '[]';\n },\n comma: 'comma',\n indices(prefix: PropertyKey, key: string) {\n return String(prefix) + '[' + key + ']';\n },\n repeat(prefix: PropertyKey) {\n return String(prefix);\n },\n};\n\nconst is_array = Array.isArray;\nconst push = Array.prototype.push;\nconst push_to_array = function (arr: any[], value_or_array: any) {\n push.apply(arr, is_array(value_or_array) ? value_or_array : [value_or_array]);\n};\n\nconst to_ISO = Date.prototype.toISOString;\n\nconst defaults = {\n addQueryPrefix: false,\n allowDots: false,\n allowEmptyArrays: false,\n arrayFormat: 'indices',\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encodeDotInKeys: false,\n encoder: encode,\n encodeValuesOnly: false,\n format: default_format,\n formatter: formatters[default_format],\n /** @deprecated */\n indices: false,\n serializeDate(date) {\n return to_ISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false,\n} as NonNullableProperties<StringifyOptions & { formatter: (typeof formatters)['RFC1738'] }>;\n\nfunction is_non_nullish_primitive(v: unknown): v is string | number | boolean | symbol | bigint {\n return (\n typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'symbol' ||\n typeof v === 'bigint'\n );\n}\n\nconst sentinel = {};\n\nfunction inner_stringify(\n object: any,\n prefix: PropertyKey,\n generateArrayPrefix: StringifyOptions['arrayFormat'] | ((prefix: string, key: string) => string),\n commaRoundTrip: boolean,\n allowEmptyArrays: boolean,\n strictNullHandling: boolean,\n skipNulls: boolean,\n encodeDotInKeys: boolean,\n encoder: StringifyOptions['encoder'],\n filter: StringifyOptions['filter'],\n sort: StringifyOptions['sort'],\n allowDots: StringifyOptions['allowDots'],\n serializeDate: StringifyOptions['serializeDate'],\n format: StringifyOptions['format'],\n formatter: StringifyOptions['formatter'],\n encodeValuesOnly: boolean,\n charset: StringifyOptions['charset'],\n sideChannel: WeakMap<any, any>,\n) {\n let obj = object;\n\n let tmp_sc = sideChannel;\n let step = 0;\n let find_flag = false;\n while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {\n // Where object last appeared in the ref tree\n const pos = tmp_sc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n } else {\n find_flag = true; // Break while\n }\n }\n if (typeof tmp_sc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n } else if (obj instanceof Date) {\n obj = serializeDate?.(obj);\n } else if (generateArrayPrefix === 'comma' && is_array(obj)) {\n obj = maybe_map(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate?.(value);\n }\n return value;\n });\n }\n\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ?\n // @ts-expect-error\n encoder(prefix, defaults.encoder, charset, 'key', format)\n : prefix;\n }\n\n obj = '';\n }\n\n if (is_non_nullish_primitive(obj) || is_buffer(obj)) {\n if (encoder) {\n const key_value =\n encodeValuesOnly ? prefix\n // @ts-expect-error\n : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [\n formatter?.(key_value) +\n '=' +\n // @ts-expect-error\n formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)),\n ];\n }\n return [formatter?.(prefix) + '=' + formatter?.(String(obj))];\n }\n\n const values: string[] = [];\n\n if (typeof obj === 'undefined') {\n return values;\n }\n\n let obj_keys;\n if (generateArrayPrefix === 'comma' && is_array(obj)) {\n // we need to join elements in\n if (encodeValuesOnly && encoder) {\n // @ts-expect-error values only\n obj = maybe_map(obj, encoder);\n }\n obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n } else if (is_array(filter)) {\n obj_keys = filter;\n } else {\n const keys = Object.keys(obj);\n obj_keys = sort ? keys.sort(sort) : keys;\n }\n\n const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\\./g, '%2E') : String(prefix);\n\n const adjusted_prefix =\n commaRoundTrip && is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix;\n\n if (allowEmptyArrays && is_array(obj) && obj.length === 0) {\n return adjusted_prefix + '[]';\n }\n\n for (let j = 0; j < obj_keys.length; ++j) {\n const key = obj_keys[j];\n const value =\n // @ts-ignore\n typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key as any];\n\n if (skipNulls && value === null) {\n continue;\n }\n\n // @ts-ignore\n const encoded_key = allowDots && encodeDotInKeys ? (key as any).replace(/\\./g, '%2E') : key;\n const key_prefix =\n is_array(obj) ?\n typeof generateArrayPrefix === 'function' ?\n generateArrayPrefix(adjusted_prefix, encoded_key)\n : adjusted_prefix\n : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']');\n\n sideChannel.set(object, step);\n const valueSideChannel = new WeakMap();\n valueSideChannel.set(sentinel, sideChannel);\n push_to_array(\n values,\n inner_stringify(\n value,\n key_prefix,\n generateArrayPrefix,\n commaRoundTrip,\n allowEmptyArrays,\n strictNullHandling,\n skipNulls,\n encodeDotInKeys,\n // @ts-ignore\n generateArrayPrefix === 'comma' && encodeValuesOnly && is_array(obj) ? null : encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset,\n valueSideChannel,\n ),\n );\n }\n\n return values;\n}\n\nfunction normalize_stringify_options(\n opts: StringifyOptions = defaults,\n): NonNullableProperties<Omit<StringifyOptions, 'indices'>> & { indices?: boolean } {\n if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {\n throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');\n }\n\n if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {\n throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');\n }\n\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n\n const charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n\n let format = default_format;\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n const formatter = formatters[format];\n\n let filter = defaults.filter;\n if (typeof opts.filter === 'function' || is_array(opts.filter)) {\n filter = opts.filter;\n }\n\n let arrayFormat: StringifyOptions['arrayFormat'];\n if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {\n arrayFormat = opts.arrayFormat;\n } else if ('indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n } else {\n arrayFormat = defaults.arrayFormat;\n }\n\n if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n\n const allowDots =\n typeof opts.allowDots === 'undefined' ?\n !!opts.encodeDotInKeys === true ?\n true\n : defaults.allowDots\n : !!opts.allowDots;\n\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n // @ts-ignore\n allowDots: allowDots,\n allowEmptyArrays:\n typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,\n arrayFormat: arrayFormat,\n charset: charset,\n charsetSentinel:\n typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n commaRoundTrip: !!opts.commaRoundTrip,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encodeDotInKeys:\n typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly:\n typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n // @ts-ignore\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling:\n typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,\n };\n}\n\nexport function stringify(object: any, opts: StringifyOptions = {}) {\n let obj = object;\n const options = normalize_stringify_options(opts);\n\n let obj_keys: PropertyKey[] | undefined;\n let filter;\n\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n } else if (is_array(options.filter)) {\n filter = options.filter;\n obj_keys = filter;\n }\n\n const keys: string[] = [];\n\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n\n const generateArrayPrefix = array_prefix_generators[options.arrayFormat];\n const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;\n\n if (!obj_keys) {\n obj_keys = Object.keys(obj);\n }\n\n if (options.sort) {\n obj_keys.sort(options.sort);\n }\n\n const sideChannel = new WeakMap();\n for (let i = 0; i < obj_keys.length; ++i) {\n const key = obj_keys[i]!;\n\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n push_to_array(\n keys,\n inner_stringify(\n obj[key],\n key,\n // @ts-expect-error\n generateArrayPrefix,\n commaRoundTrip,\n options.allowEmptyArrays,\n options.strictNullHandling,\n options.skipNulls,\n options.encodeDotInKeys,\n options.encode ? options.encoder : null,\n options.filter,\n options.sort,\n options.allowDots,\n options.serializeDate,\n options.format,\n options.formatter,\n options.encodeValuesOnly,\n options.charset,\n sideChannel,\n ),\n );\n }\n\n const joined = keys.join(options.delimiter);\n let prefix = options.addQueryPrefix === true ? '?' : '';\n\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n } else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n\n return joined.length > 0 ? prefix + joined : '';\n}\n","export const VERSION = '4.104.0'; // x-release-please-version\n","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport { type RequestOptions } from '../core';\n\nexport interface Shims {\n kind: string;\n fetch: any;\n Request: any;\n Response: any;\n Headers: any;\n FormData: any;\n Blob: any;\n File: any;\n ReadableStream: any;\n getMultipartRequestOptions: <T = Record<string, unknown>>(\n form: Shims['FormData'],\n opts: RequestOptions<T>,\n ) => Promise<RequestOptions<T>>;\n getDefaultAgent: (url: string) => any;\n fileFromPath:\n | ((path: string, filename?: string, options?: {}) => Promise<Shims['File']>)\n | ((path: string, options?: {}) => Promise<Shims['File']>);\n isFsReadStream: (value: any) => boolean;\n}\n\nexport let auto = false;\nexport let kind: Shims['kind'] | undefined = undefined;\nexport let fetch: Shims['fetch'] | undefined = undefined;\nexport let Request: Shims['Request'] | undefined = undefined;\nexport let Response: Shims['Response'] | undefined = undefined;\nexport let Headers: Shims['Headers'] | undefined = undefined;\nexport let FormData: Shims['FormData'] | undefined = undefined;\nexport let Blob: Shims['Blob'] | undefined = undefined;\nexport let File: Shims['File'] | undefined = undefined;\nexport let ReadableStream: Shims['ReadableStream'] | undefined = undefined;\nexport let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined = undefined;\nexport let getDefaultAgent: Shims['getDefaultAgent'] | undefined = undefined;\nexport let fileFromPath: Shims['fileFromPath'] | undefined = undefined;\nexport let isFsReadStream: Shims['isFsReadStream'] | undefined = undefined;\n\nexport function setShims(shims: Shims, options: { auto: boolean } = { auto: false }) {\n if (auto) {\n throw new Error(\n `you must \\`import 'openai/shims/${shims.kind}'\\` before importing anything else from openai`,\n );\n }\n if (kind) {\n throw new Error(`can't \\`import 'openai/shims/${shims.kind}'\\` after \\`import 'openai/shims/${kind}'\\``);\n }\n auto = options.auto;\n kind = shims.kind;\n fetch = shims.fetch;\n Request = shims.Request;\n Response = shims.Response;\n Headers = shims.Headers;\n FormData = shims.FormData;\n Blob = shims.Blob;\n File = shims.File;\n ReadableStream = shims.ReadableStream;\n getMultipartRequestOptions = shims.getMultipartRequestOptions;\n getDefaultAgent = shims.getDefaultAgent;\n fileFromPath = shims.fileFromPath;\n isFsReadStream = shims.isFsReadStream;\n}\n","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport * as nf from 'node-fetch';\nimport * as fd from 'formdata-node';\nimport { type File, type FilePropertyBag } from 'formdata-node';\nimport KeepAliveAgent from 'agentkeepalive';\nimport { AbortController as AbortControllerPolyfill } from 'abort-controller';\nimport { ReadStream as FsReadStream } from 'node:fs';\nimport { type Agent } from 'node:http';\nimport { FormDataEncoder } from 'form-data-encoder';\nimport { Readable } from 'node:stream';\nimport { type RequestOptions } from '../core';\nimport { MultipartBody } from './MultipartBody';\nimport { type Shims } from './registry';\nimport { ReadableStream } from 'node:stream/web';\n\ntype FileFromPathOptions = Omit<FilePropertyBag, 'lastModified'>;\n\nlet fileFromPathWarned = false;\n\n/**\n * @deprecated use fs.createReadStream('./my/file.txt') instead\n */\nasync function fileFromPath(path: string): Promise<File>;\nasync function fileFromPath(path: string, filename?: string): Promise<File>;\nasync function fileFromPath(path: string, options?: FileFromPathOptions): Promise<File>;\nasync function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise<File>;\nasync function fileFromPath(path: string, ...args: any[]): Promise<File> {\n // this import fails in environments that don't handle export maps correctly, like old versions of Jest\n const { fileFromPath: _fileFromPath } = await import('formdata-node/file-from-path');\n\n if (!fileFromPathWarned) {\n console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`);\n fileFromPathWarned = true;\n }\n // @ts-ignore\n return await _fileFromPath(path, ...args);\n}\n\nconst defaultHttpAgent: Agent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });\nconst defaultHttpsAgent: Agent = new KeepAliveAgent.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });\n\nasync function getMultipartRequestOptions<T = Record<string, unknown>>(\n form: fd.FormData,\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T>> {\n const encoder = new FormDataEncoder(form);\n const readable = Readable.from(encoder);\n const body = new MultipartBody(readable);\n const headers = {\n ...opts.headers,\n ...encoder.headers,\n 'Content-Length': encoder.contentLength,\n };\n\n return { ...opts, body: body as any, headers };\n}\n\nexport function getRuntime(): Shims {\n // Polyfill global object if needed.\n if (typeof AbortController === 'undefined') {\n // @ts-expect-error (the types are subtly different, but compatible in practice)\n globalThis.AbortController = AbortControllerPolyfill;\n }\n return {\n kind: 'node',\n fetch: nf.default,\n Request: nf.Request,\n Response: nf.Response,\n Headers: nf.Headers,\n FormData: fd.FormData,\n Blob: fd.Blob,\n File: fd.File,\n ReadableStream,\n getMultipartRequestOptions,\n getDefaultAgent: (url: string): Agent => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent),\n fileFromPath,\n isFsReadStream: (value: any): value is FsReadStream => value instanceof FsReadStream,\n };\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _FormData_instances, _FormData_entries, _FormData_setEntry;\nimport { inspect } from \"util\";\nimport { File } from \"./File.js\";\nimport { isFile } from \"./isFile.js\";\nimport { isBlob } from \"./isBlob.js\";\nimport { isFunction } from \"./isFunction.js\";\nimport { deprecateConstructorEntries } from \"./deprecateConstructorEntries.js\";\nexport class FormData {\n constructor(entries) {\n _FormData_instances.add(this);\n _FormData_entries.set(this, new Map());\n if (entries) {\n deprecateConstructorEntries();\n entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName));\n }\n }\n static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) {\n return Boolean(value\n && isFunction(value.constructor)\n && value[Symbol.toStringTag] === \"FormData\"\n && isFunction(value.append)\n && isFunction(value.set)\n && isFunction(value.get)\n && isFunction(value.getAll)\n && isFunction(value.has)\n && isFunction(value.delete)\n && isFunction(value.entries)\n && isFunction(value.values)\n && isFunction(value.keys)\n && isFunction(value[Symbol.iterator])\n && isFunction(value.forEach));\n }\n append(name, value, fileName) {\n __classPrivateFieldGet(this, _FormData_instances, \"m\", _FormData_setEntry).call(this, {\n name,\n fileName,\n append: true,\n rawValue: value,\n argsLength: arguments.length\n });\n }\n set(name, value, fileName) {\n __classPrivateFieldGet(this, _FormData_instances, \"m\", _FormData_setEntry).call(this, {\n name,\n fileName,\n append: false,\n rawValue: value,\n argsLength: arguments.length\n });\n }\n get(name) {\n const field = __classPrivateFieldGet(this, _FormData_entries, \"f\").get(String(name));\n if (!field) {\n return null;\n }\n return field[0];\n }\n getAll(name) {\n const field = __classPrivateFieldGet(this, _FormData_entries, \"f\").get(String(name));\n if (!field) {\n return [];\n }\n return field.slice();\n }\n has(name) {\n return __classPrivateFieldGet(this, _FormData_entries, \"f\").has(String(name));\n }\n delete(name) {\n __classPrivateFieldGet(this, _FormData_entries, \"f\").delete(String(name));\n }\n *keys() {\n for (const key of __classPrivateFieldGet(this, _FormData_entries, \"f\").keys()) {\n yield key;\n }\n }\n *entries() {\n for (const name of this.keys()) {\n const values = this.getAll(name);\n for (const value of values) {\n yield [name, value];\n }\n }\n }\n *values() {\n for (const [, value] of this) {\n yield value;\n }\n }\n [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) {\n const methodName = append ? \"append\" : \"set\";\n if (argsLength < 2) {\n throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `\n + `2 arguments required, but only ${argsLength} present.`);\n }\n name = String(name);\n let value;\n if (isFile(rawValue)) {\n value = fileName === undefined\n ? rawValue\n : new File([rawValue], fileName, {\n type: rawValue.type,\n lastModified: rawValue.lastModified\n });\n }\n else if (isBlob(rawValue)) {\n value = new File([rawValue], fileName === undefined ? \"blob\" : fileName, {\n type: rawValue.type\n });\n }\n else if (fileName) {\n throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `\n + \"parameter 2 is not of type 'Blob'.\");\n }\n else {\n value = String(rawValue);\n }\n const values = __classPrivateFieldGet(this, _FormData_entries, \"f\").get(name);\n if (!values) {\n return void __classPrivateFieldGet(this, _FormData_entries, \"f\").set(name, [value]);\n }\n if (!append) {\n return void __classPrivateFieldGet(this, _FormData_entries, \"f\").set(name, [value]);\n }\n values.push(value);\n }, Symbol.iterator)]() {\n return this.entries();\n }\n forEach(callback, thisArg) {\n for (const [name, value] of this) {\n callback.call(thisArg, value, name, this);\n }\n }\n get [Symbol.toStringTag]() {\n return \"FormData\";\n }\n [inspect.custom]() {\n return this[Symbol.toStringTag];\n }\n}\n","import { Blob } from \"./Blob.js\";\nexport const isBlob = (value) => value instanceof Blob;\n","import { deprecate } from \"util\";\nexport const deprecateConstructorEntries = deprecate(() => { }, \"Constructor \\\"entries\\\" argument is not spec-compliant \"\n + \"and will be removed in next major release.\");\n","const alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789\";\nfunction createBoundary() {\n let size = 16;\n let res = \"\";\n while (size--) {\n res += alphabet[(Math.random() * alphabet.length) << 0];\n }\n return res;\n}\nexport default createBoundary;\n","const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase());\nfunction isPlainObject(value) {\n if (getType(value) !== \"object\") {\n return false;\n }\n const pp = Object.getPrototypeOf(value);\n if (pp === null || pp === undefined) {\n return true;\n }\n const Ctor = pp.constructor && pp.constructor.toString();\n return Ctor === Object.toString();\n}\nexport default isPlainObject;\n","const normalizeValue = (value) => String(value)\n .replace(/\\r|\\n/g, (match, i, str) => {\n if ((match === \"\\r\" && str[i + 1] !== \"\\n\")\n || (match === \"\\n\" && str[i - 1] !== \"\\r\")) {\n return \"\\r\\n\";\n }\n return match;\n});\nexport default normalizeValue;\n","const escapeName = (name) => String(name)\n .replace(/\\r/g, \"%0D\")\n .replace(/\\n/g, \"%0A\")\n .replace(/\"/g, \"%22\");\nexport default escapeName;\n","const isFunction = (value) => (typeof value === \"function\");\nexport default isFunction;\n","import isFunction from \"./isFunction.js\";\nexport const isFileLike = (value) => Boolean(value\n && typeof value === \"object\"\n && isFunction(value.constructor)\n && value[Symbol.toStringTag] === \"File\"\n && isFunction(value.stream)\n && value.name != null\n && value.size != null\n && value.lastModified != null);\n","import isFunction from \"./isFunction.js\";\nexport const isFormData = (value) => Boolean(value\n && isFunction(value.constructor)\n && value[Symbol.toStringTag] === \"FormData\"\n && isFunction(value.append)\n && isFunction(value.getAll)\n && isFunction(value.entries)\n && isFunction(value[Symbol.iterator]));\nexport const isFormDataLike = isFormData;\n","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader;\nimport createBoundary from \"./util/createBoundary.js\";\nimport isPlainObject from \"./util/isPlainObject.js\";\nimport normalize from \"./util/normalizeValue.js\";\nimport escape from \"./util/escapeName.js\";\nimport { isFileLike } from \"./util/isFileLike.js\";\nimport { isFormData } from \"./util/isFormData.js\";\nconst defaultOptions = {\n enableAdditionalHeaders: false\n};\nexport class FormDataEncoder {\n constructor(form, boundaryOrOptions, options) {\n _FormDataEncoder_instances.add(this);\n _FormDataEncoder_CRLF.set(this, \"\\r\\n\");\n _FormDataEncoder_CRLF_BYTES.set(this, void 0);\n _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0);\n _FormDataEncoder_DASHES.set(this, \"-\".repeat(2));\n _FormDataEncoder_encoder.set(this, new TextEncoder());\n _FormDataEncoder_footer.set(this, void 0);\n _FormDataEncoder_form.set(this, void 0);\n _FormDataEncoder_options.set(this, void 0);\n if (!isFormData(form)) {\n throw new TypeError(\"Expected first argument to be a FormData instance.\");\n }\n let boundary;\n if (isPlainObject(boundaryOrOptions)) {\n options = boundaryOrOptions;\n }\n else {\n boundary = boundaryOrOptions;\n }\n if (!boundary) {\n boundary = createBoundary();\n }\n if (typeof boundary !== \"string\") {\n throw new TypeError(\"Expected boundary argument to be a string.\");\n }\n if (options && !isPlainObject(options)) {\n throw new TypeError(\"Expected options argument to be an object.\");\n }\n __classPrivateFieldSet(this, _FormDataEncoder_form, form, \"f\");\n __classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, \"f\");\n __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, __classPrivateFieldGet(this, _FormDataEncoder_encoder, \"f\").encode(__classPrivateFieldGet(this, _FormDataEncoder_CRLF, \"f\")), \"f\");\n __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, \"f\").byteLength, \"f\");\n this.boundary = `form-data-boundary-${boundary}`;\n this.contentType = `multipart/form-data; boundary=${this.boundary}`;\n __classPrivateFieldSet(this, _FormDataEncoder_footer, __classPrivateFieldGet(this, _FormDataEncoder_encoder, \"f\").encode(`${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, \"f\")}${this.boundary}${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, \"f\")}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, \"f\").repeat(2)}`), \"f\");\n this.contentLength = String(this.getContentLength());\n this.headers = Object.freeze({\n \"Content-Type\": this.contentType,\n \"Content-Length\": this.contentLength\n });\n Object.defineProperties(this, {\n boundary: { writable: false, configurable: false },\n contentType: { writable: false, configurable: false },\n contentLength: { writable: false, configurable: false },\n headers: { writable: false, configurable: false }\n });\n }\n getContentLength() {\n let length = 0;\n for (const [name, raw] of __classPrivateFieldGet(this, _FormDataEncoder_form, \"f\")) {\n const value = isFileLike(raw) ? raw : __classPrivateFieldGet(this, _FormDataEncoder_encoder, \"f\").encode(normalize(raw));\n length += __classPrivateFieldGet(this, _FormDataEncoder_instances, \"m\", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength;\n length += isFileLike(value) ? value.size : value.byteLength;\n length += __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, \"f\");\n }\n return length + __classPrivateFieldGet(this, _FormDataEncoder_footer, \"f\").byteLength;\n }\n *values() {\n for (const [name, raw] of __classPrivateFieldGet(this, _FormDataEncoder_form, \"f\").entries()) {\n const value = isFileLike(raw) ? raw : __classPrivateFieldGet(this, _FormDataEncoder_encoder, \"f\").encode(normalize(raw));\n yield __classPrivateFieldGet(this, _FormDataEncoder_instances, \"m\", _FormDataEncoder_getFieldHeader).call(this, name, value);\n yield value;\n yield __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, \"f\");\n }\n yield __classPrivateFieldGet(this, _FormDataEncoder_footer, \"f\");\n }\n async *encode() {\n for (const part of this.values()) {\n if (isFileLike(part)) {\n yield* part.stream();\n }\n else {\n yield part;\n }\n }\n }\n [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) {\n let header = \"\";\n header += `${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, \"f\")}${this.boundary}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, \"f\")}`;\n header += `Content-Disposition: form-data; name=\"${escape(name)}\"`;\n if (isFileLike(value)) {\n header += `; filename=\"${escape(value.name)}\"${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, \"f\")}`;\n header += `Content-Type: ${value.type || \"application/octet-stream\"}`;\n }\n if (__classPrivateFieldGet(this, _FormDataEncoder_options, \"f\").enableAdditionalHeaders === true) {\n header += `${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, \"f\")}Content-Length: ${isFileLike(value) ? value.size : value.byteLength}`;\n }\n return __classPrivateFieldGet(this, _FormDataEncoder_encoder, \"f\").encode(`${header}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, \"f\").repeat(2)}`);\n }, Symbol.iterator)]() {\n return this.values();\n }\n [Symbol.asyncIterator]() {\n return this.encode();\n }\n}\nexport const Encoder = FormDataEncoder;\n","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nexport class MultipartBody {\n constructor(public body: any) {}\n get [Symbol.toStringTag](): string {\n return 'MultipartBody';\n }\n}\n","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport * as shims from './registry.mjs';\nimport * as auto from 'openai/_shims/auto/runtime';\nexport const init = () => {\n if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });\n};\nexport * from './registry.mjs';\n\ninit();\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { castToError, Headers } from './core';\n\nexport class OpenAIError extends Error {}\n\nexport class APIError<\n TStatus extends number | undefined = number | undefined,\n THeaders extends Headers | undefined = Headers | undefined,\n TError extends Object | undefined = Object | undefined,\n> extends OpenAIError {\n /** HTTP status for the response that caused the error */\n readonly status: TStatus;\n /** HTTP headers for the response that caused the error */\n readonly headers: THeaders;\n /** JSON body of the response that caused the error */\n readonly error: TError;\n\n readonly code: string | null | undefined;\n readonly param: string | null | undefined;\n readonly type: string | undefined;\n\n readonly request_id: string | null | undefined;\n\n constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.request_id = headers?.['x-request-id'];\n this.error = error;\n\n const data = error as Record<string, any>;\n this.code = data?.['code'];\n this.param = data?.['param'];\n this.type = data?.['type'];\n }\n\n private static makeMessage(status: number | undefined, error: any, message: string | undefined) {\n const msg =\n error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n\n static generate(\n status: number | undefined,\n errorResponse: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n\n const error = (errorResponse as Record<string, any>)?.['error'];\n\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n\n return new APIError(status, error, message, headers);\n }\n}\n\nexport class APIUserAbortError extends APIError<undefined, undefined, undefined> {\n constructor({ message }: { message?: string } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\n\nexport class APIConnectionError extends APIError<undefined, undefined, undefined> {\n constructor({ message, cause }: { message?: string | undefined; cause?: Error | undefined }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause) this.cause = cause;\n }\n}\n\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message }: { message?: string } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\n\nexport class BadRequestError extends APIError<400, Headers> {}\n\nexport class AuthenticationError extends APIError<401, Headers> {}\n\nexport class PermissionDeniedError extends APIError<403, Headers> {}\n\nexport class NotFoundError extends APIError<404, Headers> {}\n\nexport class ConflictError extends APIError<409, Headers> {}\n\nexport class UnprocessableEntityError extends APIError<422, Headers> {}\n\nexport class RateLimitError extends APIError<429, Headers> {}\n\nexport class InternalServerError extends APIError<number, Headers> {}\n\nexport class LengthFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the length limit was reached`);\n }\n}\n\nexport class ContentFilterFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the request was rejected by the content filter`);\n }\n}\n","import { OpenAIError } from '../../error';\n\nexport type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;\n\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n // prettier-ignore\n static NEWLINE_CHARS = new Set(['\\n', '\\r']);\n static NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n\n buffer: Uint8Array;\n #carriageReturnIndex: number | null;\n textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either \"dom\" or \"node\" types.\n\n constructor() {\n this.buffer = new Uint8Array();\n this.#carriageReturnIndex = null;\n }\n\n decode(chunk: Bytes): string[] {\n if (chunk == null) {\n return [];\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n\n let newData = new Uint8Array(this.buffer.length + binaryChunk.length);\n newData.set(this.buffer);\n newData.set(binaryChunk, this.buffer.length);\n this.buffer = newData;\n\n const lines: string[] = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(this.buffer, this.#carriageReturnIndex)) != null) {\n if (patternIndex.carriage && this.#carriageReturnIndex == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n this.#carriageReturnIndex = patternIndex.index;\n continue;\n }\n\n // we got double \\r or \\rtext\\n\n if (\n this.#carriageReturnIndex != null &&\n (patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage)\n ) {\n lines.push(this.decodeText(this.buffer.slice(0, this.#carriageReturnIndex - 1)));\n this.buffer = this.buffer.slice(this.#carriageReturnIndex);\n this.#carriageReturnIndex = null;\n continue;\n }\n\n const endIndex =\n this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n\n const line = this.decodeText(this.buffer.slice(0, endIndex));\n lines.push(line);\n\n this.buffer = this.buffer.slice(patternIndex.index);\n this.#carriageReturnIndex = null;\n }\n\n return lines;\n }\n\n decodeText(bytes: Bytes): string {\n if (bytes == null) return '';\n if (typeof bytes === 'string') return bytes;\n\n // Node:\n if (typeof Buffer !== 'undefined') {\n if (bytes instanceof Buffer) {\n return bytes.toString();\n }\n if (bytes instanceof Uint8Array) {\n return Buffer.from(bytes).toString();\n }\n\n throw new OpenAIError(\n `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global \"Buffer\" defined, which this library assumes to be Node. Please report this error.`,\n );\n }\n\n // Browser\n if (typeof TextDecoder !== 'undefined') {\n if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {\n this.textDecoder ??= new TextDecoder('utf8');\n return this.textDecoder.decode(bytes);\n }\n\n throw new OpenAIError(\n `Unexpected: received non-Uint8Array/ArrayBuffer (${\n (bytes as any).constructor.name\n }) in a web platform. Please report this error.`,\n );\n }\n\n throw new OpenAIError(\n `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`,\n );\n }\n\n flush(): string[] {\n if (!this.buffer.length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(\n buffer: Uint8Array,\n startIndex: number | null,\n): { preceding: number; index: number; carriage: boolean } | null {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n\n return null;\n}\n\nexport function findDoubleNewlineIndex(buffer: Uint8Array): number {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = 0; i < buffer.length - 1; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (\n buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline\n ) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n\n return -1;\n}\n","/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {\n if (stream[Symbol.asyncIterator]) return stream;\n\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done) reader.releaseLock(); // release lock when stream becomes closed\n return result;\n } catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n","import { ReadableStream, type Response } from './_shims/index';\nimport { OpenAIError } from './error';\nimport { findDoubleNewlineIndex, LineDecoder } from './internal/decoders/line';\nimport { ReadableStreamToAsyncIterable } from './internal/stream-utils';\n\nimport { createResponseHeaders } from './core';\nimport { APIError } from './error';\n\ntype Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;\n\nexport type ServerSentEvent = {\n event: string | null;\n data: string;\n raw: string[];\n};\n\nexport class Stream<Item> implements AsyncIterable<Item> {\n controller: AbortController;\n\n constructor(\n private iterator: () => AsyncIterator<Item>,\n controller: AbortController,\n ) {\n this.controller = controller;\n }\n\n static fromSSEResponse<Item>(response: Response, controller: AbortController): Stream<Item> {\n let consumed = false;\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (done) continue;\n\n if (sse.data.startsWith('[DONE]')) {\n done = true;\n continue;\n }\n\n if (\n sse.event === null ||\n sse.event.startsWith('response.') ||\n sse.event.startsWith('transcript.')\n ) {\n let data;\n\n try {\n data = JSON.parse(sse.data);\n } catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n\n if (data && data.error) {\n throw new APIError(undefined, data.error, undefined, createResponseHeaders(response.headers));\n }\n\n yield data;\n } else {\n let data;\n try {\n data = JSON.parse(sse.data);\n } catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n // TODO: Is this where the error should be thrown?\n if (sse.event == 'error') {\n throw new APIError(undefined, data.error, data.message, undefined);\n }\n yield { event: sse.event, data: data } as any;\n }\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError') return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller);\n }\n\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController): Stream<Item> {\n let consumed = false;\n\n async function* iterLines(): AsyncGenerator<string, void, unknown> {\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done) continue;\n if (line) yield JSON.parse(line);\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError') return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Item> {\n return this.iterator();\n }\n\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee(): [Stream<Item>, Stream<Item>] {\n const left: Array<Promise<IteratorResult<Item>>> = [];\n const right: Array<Promise<IteratorResult<Item>>> = [];\n const iterator = this.iterator();\n\n const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift()!;\n },\n };\n };\n\n return [\n new Stream(() => teeIterator(left), this.controller),\n new Stream(() => teeIterator(right), this.controller),\n ];\n }\n\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream(): ReadableStream {\n const self = this;\n let iter: AsyncIterator<Item>;\n const encoder = new TextEncoder();\n\n return new ReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl: any) {\n try {\n const { value, done } = await iter.next();\n if (done) return ctrl.close();\n\n const bytes = encoder.encode(JSON.stringify(value) + '\\n');\n\n ctrl.enqueue(bytes);\n } catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\n\nexport async function* _iterSSEMessages(\n response: Response,\n controller: AbortController,\n): AsyncGenerator<ServerSentEvent, void, unknown> {\n if (!response.body) {\n controller.abort();\n throw new OpenAIError(`Attempted to iterate over a response with no body`);\n }\n\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n}\n\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {\n let data = new Uint8Array();\n\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n\n if (data.length > 0) {\n yield data;\n }\n}\n\nclass SSEDecoder {\n private data: string[];\n private event: string | null;\n private chunks: string[];\n\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n\n decode(line: string) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length) return null;\n\n const sse: ServerSentEvent = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n\n this.event = null;\n this.data = [];\n this.chunks = [];\n\n return sse;\n }\n\n this.chunks.push(line);\n\n if (line.startsWith(':')) {\n return null;\n }\n\n let [fieldname, _, value] = partition(line, ':');\n\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n\n if (fieldname === 'event') {\n this.event = value;\n } else if (fieldname === 'data') {\n this.data.push(value);\n }\n\n return null;\n }\n}\n\nfunction partition(str: string, delimiter: string): [string, string, string] {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n\n return [str, '', ''];\n}\n","import { type RequestOptions } from './core';\nimport {\n FormData,\n File,\n type Blob,\n type FilePropertyBag,\n getMultipartRequestOptions,\n type FsReadStream,\n isFsReadStream,\n} from './_shims/index';\nimport { MultipartBody } from './_shims/MultipartBody';\nexport { fileFromPath } from './_shims/index';\n\ntype BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;\nexport type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView;\n\n/**\n * Typically, this is a native \"File\" class.\n *\n * We provide the {@link toFile} utility to convert a variety of objects\n * into the File class.\n *\n * For convenience, you can also pass a fetch Response, or in Node,\n * the result of fs.createReadStream().\n */\nexport type Uploadable = FileLike | ResponseLike | FsReadStream;\n\n/**\n * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.\n */\nexport interface BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n readonly size: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n readonly type: string;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n text(): Promise<string>;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n slice(start?: number, end?: number): BlobLike;\n // unfortunately @types/node-fetch@^2.6.4 doesn't type the arrayBuffer method\n}\n\n/**\n * Intended to match web.File, node.File, node-fetch.File, etc.\n */\nexport interface FileLike extends BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n readonly lastModified: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n readonly name: string;\n}\n\n/**\n * Intended to match web.Response, node.Response, node-fetch.Response, etc.\n */\nexport interface ResponseLike {\n url: string;\n blob(): Promise<BlobLike>;\n}\n\nexport const isResponseLike = (value: any): value is ResponseLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\n\nexport const isFileLike = (value: any): value is FileLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\n\n/**\n * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check\n * adds the arrayBuffer() method type because it is available and used at runtime\n */\nexport const isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\n\nexport const isUploadable = (value: any): value is Uploadable => {\n return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);\n};\n\nexport type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;\n\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(\n value: ToFileInput | PromiseLike<ToFileInput>,\n name?: string | null | undefined,\n options?: FilePropertyBag | undefined,\n): Promise<FileLike> {\n // If it's a promise, resolve it.\n value = await value;\n\n // If we've been given a `File` we don't need to do anything\n if (isFileLike(value)) {\n return value;\n }\n\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name ||= new URL(value.url).pathname.split(/[\\\\/]/).pop() ?? 'unknown_file';\n\n // we need to convert the `Blob` into an array buffer because the `Blob` class\n // that `node-fetch` defines is incompatible with the web standard which results\n // in `new File` interpreting it as a string instead of binary data.\n const data = isBlobLike(blob) ? [(await blob.arrayBuffer()) as any] : [blob];\n\n return new File(data, name, options);\n }\n\n const bits = await getBytes(value);\n\n name ||= getName(value) ?? 'unknown_file';\n\n if (!options?.type) {\n const type = (bits[0] as any)?.type;\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n\n return new File(bits, name, options);\n}\n\nasync function getBytes(value: ToFileInput): Promise<Array<BlobPart>> {\n let parts: Array<BlobPart> = [];\n if (\n typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer\n ) {\n parts.push(value);\n } else if (isBlobLike(value)) {\n parts.push(await value.arrayBuffer());\n } else if (\n isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(chunk as BlobPart); // TODO, consider validating?\n }\n } else {\n throw new Error(\n `Unexpected data type: ${typeof value}; constructor: ${value?.constructor\n ?.name}; props: ${propsForError(value)}`,\n );\n }\n\n return parts;\n}\n\nfunction propsForError(value: any): string {\n const props = Object.getOwnPropertyNames(value);\n return `[${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n\nfunction getName(value: any): string | undefined {\n return (\n getStringFromMaybeBuffer(value.name) ||\n getStringFromMaybeBuffer(value.filename) ||\n // For fs.ReadStream\n getStringFromMaybeBuffer(value.path)?.split(/[\\\\/]/).pop()\n );\n}\n\nconst getStringFromMaybeBuffer = (x: string | Buffer | unknown): string | undefined => {\n if (typeof x === 'string') return x;\n if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x);\n return undefined;\n};\n\nconst isAsyncIterableIterator = (value: any): value is AsyncIterableIterator<unknown> =>\n value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n\nexport const isMultipartBody = (body: any): body is MultipartBody =>\n body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';\n\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async <T = Record<string, unknown>>(\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T | MultipartBody>> => {\n if (!hasUploadableValue(opts.body)) return opts;\n\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\n\nexport const multipartFormRequestOptions = async <T = Record<string, unknown>>(\n opts: RequestOptions<T>,\n): Promise<RequestOptions<T | MultipartBody>> => {\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\n\nexport const createForm = async <T = Record<string, unknown>>(body: T | undefined): Promise<FormData> => {\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\n\nconst hasUploadableValue = (value: unknown): boolean => {\n if (isUploadable(value)) return true;\n if (Array.isArray(value)) return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue((value as any)[k])) return true;\n }\n }\n return false;\n};\n\nconst addFormValue = async (form: FormData, key: string, value: unknown): Promise<void> => {\n if (value === undefined) return;\n if (value == null) {\n throw new TypeError(\n `Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`,\n );\n }\n\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n } else if (isUploadable(value)) {\n const file = await toFile(value);\n form.append(key, file as File);\n } else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n } else if (typeof value === 'object') {\n await Promise.all(\n Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)),\n );\n } else {\n throw new TypeError(\n `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`,\n );\n }\n};\n","import { VERSION } from './version';\nimport { Stream } from './streaming';\nimport {\n OpenAIError,\n APIError,\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n} from './error';\nimport {\n kind as shimsKind,\n type Readable,\n getDefaultAgent,\n type Agent,\n fetch,\n type RequestInfo,\n type RequestInit,\n type Response,\n type HeadersInit,\n init,\n} from './_shims/index';\n\n// try running side effects outside of _shims/index to workaround https://github.com/vercel/next.js/issues/76881\ninit();\n\nexport { type Response };\nimport { BlobLike, isBlobLike, isMultipartBody } from './uploads';\nexport {\n maybeMultipartFormRequestOptions,\n multipartFormRequestOptions,\n createForm,\n type Uploadable,\n} from './uploads';\n\nexport type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;\n\n/**\n * An alias to the builtin `Array` type so we can\n * easily alias it in import statements if there are name clashes.\n */\ntype _Array<T> = Array<T>;\n\n/**\n * An alias to the builtin `Record` type so we can\n * easily alias it in import statements if there are name clashes.\n */\ntype _Record<K extends keyof any, T> = Record<K, T>;\n\nexport type { _Array as Array, _Record as Record };\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\ntype APIResponseProps = {\n response: Response;\n options: FinalRequestOptions;\n controller: AbortController;\n};\n\nasync function defaultParseResponse<T>(props: APIResponseProps): Promise<WithRequestID<T>> {\n const { response } = props;\n if (props.options.stream) {\n debug('response', response.status, response.url, response.headers, response.body);\n\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream<T>`\n\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;\n }\n\n return Stream.fromSSEResponse(response, props.controller) as any;\n }\n\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null as WithRequestID<T>;\n }\n\n if (props.options.__binaryResponse) {\n return response as unknown as WithRequestID<T>;\n }\n\n const contentType = response.headers.get('content-type');\n const mediaType = contentType?.split(';')[0]?.trim();\n const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');\n if (isJSON) {\n const json = await response.json();\n\n debug('response', response.status, response.url, response.headers, json);\n\n return _addRequestID(json, response);\n }\n\n const text = await response.text();\n debug('response', response.status, response.url, response.headers, text);\n\n // TODO handle blob, arraybuffer, other content types, etc.\n return text as unknown as WithRequestID<T>;\n}\n\ntype WithRequestID<T> =\n T extends Array<any> | Response | AbstractPage<any> ? T\n : T extends Record<string, any> ? T & { _request_id?: string | null }\n : T;\n\nfunction _addRequestID<T>(value: T, response: Response): WithRequestID<T> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value as WithRequestID<T>;\n }\n\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('x-request-id'),\n enumerable: false,\n }) as WithRequestID<T>;\n}\n\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise<T> extends Promise<WithRequestID<T>> {\n private parsedPromise: Promise<WithRequestID<T>> | undefined;\n\n constructor(\n private responsePromise: Promise<APIResponseProps>,\n private parseResponse: (\n props: APIResponseProps,\n ) => PromiseOrValue<WithRequestID<T>> = defaultParseResponse,\n ) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null as any);\n });\n }\n\n _thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {\n return new APIPromise(this.responsePromise, async (props) =>\n _addRequestID(transform(await this.parseResponse(props), props), props.response),\n );\n }\n\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import … from 'openai'`:\n * - `import 'openai/shims/node'` (if you're running on Node)\n * - `import 'openai/shims/web'` (otherwise)\n */\n asResponse(): Promise<Response> {\n return this.responsePromise.then((p) => p.response);\n }\n\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned via the X-Request-ID header which is useful for debugging requests and reporting\n * issues to OpenAI.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import … from 'openai'`:\n * - `import 'openai/shims/node'` (if you're running on Node)\n * - `import 'openai/shims/web'` (otherwise)\n */\n async withResponse(): Promise<{ data: T; response: Response; request_id: string | null | undefined }> {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('x-request-id') };\n }\n\n private parse(): Promise<WithRequestID<T>> {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then(this.parseResponse) as any as Promise<WithRequestID<T>>;\n }\n return this.parsedPromise;\n }\n\n override then<TResult1 = WithRequestID<T>, TResult2 = never>(\n onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): Promise<TResult1 | TResult2> {\n return this.parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,\n ): Promise<WithRequestID<T> | TResult> {\n return this.parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>> {\n return this.parse().finally(onfinally);\n }\n}\n\nexport abstract class APIClient {\n baseURL: string;\n maxRetries: number;\n timeout: number;\n httpAgent: Agent | undefined;\n\n private fetch: Fetch;\n protected idempotencyHeader?: string;\n\n constructor({\n baseURL,\n maxRetries = 2,\n timeout = 600000, // 10 minutes\n httpAgent,\n fetch: overriddenFetch,\n }: {\n baseURL: string;\n maxRetries?: number | undefined;\n timeout: number | undefined;\n httpAgent: Agent | undefined;\n fetch: Fetch | undefined;\n }) {\n this.baseURL = baseURL;\n this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);\n this.timeout = validatePositiveInteger('timeout', timeout);\n this.httpAgent = httpAgent;\n\n this.fetch = overriddenFetch ?? fetch;\n }\n\n protected authHeaders(opts: FinalRequestOptions): Headers {\n return {};\n }\n\n /**\n * Override this to add your own default headers, for example:\n *\n * {\n * ...super.defaultHeaders(),\n * Authorization: 'Bearer 123',\n * }\n */\n protected defaultHeaders(opts: FinalRequestOptions): Headers {\n return {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': this.getUserAgent(),\n ...getPlatformHeaders(),\n ...this.authHeaders(opts),\n };\n }\n\n protected abstract defaultQuery(): DefaultQuery | undefined;\n\n /**\n * Override this to add your own headers validation:\n */\n protected validateHeaders(headers: Headers, customHeaders: Headers) {}\n\n protected defaultIdempotencyKey(): string {\n return `stainless-node-retry-${uuid4()}`;\n }\n\n get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('get', path, opts);\n }\n\n post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('post', path, opts);\n }\n\n patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('patch', path, opts);\n }\n\n put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('put', path, opts);\n }\n\n delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {\n return this.methodRequest('delete', path, opts);\n }\n\n private methodRequest<Req, Rsp>(\n method: HTTPMethod,\n path: string,\n opts?: PromiseOrValue<RequestOptions<Req>>,\n ): APIPromise<Rsp> {\n return this.request(\n Promise.resolve(opts).then(async (opts) => {\n const body =\n opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())\n : opts?.body instanceof DataView ? opts.body\n : opts?.body instanceof ArrayBuffer ? new DataView(opts.body)\n : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)\n : opts?.body;\n return { method, path, ...opts, body };\n }),\n );\n }\n\n getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(\n path: string,\n Page: new (...args: any[]) => PageClass,\n opts?: RequestOptions<any>,\n ): PagePromise<PageClass, Item> {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n\n private calculateContentLength(body: unknown): string | null {\n if (typeof body === 'string') {\n if (typeof Buffer !== 'undefined') {\n return Buffer.byteLength(body, 'utf8').toString();\n }\n\n if (typeof TextEncoder !== 'undefined') {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(body);\n return encoded.length.toString();\n }\n } else if (ArrayBuffer.isView(body)) {\n return body.byteLength.toString();\n }\n\n return null;\n }\n\n buildRequest<Req>(\n inputOptions: FinalRequestOptions<Req>,\n { retryCount = 0 }: { retryCount?: number } = {},\n ): { req: RequestInit; url: string; timeout: number } {\n const options = { ...inputOptions };\n const { method, path, query, headers: headers = {} } = options;\n\n const body =\n ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?\n options.body\n : isMultipartBody(options.body) ? options.body.body\n : options.body ? JSON.stringify(options.body, null, 2)\n : null;\n const contentLength = this.calculateContentLength(body);\n\n const url = this.buildURL(path!, query);\n if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);\n const minAgentTimeout = options.timeout + 1000;\n if (\n typeof (httpAgent as any)?.options?.timeout === 'number' &&\n minAgentTimeout > ((httpAgent as any).options.timeout ?? 0)\n ) {\n // Allow any given request to bump our agent active socket timeout.\n // This may seem strange, but leaking active sockets should be rare and not particularly problematic,\n // and without mutating agent we would need to create more of them.\n // This tradeoff optimizes for performance.\n (httpAgent as any).options.timeout = minAgentTimeout;\n }\n\n if (this.idempotencyHeader && method !== 'get') {\n if (!inputOptions.idempotencyKey) inputOptions.idempotencyKey = this.defaultIdempotencyKey();\n headers[this.idempotencyHeader] = inputOptions.idempotencyKey;\n }\n\n const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });\n\n const req: RequestInit = {\n method,\n ...(body && { body: body as any }),\n headers: reqHeaders,\n ...(httpAgent && { agent: httpAgent }),\n // @ts-ignore node-fetch uses a custom AbortSignal type that is\n // not compatible with standard web types\n signal: options.signal ?? null,\n };\n\n return { req, url, timeout: options.timeout };\n }\n\n private buildHeaders({\n options,\n headers,\n contentLength,\n retryCount,\n }: {\n options: FinalRequestOptions;\n headers: Record<string, string | null | undefined>;\n contentLength: string | null | undefined;\n retryCount: number;\n }): Record<string, string> {\n const reqHeaders: Record<string, string> = {};\n if (contentLength) {\n reqHeaders['content-length'] = contentLength;\n }\n\n const defaultHeaders = this.defaultHeaders(options);\n applyHeadersMut(reqHeaders, defaultHeaders);\n applyHeadersMut(reqHeaders, headers);\n\n // let builtin fetch set the Content-Type for multipart bodies\n if (isMultipartBody(options.body) && shimsKind !== 'node') {\n delete reqHeaders['content-type'];\n }\n\n // Don't set theses headers if they were already set or removed through default headers or by the caller.\n // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account\n // for the removal case.\n if (\n getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&\n getHeader(headers, 'x-stainless-retry-count') === undefined\n ) {\n reqHeaders['x-stainless-retry-count'] = String(retryCount);\n }\n if (\n getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&\n getHeader(headers, 'x-stainless-timeout') === undefined &&\n options.timeout\n ) {\n reqHeaders['x-stainless-timeout'] = String(Math.trunc(options.timeout / 1000));\n }\n\n this.validateHeaders(reqHeaders, headers);\n\n return reqHeaders;\n }\n\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}\n\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n protected async prepareRequest(\n request: RequestInit,\n { url, options }: { url: string; options: FinalRequestOptions },\n ): Promise<void> {}\n\n protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string> {\n return (\n !headers ? {}\n : Symbol.iterator in headers ?\n Object.fromEntries(Array.from(headers as Iterable<string[]>).map((header) => [...header]))\n : { ...(headers as any as Record<string, string>) }\n );\n }\n\n protected makeStatusError(\n status: number | undefined,\n error: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n return APIError.generate(status, error, message, headers);\n }\n\n request<Req, Rsp>(\n options: PromiseOrValue<FinalRequestOptions<Req>>,\n remainingRetries: number | null = null,\n ): APIPromise<Rsp> {\n return new APIPromise(this.makeRequest(options, remainingRetries));\n }\n\n private async makeRequest<Req>(\n optionsInput: PromiseOrValue<FinalRequestOptions<Req>>,\n retriesRemaining: number | null,\n ): Promise<APIResponseProps> {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n\n await this.prepareOptions(options);\n\n const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });\n\n await this.prepareRequest(req, { url, options });\n\n debug('request', url, options, req.headers);\n\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n\n if (response instanceof Error) {\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n if (retriesRemaining) {\n return this.retryRequest(options, retriesRemaining);\n }\n if (response.name === 'AbortError') {\n throw new APIConnectionTimeoutError();\n }\n throw new APIConnectionError({ cause: response });\n }\n\n const responseHeaders = createResponseHeaders(response.headers);\n\n if (!response.ok) {\n if (retriesRemaining && this.shouldRetry(response)) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);\n return this.retryRequest(options, retriesRemaining, responseHeaders);\n }\n\n const errText = await response.text().catch((e) => castToError(e).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;\n\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);\n\n const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);\n throw err;\n }\n\n return { response, options, controller };\n }\n\n requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n options: FinalRequestOptions,\n ): PagePromise<PageClass, Item> {\n const request = this.makeRequest(options, null);\n return new PagePromise<PageClass, Item>(this, request, Page);\n }\n\n buildURL<Req>(path: string, query: Req | null | undefined): string {\n const url =\n isAbsoluteURL(path) ?\n new URL(path)\n : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query } as Req;\n }\n\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query as Record<string, unknown>);\n }\n\n return url.toString();\n }\n\n protected stringifyQuery(query: Record<string, unknown>): string {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new OpenAIError(\n `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,\n );\n })\n .join('&');\n }\n\n async fetchWithTimeout(\n url: RequestInfo,\n init: RequestInit | undefined,\n ms: number,\n controller: AbortController,\n ): Promise<Response> {\n const { signal, ...options } = init || {};\n if (signal) signal.addEventListener('abort', () => controller.abort());\n\n const timeout = setTimeout(() => controller.abort(), ms);\n\n const fetchOptions = {\n signal: controller.signal as any,\n ...options,\n };\n if (fetchOptions.method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = fetchOptions.method.toUpperCase();\n }\n\n return (\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n this.fetch.call(undefined, url, fetchOptions).finally(() => {\n clearTimeout(timeout);\n })\n );\n }\n\n private shouldRetry(response: Response): boolean {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true') return true;\n if (shouldRetryHeader === 'false') return false;\n\n // Retry on request timeouts.\n if (response.status === 408) return true;\n\n // Retry on lock timeouts.\n if (response.status === 409) return true;\n\n // Retry on rate limits.\n if (response.status === 429) return true;\n\n // Retry internal errors.\n if (response.status >= 500) return true;\n\n return false;\n }\n\n private async retryRequest(\n options: FinalRequestOptions,\n retriesRemaining: number,\n responseHeaders?: Headers | undefined,\n ): Promise<APIResponseProps> {\n let timeoutMillis: number | undefined;\n\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.['retry-after'];\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n } else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n\n return this.makeRequest(options, retriesRemaining - 1);\n }\n\n private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n\n const numRetries = maxRetries - retriesRemaining;\n\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n\n return sleepSeconds * jitter * 1000;\n }\n\n private getUserAgent(): string {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n}\n\nexport type PageInfo = { url: URL } | { params: Record<string, unknown> | null };\n\nexport abstract class AbstractPage<Item> implements AsyncIterable<Item> {\n #client: APIClient;\n protected options: FinalRequestOptions;\n\n protected response: Response;\n protected body: unknown;\n\n constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) {\n this.#client = client;\n this.options = options;\n this.response = response;\n this.body = body;\n }\n\n /**\n * @deprecated Use nextPageInfo instead\n */\n abstract nextPageParams(): Partial<Record<string, unknown>> | null;\n abstract nextPageInfo(): PageInfo | null;\n\n abstract getPaginatedItems(): Item[];\n\n hasNextPage(): boolean {\n const items = this.getPaginatedItems();\n if (!items.length) return false;\n return this.nextPageInfo() != null;\n }\n\n async getNextPage(): Promise<this> {\n const nextInfo = this.nextPageInfo();\n if (!nextInfo) {\n throw new OpenAIError(\n 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',\n );\n }\n const nextOptions = { ...this.options };\n if ('params' in nextInfo && typeof nextOptions.query === 'object') {\n nextOptions.query = { ...nextOptions.query, ...nextInfo.params };\n } else if ('url' in nextInfo) {\n const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];\n for (const [key, value] of params) {\n nextInfo.url.searchParams.set(key, value as any);\n }\n nextOptions.query = undefined;\n nextOptions.path = nextInfo.url.toString();\n }\n return await this.#client.requestAPIList(this.constructor as any, nextOptions);\n }\n\n async *iterPages(): AsyncGenerator<this> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page: this = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise<\n PageClass extends AbstractPage<Item>,\n Item = ReturnType<PageClass['getPaginatedItems']>[number],\n >\n extends APIPromise<PageClass>\n implements AsyncIterable<Item>\n{\n constructor(\n client: APIClient,\n request: Promise<APIResponseProps>,\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n ) {\n super(\n request,\n async (props) =>\n new Page(\n client,\n props.response,\n await defaultParseResponse(props),\n props.options,\n ) as WithRequestID<PageClass>,\n );\n }\n\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\n\nexport const createResponseHeaders = (\n headers: Awaited<ReturnType<Fetch>>['headers'],\n): Record<string, string> => {\n return new Proxy(\n Object.fromEntries(\n // @ts-ignore\n headers.entries(),\n ),\n {\n get(target, name) {\n const key = name.toString();\n return target[key.toLowerCase()] || target[key];\n },\n },\n );\n};\n\ntype HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport type RequestClient = { fetch: Fetch };\nexport type Headers = Record<string, string | null | undefined>;\nexport type DefaultQuery = Record<string, string | undefined>;\nexport type KeysEnum<T> = { [P in keyof Required<T>]: true };\n\nexport type RequestOptions<\n Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer,\n> = {\n method?: HTTPMethod;\n path?: string;\n query?: Req | undefined;\n body?: Req | null | undefined;\n headers?: Headers | undefined;\n\n maxRetries?: number;\n stream?: boolean | undefined;\n timeout?: number;\n httpAgent?: Agent;\n signal?: AbortSignal | undefined | null;\n idempotencyKey?: string;\n\n __metadata?: Record<string, unknown>;\n __binaryRequest?: boolean | undefined;\n __binaryResponse?: boolean | undefined;\n __streamClass?: typeof Stream;\n};\n\n// This is required so that we can determine if a given object matches the RequestOptions\n// type at runtime. While this requires duplication, it is enforced by the TypeScript\n// compiler such that any missing / extraneous keys will cause an error.\nconst requestOptionsKeys: KeysEnum<RequestOptions> = {\n method: true,\n path: true,\n query: true,\n body: true,\n headers: true,\n\n maxRetries: true,\n stream: true,\n timeout: true,\n httpAgent: true,\n signal: true,\n idempotencyKey: true,\n\n __metadata: true,\n __binaryRequest: true,\n __binaryResponse: true,\n __streamClass: true,\n};\n\nexport const isRequestOptions = (obj: unknown): obj is RequestOptions => {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n !isEmptyObj(obj) &&\n Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))\n );\n};\n\nexport type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> =\n RequestOptions<Req> & {\n method: HTTPMethod;\n path: string;\n };\n\ndeclare const Deno: any;\ndeclare const EdgeRuntime: any;\ntype Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';\ntype PlatformName =\n | 'MacOS'\n | 'Linux'\n | 'Windows'\n | 'FreeBSD'\n | 'OpenBSD'\n | 'iOS'\n | 'Android'\n | `Other:${string}`\n | 'Unknown';\ntype Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';\ntype PlatformProperties = {\n 'X-Stainless-Lang': 'js';\n 'X-Stainless-Package-Version': string;\n 'X-Stainless-OS': PlatformName;\n 'X-Stainless-Arch': Arch;\n 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';\n 'X-Stainless-Runtime-Version': string;\n};\nconst getPlatformProperties = (): PlatformProperties => {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version':\n typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n // Check if Node.js\n if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(process.platform),\n 'X-Stainless-Arch': normalizeArch(process.arch),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n\ntype BrowserInfo = {\n browser: Browser;\n version: string;\n};\n\ndeclare const navigator: { userAgent: string } | undefined;\n\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo(): BrowserInfo | null {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge' as const, pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome' as const, pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox' as const, pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari' as const, pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n\n return null;\n}\n\nconst normalizeArch = (arch: string): Arch => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32') return 'x32';\n if (arch === 'x86_64' || arch === 'x64') return 'x64';\n if (arch === 'arm') return 'arm';\n if (arch === 'aarch64' || arch === 'arm64') return 'arm64';\n if (arch) return `other:${arch}`;\n return 'unknown';\n};\n\nconst normalizePlatform = (platform: string): PlatformName => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n\n platform = platform.toLowerCase();\n\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios')) return 'iOS';\n if (platform === 'android') return 'Android';\n if (platform === 'darwin') return 'MacOS';\n if (platform === 'win32') return 'Windows';\n if (platform === 'freebsd') return 'FreeBSD';\n if (platform === 'openbsd') return 'OpenBSD';\n if (platform === 'linux') return 'Linux';\n if (platform) return `Other:${platform}`;\n return 'Unknown';\n};\n\nlet _platformHeaders: PlatformProperties;\nconst getPlatformHeaders = () => {\n return (_platformHeaders ??= getPlatformProperties());\n};\n\nexport const safeJSON = (text: string) => {\n try {\n return JSON.parse(text);\n } catch (err) {\n return undefined;\n }\n};\n\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nconst isAbsoluteURL = (url: string): boolean => {\n return startsWithSchemeRegexp.test(url);\n};\n\nexport const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst validatePositiveInteger = (name: string, n: unknown): number => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new OpenAIError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new OpenAIError(`${name} must be a positive integer`);\n }\n return n;\n};\n\nexport const castToError = (err: any): Error => {\n if (err instanceof Error) return err;\n if (typeof err === 'object' && err !== null) {\n try {\n return new Error(JSON.stringify(err));\n } catch {}\n }\n return new Error(err);\n};\n\nexport const ensurePresent = <T>(value: T | null | undefined): T => {\n if (value == null) throw new OpenAIError(`Expected a value to be given but received ${value} instead.`);\n return value;\n};\n\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env: string): string | undefined => {\n if (typeof process !== 'undefined') {\n return process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof Deno !== 'undefined') {\n return Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\n\nexport const coerceInteger = (value: unknown): number => {\n if (typeof value === 'number') return Math.round(value);\n if (typeof value === 'string') return parseInt(value, 10);\n\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceFloat = (value: unknown): number => {\n if (typeof value === 'number') return value;\n if (typeof value === 'string') return parseFloat(value);\n\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string') return value === 'true';\n return Boolean(value);\n};\n\nexport const maybeCoerceInteger = (value: unknown): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceInteger(value);\n};\n\nexport const maybeCoerceFloat = (value: unknown): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceFloat(value);\n};\n\nexport const maybeCoerceBoolean = (value: unknown): boolean | undefined => {\n if (value === undefined) {\n return undefined;\n }\n return coerceBoolean(value);\n};\n\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj: Object | null | undefined): boolean {\n if (!obj) return true;\n for (const _k in obj) return false;\n return true;\n}\n\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj: Object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\n/**\n * Copies headers from \"newHeaders\" onto \"targetHeaders\",\n * using lower-case for all properties,\n * ignoring any keys with undefined values,\n * and deleting any keys with null values.\n */\nfunction applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void {\n for (const k in newHeaders) {\n if (!hasOwn(newHeaders, k)) continue;\n const lowerKey = k.toLowerCase();\n if (!lowerKey) continue;\n\n const val = newHeaders[k];\n\n if (val === null) {\n delete targetHeaders[lowerKey];\n } else if (val !== undefined) {\n targetHeaders[lowerKey] = val;\n }\n }\n}\n\nconst SENSITIVE_HEADERS = new Set(['authorization', 'api-key']);\n\nexport function debug(action: string, ...args: any[]) {\n if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {\n const modifiedArgs = args.map((arg) => {\n if (!arg) {\n return arg;\n }\n\n // Check for sensitive headers in request body 'headers' object\n if (arg['headers']) {\n // clone so we don't mutate\n const modifiedArg = { ...arg, headers: { ...arg['headers'] } };\n\n for (const header in arg['headers']) {\n if (SENSITIVE_HEADERS.has(header.toLowerCase())) {\n modifiedArg['headers'][header] = 'REDACTED';\n }\n }\n\n return modifiedArg;\n }\n\n let modifiedArg = null;\n\n // Check for sensitive headers in headers object\n for (const header in arg) {\n if (SENSITIVE_HEADERS.has(header.toLowerCase())) {\n // avoid making a copy until we need to\n modifiedArg ??= { ...arg };\n modifiedArg[header] = 'REDACTED';\n }\n }\n\n return modifiedArg ?? arg;\n });\n console.log(`OpenAI:DEBUG:${action}`, ...modifiedArgs);\n }\n}\n\n/**\n * https://stackoverflow.com/a/2117523\n */\nconst uuid4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined'\n );\n};\n\nexport interface HeadersProtocol {\n get: (header: string) => string | null | undefined;\n}\nexport type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;\n\nexport const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {\n return typeof headers?.get === 'function';\n};\n\nexport const getRequiredHeader = (headers: HeadersLike | Headers, header: string): string => {\n const foundHeader = getHeader(headers, header);\n if (foundHeader === undefined) {\n throw new Error(`Could not find ${header} header`);\n }\n return foundHeader;\n};\n\nexport const getHeader = (headers: HeadersLike | Headers, header: string): string | undefined => {\n const lowerCasedHeader = header.toLowerCase();\n if (isHeadersProtocol(headers)) {\n // to deal with the case where the header looks like Stainless-Event-Id\n const intercapsHeader =\n header[0]?.toUpperCase() +\n header.substring(1).replace(/([^\\w])(\\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());\n for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {\n const value = headers.get(key);\n if (value) {\n return value;\n }\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === lowerCasedHeader) {\n if (Array.isArray(value)) {\n if (value.length <= 1) return value[0];\n console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);\n return value[0];\n }\n return value;\n }\n }\n\n return undefined;\n};\n\n/**\n * Encodes a string to Base64 format.\n */\nexport const toBase64 = (str: string | null | undefined): string => {\n if (!str) return '';\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str).toString('base64');\n }\n\n if (typeof btoa !== 'undefined') {\n return btoa(str);\n }\n\n throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');\n};\n\n/**\n * Converts a Base64 encoded string to a Float32Array.\n * @param base64Str - The Base64 encoded string.\n * @returns An Array of numbers interpreted as Float32 values.\n */\nexport const toFloat32Array = (base64Str: string): Array<number> => {\n if (typeof Buffer !== 'undefined') {\n // for Node.js environment\n const buf = Buffer.from(base64Str, 'base64');\n return Array.from(\n new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT),\n );\n } else {\n // for legacy web platform APIs\n const binaryStr = atob(base64Str);\n const len = binaryStr.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryStr.charCodeAt(i);\n }\n return Array.from(new Float32Array(bytes.buffer));\n }\n};\n\nexport function isObj(obj: unknown): obj is Record<string, unknown> {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from './core';\n\nexport interface PageResponse<Item> {\n data: Array<Item>;\n\n object: string;\n}\n\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {\n data: Array<Item>;\n\n object: string;\n\n constructor(client: APIClient, response: Response, body: PageResponse<Item>, options: FinalRequestOptions) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.object = body.object;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n // @deprecated Please use `nextPageInfo()` instead\n /**\n * This page represents a response that isn't actually paginated at the API level\n * so there will never be any next page params.\n */\n nextPageParams(): null {\n return null;\n }\n\n nextPageInfo(): null {\n return null;\n }\n}\n\nexport interface CursorPageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n}\n\nexport interface CursorPageParams {\n after?: string;\n\n limit?: number;\n}\n\nexport class CursorPage<Item extends { id: string }>\n extends AbstractPage<Item>\n implements CursorPageResponse<Item>\n{\n data: Array<Item>;\n\n has_more: boolean;\n\n constructor(\n client: APIClient,\n response: Response,\n body: CursorPageResponse<Item>,\n options: FinalRequestOptions,\n ) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n override hasNextPage(): boolean {\n if (this.has_more === false) {\n return false;\n }\n\n return super.hasNextPage();\n }\n\n // @deprecated Please use `nextPageInfo()` instead\n nextPageParams(): Partial<CursorPageParams> | null {\n const info = this.nextPageInfo();\n if (!info) return null;\n if ('params' in info) return info.params;\n const params = Object.fromEntries(info.url.searchParams);\n if (!Object.keys(params).length) return null;\n return params;\n }\n\n nextPageInfo(): PageInfo | null {\n const data = this.getPaginatedItems();\n if (!data.length) {\n return null;\n }\n\n const id = data[data.length - 1]?.id;\n if (!id) {\n return null;\n }\n\n return { params: { after: id } };\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { OpenAI } from './index';\n\nexport class APIResource {\n protected _client: OpenAI;\n\n constructor(client: OpenAI) {\n this._client = client;\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport * as CompletionsAPI from './completions';\nimport { ChatCompletionStoreMessagesPage } from './completions';\nimport { type CursorPageParams } from '../../../pagination';\n\nexport class Messages extends APIResource {\n /**\n * Get the messages in a stored chat completion. Only Chat Completions that have\n * been created with the `store` parameter set to `true` will be returned.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(\n * 'completion_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n completionId: string,\n query?: MessageListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<ChatCompletionStoreMessagesPage, CompletionsAPI.ChatCompletionStoreMessage>;\n list(\n completionId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<ChatCompletionStoreMessagesPage, CompletionsAPI.ChatCompletionStoreMessage>;\n list(\n completionId: string,\n query: MessageListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<ChatCompletionStoreMessagesPage, CompletionsAPI.ChatCompletionStoreMessage> {\n if (isRequestOptions(query)) {\n return this.list(completionId, {}, query);\n }\n return this._client.getAPIList(\n `/chat/completions/${completionId}/messages`,\n ChatCompletionStoreMessagesPage,\n { query, ...options },\n );\n }\n}\n\nexport interface MessageListParams extends CursorPageParams {\n /**\n * Sort order for messages by timestamp. Use `asc` for ascending order or `desc`\n * for descending order. Defaults to `asc`.\n */\n order?: 'asc' | 'desc';\n}\n\nexport declare namespace Messages {\n export { type MessageListParams as MessageListParams };\n}\n\nexport { ChatCompletionStoreMessagesPage };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport { APIPromise } from '../../../core';\nimport * as Core from '../../../core';\nimport * as CompletionsCompletionsAPI from './completions';\nimport * as CompletionsAPI from '../../completions';\nimport * as Shared from '../../shared';\nimport * as MessagesAPI from './messages';\nimport { MessageListParams, Messages } from './messages';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\nimport { Stream } from '../../../streaming';\n\nexport class Completions extends APIResource {\n messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client);\n\n /**\n * **Starting a new project?** We recommend trying\n * [Responses](https://platform.openai.com/docs/api-reference/responses) to take\n * advantage of the latest OpenAI platform features. Compare\n * [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses).\n *\n * ---\n *\n * Creates a model response for the given chat conversation. Learn more in the\n * [text generation](https://platform.openai.com/docs/guides/text-generation),\n * [vision](https://platform.openai.com/docs/guides/vision), and\n * [audio](https://platform.openai.com/docs/guides/audio) guides.\n *\n * Parameter support can differ depending on the model used to generate the\n * response, particularly for newer reasoning models. Parameters that are only\n * supported for reasoning models are noted below. For the current state of\n * unsupported parameters in reasoning models,\n * [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).\n *\n * @example\n * ```ts\n * const chatCompletion = await client.chat.completions.create(\n * {\n * messages: [{ content: 'string', role: 'developer' }],\n * model: 'gpt-4o',\n * },\n * );\n * ```\n */\n create(\n body: ChatCompletionCreateParamsNonStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<ChatCompletion>;\n create(\n body: ChatCompletionCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<ChatCompletionChunk>>;\n create(\n body: ChatCompletionCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<ChatCompletionChunk> | ChatCompletion>;\n create(\n body: ChatCompletionCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<ChatCompletion> | APIPromise<Stream<ChatCompletionChunk>> {\n return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }) as\n | APIPromise<ChatCompletion>\n | APIPromise<Stream<ChatCompletionChunk>>;\n }\n\n /**\n * Get a stored chat completion. Only Chat Completions that have been created with\n * the `store` parameter set to `true` will be returned.\n *\n * @example\n * ```ts\n * const chatCompletion =\n * await client.chat.completions.retrieve('completion_id');\n * ```\n */\n retrieve(completionId: string, options?: Core.RequestOptions): Core.APIPromise<ChatCompletion> {\n return this._client.get(`/chat/completions/${completionId}`, options);\n }\n\n /**\n * Modify a stored chat completion. Only Chat Completions that have been created\n * with the `store` parameter set to `true` can be modified. Currently, the only\n * supported modification is to update the `metadata` field.\n *\n * @example\n * ```ts\n * const chatCompletion = await client.chat.completions.update(\n * 'completion_id',\n * { metadata: { foo: 'string' } },\n * );\n * ```\n */\n update(\n completionId: string,\n body: ChatCompletionUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<ChatCompletion> {\n return this._client.post(`/chat/completions/${completionId}`, { body, ...options });\n }\n\n /**\n * List stored Chat Completions. Only Chat Completions that have been stored with\n * the `store` parameter set to `true` will be returned.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const chatCompletion of client.chat.completions.list()) {\n * // ...\n * }\n * ```\n */\n list(\n query?: ChatCompletionListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<ChatCompletionsPage, ChatCompletion>;\n list(options?: Core.RequestOptions): Core.PagePromise<ChatCompletionsPage, ChatCompletion>;\n list(\n query: ChatCompletionListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<ChatCompletionsPage, ChatCompletion> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/chat/completions', ChatCompletionsPage, { query, ...options });\n }\n\n /**\n * Delete a stored chat completion. Only Chat Completions that have been created\n * with the `store` parameter set to `true` can be deleted.\n *\n * @example\n * ```ts\n * const chatCompletionDeleted =\n * await client.chat.completions.del('completion_id');\n * ```\n */\n del(completionId: string, options?: Core.RequestOptions): Core.APIPromise<ChatCompletionDeleted> {\n return this._client.delete(`/chat/completions/${completionId}`, options);\n }\n}\n\nexport class ChatCompletionsPage extends CursorPage<ChatCompletion> {}\n\nexport class ChatCompletionStoreMessagesPage extends CursorPage<ChatCompletionStoreMessage> {}\n\n/**\n * Represents a chat completion response returned by model, based on the provided\n * input.\n */\nexport interface ChatCompletion {\n /**\n * A unique identifier for the chat completion.\n */\n id: string;\n\n /**\n * A list of chat completion choices. Can be more than one if `n` is greater\n * than 1.\n */\n choices: Array<ChatCompletion.Choice>;\n\n /**\n * The Unix timestamp (in seconds) of when the chat completion was created.\n */\n created: number;\n\n /**\n * The model used for the chat completion.\n */\n model: string;\n\n /**\n * The object type, which is always `chat.completion`.\n */\n object: 'chat.completion';\n\n /**\n * Specifies the latency tier to use for processing the request. This parameter is\n * relevant for customers subscribed to the scale tier service:\n *\n * - If set to 'auto', and the Project is Scale tier enabled, the system will\n * utilize scale tier credits until they are exhausted.\n * - If set to 'auto', and the Project is not Scale tier enabled, the request will\n * be processed using the default service tier with a lower uptime SLA and no\n * latency guarentee.\n * - If set to 'default', the request will be processed using the default service\n * tier with a lower uptime SLA and no latency guarentee.\n * - If set to 'flex', the request will be processed with the Flex Processing\n * service tier.\n * [Learn more](https://platform.openai.com/docs/guides/flex-processing).\n * - When not set, the default behavior is 'auto'.\n *\n * When this parameter is set, the response body will include the `service_tier`\n * utilized.\n */\n service_tier?: 'auto' | 'default' | 'flex' | null;\n\n /**\n * This fingerprint represents the backend configuration that the model runs with.\n *\n * Can be used in conjunction with the `seed` request parameter to understand when\n * backend changes have been made that might impact determinism.\n */\n system_fingerprint?: string;\n\n /**\n * Usage statistics for the completion request.\n */\n usage?: CompletionsAPI.CompletionUsage;\n}\n\nexport namespace ChatCompletion {\n export interface Choice {\n /**\n * The reason the model stopped generating tokens. This will be `stop` if the model\n * hit a natural stop point or a provided stop sequence, `length` if the maximum\n * number of tokens specified in the request was reached, `content_filter` if\n * content was omitted due to a flag from our content filters, `tool_calls` if the\n * model called a tool, or `function_call` (deprecated) if the model called a\n * function.\n */\n finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call';\n\n /**\n * The index of the choice in the list of choices.\n */\n index: number;\n\n /**\n * Log probability information for the choice.\n */\n logprobs: Choice.Logprobs | null;\n\n /**\n * A chat completion message generated by the model.\n */\n message: CompletionsCompletionsAPI.ChatCompletionMessage;\n }\n\n export namespace Choice {\n /**\n * Log probability information for the choice.\n */\n export interface Logprobs {\n /**\n * A list of message content tokens with log probability information.\n */\n content: Array<CompletionsCompletionsAPI.ChatCompletionTokenLogprob> | null;\n\n /**\n * A list of message refusal tokens with log probability information.\n */\n refusal: Array<CompletionsCompletionsAPI.ChatCompletionTokenLogprob> | null;\n }\n }\n}\n\n/**\n * Messages sent by the model in response to user messages.\n */\nexport interface ChatCompletionAssistantMessageParam {\n /**\n * The role of the messages author, in this case `assistant`.\n */\n role: 'assistant';\n\n /**\n * Data about a previous audio response from the model.\n * [Learn more](https://platform.openai.com/docs/guides/audio).\n */\n audio?: ChatCompletionAssistantMessageParam.Audio | null;\n\n /**\n * The contents of the assistant message. Required unless `tool_calls` or\n * `function_call` is specified.\n */\n content?: string | Array<ChatCompletionContentPartText | ChatCompletionContentPartRefusal> | null;\n\n /**\n * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a\n * function that should be called, as generated by the model.\n */\n function_call?: ChatCompletionAssistantMessageParam.FunctionCall | null;\n\n /**\n * An optional name for the participant. Provides the model information to\n * differentiate between participants of the same role.\n */\n name?: string;\n\n /**\n * The refusal message by the assistant.\n */\n refusal?: string | null;\n\n /**\n * The tool calls generated by the model, such as function calls.\n */\n tool_calls?: Array<ChatCompletionMessageToolCall>;\n}\n\nexport namespace ChatCompletionAssistantMessageParam {\n /**\n * Data about a previous audio response from the model.\n * [Learn more](https://platform.openai.com/docs/guides/audio).\n */\n export interface Audio {\n /**\n * Unique identifier for a previous audio response from the model.\n */\n id: string;\n }\n\n /**\n * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a\n * function that should be called, as generated by the model.\n */\n export interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n }\n}\n\n/**\n * If the audio output modality is requested, this object contains data about the\n * audio response from the model.\n * [Learn more](https://platform.openai.com/docs/guides/audio).\n */\nexport interface ChatCompletionAudio {\n /**\n * Unique identifier for this audio response.\n */\n id: string;\n\n /**\n * Base64 encoded audio bytes generated by the model, in the format specified in\n * the request.\n */\n data: string;\n\n /**\n * The Unix timestamp (in seconds) for when this audio response will no longer be\n * accessible on the server for use in multi-turn conversations.\n */\n expires_at: number;\n\n /**\n * Transcript of the audio generated by the model.\n */\n transcript: string;\n}\n\n/**\n * Parameters for audio output. Required when audio output is requested with\n * `modalities: [\"audio\"]`.\n * [Learn more](https://platform.openai.com/docs/guides/audio).\n */\nexport interface ChatCompletionAudioParam {\n /**\n * Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`,\n * or `pcm16`.\n */\n format: 'wav' | 'aac' | 'mp3' | 'flac' | 'opus' | 'pcm16';\n\n /**\n * The voice the model uses to respond. Supported voices are `alloy`, `ash`,\n * `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`.\n */\n voice:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n}\n\n/**\n * Represents a streamed chunk of a chat completion response returned by the model,\n * based on the provided input.\n * [Learn more](https://platform.openai.com/docs/guides/streaming-responses).\n */\nexport interface ChatCompletionChunk {\n /**\n * A unique identifier for the chat completion. Each chunk has the same ID.\n */\n id: string;\n\n /**\n * A list of chat completion choices. Can contain more than one elements if `n` is\n * greater than 1. Can also be empty for the last chunk if you set\n * `stream_options: {\"include_usage\": true}`.\n */\n choices: Array<ChatCompletionChunk.Choice>;\n\n /**\n * The Unix timestamp (in seconds) of when the chat completion was created. Each\n * chunk has the same timestamp.\n */\n created: number;\n\n /**\n * The model to generate the completion.\n */\n model: string;\n\n /**\n * The object type, which is always `chat.completion.chunk`.\n */\n object: 'chat.completion.chunk';\n\n /**\n * Specifies the latency tier to use for processing the request. This parameter is\n * relevant for customers subscribed to the scale tier service:\n *\n * - If set to 'auto', and the Project is Scale tier enabled, the system will\n * utilize scale tier credits until they are exhausted.\n * - If set to 'auto', and the Project is not Scale tier enabled, the request will\n * be processed using the default service tier with a lower uptime SLA and no\n * latency guarentee.\n * - If set to 'default', the request will be processed using the default service\n * tier with a lower uptime SLA and no latency guarentee.\n * - If set to 'flex', the request will be processed with the Flex Processing\n * service tier.\n * [Learn more](https://platform.openai.com/docs/guides/flex-processing).\n * - When not set, the default behavior is 'auto'.\n *\n * When this parameter is set, the response body will include the `service_tier`\n * utilized.\n */\n service_tier?: 'auto' | 'default' | 'flex' | null;\n\n /**\n * This fingerprint represents the backend configuration that the model runs with.\n * Can be used in conjunction with the `seed` request parameter to understand when\n * backend changes have been made that might impact determinism.\n */\n system_fingerprint?: string;\n\n /**\n * An optional field that will only be present when you set\n * `stream_options: {\"include_usage\": true}` in your request. When present, it\n * contains a null value **except for the last chunk** which contains the token\n * usage statistics for the entire request.\n *\n * **NOTE:** If the stream is interrupted or cancelled, you may not receive the\n * final usage chunk which contains the total token usage for the request.\n */\n usage?: CompletionsAPI.CompletionUsage | null;\n}\n\nexport namespace ChatCompletionChunk {\n export interface Choice {\n /**\n * A chat completion delta generated by streamed model responses.\n */\n delta: Choice.Delta;\n\n /**\n * The reason the model stopped generating tokens. This will be `stop` if the model\n * hit a natural stop point or a provided stop sequence, `length` if the maximum\n * number of tokens specified in the request was reached, `content_filter` if\n * content was omitted due to a flag from our content filters, `tool_calls` if the\n * model called a tool, or `function_call` (deprecated) if the model called a\n * function.\n */\n finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call' | null;\n\n /**\n * The index of the choice in the list of choices.\n */\n index: number;\n\n /**\n * Log probability information for the choice.\n */\n logprobs?: Choice.Logprobs | null;\n }\n\n export namespace Choice {\n /**\n * A chat completion delta generated by streamed model responses.\n */\n export interface Delta {\n /**\n * The contents of the chunk message.\n */\n content?: string | null;\n\n /**\n * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a\n * function that should be called, as generated by the model.\n */\n function_call?: Delta.FunctionCall;\n\n /**\n * The refusal message generated by the model.\n */\n refusal?: string | null;\n\n /**\n * The role of the author of this message.\n */\n role?: 'developer' | 'system' | 'user' | 'assistant' | 'tool';\n\n tool_calls?: Array<Delta.ToolCall>;\n }\n\n export namespace Delta {\n /**\n * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a\n * function that should be called, as generated by the model.\n */\n export interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments?: string;\n\n /**\n * The name of the function to call.\n */\n name?: string;\n }\n\n export interface ToolCall {\n index: number;\n\n /**\n * The ID of the tool call.\n */\n id?: string;\n\n function?: ToolCall.Function;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type?: 'function';\n }\n\n export namespace ToolCall {\n export interface Function {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments?: string;\n\n /**\n * The name of the function to call.\n */\n name?: string;\n }\n }\n }\n\n /**\n * Log probability information for the choice.\n */\n export interface Logprobs {\n /**\n * A list of message content tokens with log probability information.\n */\n content: Array<CompletionsCompletionsAPI.ChatCompletionTokenLogprob> | null;\n\n /**\n * A list of message refusal tokens with log probability information.\n */\n refusal: Array<CompletionsCompletionsAPI.ChatCompletionTokenLogprob> | null;\n }\n }\n}\n\n/**\n * Learn about\n * [text inputs](https://platform.openai.com/docs/guides/text-generation).\n */\nexport type ChatCompletionContentPart =\n | ChatCompletionContentPartText\n | ChatCompletionContentPartImage\n | ChatCompletionContentPartInputAudio\n | ChatCompletionContentPart.File;\n\nexport namespace ChatCompletionContentPart {\n /**\n * Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text\n * generation.\n */\n export interface File {\n file: File.File;\n\n /**\n * The type of the content part. Always `file`.\n */\n type: 'file';\n }\n\n export namespace File {\n export interface File {\n /**\n * The base64 encoded file data, used when passing the file to the model as a\n * string.\n */\n file_data?: string;\n\n /**\n * The ID of an uploaded file to use as input.\n */\n file_id?: string;\n\n /**\n * The name of the file, used when passing the file to the model as a string.\n */\n filename?: string;\n }\n }\n}\n\n/**\n * Learn about [image inputs](https://platform.openai.com/docs/guides/vision).\n */\nexport interface ChatCompletionContentPartImage {\n image_url: ChatCompletionContentPartImage.ImageURL;\n\n /**\n * The type of the content part.\n */\n type: 'image_url';\n}\n\nexport namespace ChatCompletionContentPartImage {\n export interface ImageURL {\n /**\n * Either a URL of the image or the base64 encoded image data.\n */\n url: string;\n\n /**\n * Specifies the detail level of the image. Learn more in the\n * [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).\n */\n detail?: 'auto' | 'low' | 'high';\n }\n}\n\n/**\n * Learn about [audio inputs](https://platform.openai.com/docs/guides/audio).\n */\nexport interface ChatCompletionContentPartInputAudio {\n input_audio: ChatCompletionContentPartInputAudio.InputAudio;\n\n /**\n * The type of the content part. Always `input_audio`.\n */\n type: 'input_audio';\n}\n\nexport namespace ChatCompletionContentPartInputAudio {\n export interface InputAudio {\n /**\n * Base64 encoded audio data.\n */\n data: string;\n\n /**\n * The format of the encoded audio data. Currently supports \"wav\" and \"mp3\".\n */\n format: 'wav' | 'mp3';\n }\n}\n\nexport interface ChatCompletionContentPartRefusal {\n /**\n * The refusal message generated by the model.\n */\n refusal: string;\n\n /**\n * The type of the content part.\n */\n type: 'refusal';\n}\n\n/**\n * Learn about\n * [text inputs](https://platform.openai.com/docs/guides/text-generation).\n */\nexport interface ChatCompletionContentPartText {\n /**\n * The text content.\n */\n text: string;\n\n /**\n * The type of the content part.\n */\n type: 'text';\n}\n\nexport interface ChatCompletionDeleted {\n /**\n * The ID of the chat completion that was deleted.\n */\n id: string;\n\n /**\n * Whether the chat completion was deleted.\n */\n deleted: boolean;\n\n /**\n * The type of object being deleted.\n */\n object: 'chat.completion.deleted';\n}\n\n/**\n * Developer-provided instructions that the model should follow, regardless of\n * messages sent by the user. With o1 models and newer, `developer` messages\n * replace the previous `system` messages.\n */\nexport interface ChatCompletionDeveloperMessageParam {\n /**\n * The contents of the developer message.\n */\n content: string | Array<ChatCompletionContentPartText>;\n\n /**\n * The role of the messages author, in this case `developer`.\n */\n role: 'developer';\n\n /**\n * An optional name for the participant. Provides the model information to\n * differentiate between participants of the same role.\n */\n name?: string;\n}\n\n/**\n * Specifying a particular function via `{\"name\": \"my_function\"}` forces the model\n * to call that function.\n */\nexport interface ChatCompletionFunctionCallOption {\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\n/**\n * @deprecated\n */\nexport interface ChatCompletionFunctionMessageParam {\n /**\n * The contents of the function message.\n */\n content: string | null;\n\n /**\n * The name of the function to call.\n */\n name: string;\n\n /**\n * The role of the messages author, in this case `function`.\n */\n role: 'function';\n}\n\n/**\n * A chat completion message generated by the model.\n */\nexport interface ChatCompletionMessage {\n /**\n * The contents of the message.\n */\n content: string | null;\n\n /**\n * The refusal message generated by the model.\n */\n refusal: string | null;\n\n /**\n * The role of the author of this message.\n */\n role: 'assistant';\n\n /**\n * Annotations for the message, when applicable, as when using the\n * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n */\n annotations?: Array<ChatCompletionMessage.Annotation>;\n\n /**\n * If the audio output modality is requested, this object contains data about the\n * audio response from the model.\n * [Learn more](https://platform.openai.com/docs/guides/audio).\n */\n audio?: ChatCompletionAudio | null;\n\n /**\n * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a\n * function that should be called, as generated by the model.\n */\n function_call?: ChatCompletionMessage.FunctionCall | null;\n\n /**\n * The tool calls generated by the model, such as function calls.\n */\n tool_calls?: Array<ChatCompletionMessageToolCall>;\n}\n\nexport namespace ChatCompletionMessage {\n /**\n * A URL citation when using web search.\n */\n export interface Annotation {\n /**\n * The type of the URL citation. Always `url_citation`.\n */\n type: 'url_citation';\n\n /**\n * A URL citation when using web search.\n */\n url_citation: Annotation.URLCitation;\n }\n\n export namespace Annotation {\n /**\n * A URL citation when using web search.\n */\n export interface URLCitation {\n /**\n * The index of the last character of the URL citation in the message.\n */\n end_index: number;\n\n /**\n * The index of the first character of the URL citation in the message.\n */\n start_index: number;\n\n /**\n * The title of the web resource.\n */\n title: string;\n\n /**\n * The URL of the web resource.\n */\n url: string;\n }\n }\n\n /**\n * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a\n * function that should be called, as generated by the model.\n */\n export interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n }\n}\n\n/**\n * Developer-provided instructions that the model should follow, regardless of\n * messages sent by the user. With o1 models and newer, `developer` messages\n * replace the previous `system` messages.\n */\nexport type ChatCompletionMessageParam =\n | ChatCompletionDeveloperMessageParam\n | ChatCompletionSystemMessageParam\n | ChatCompletionUserMessageParam\n | ChatCompletionAssistantMessageParam\n | ChatCompletionToolMessageParam\n | ChatCompletionFunctionMessageParam;\n\nexport interface ChatCompletionMessageToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: ChatCompletionMessageToolCall.Function;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: 'function';\n}\n\nexport namespace ChatCompletionMessageToolCall {\n /**\n * The function that the model called.\n */\n export interface Function {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n }\n}\n\nexport type ChatCompletionModality = 'text' | 'audio';\n\n/**\n * Specifies a tool the model should use. Use to force the model to call a specific\n * function.\n */\nexport interface ChatCompletionNamedToolChoice {\n function: ChatCompletionNamedToolChoice.Function;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: 'function';\n}\n\nexport namespace ChatCompletionNamedToolChoice {\n export interface Function {\n /**\n * The name of the function to call.\n */\n name: string;\n }\n}\n\n/**\n * Static predicted output content, such as the content of a text file that is\n * being regenerated.\n */\nexport interface ChatCompletionPredictionContent {\n /**\n * The content that should be matched when generating a model response. If\n * generated tokens would match this content, the entire model response can be\n * returned much more quickly.\n */\n content: string | Array<ChatCompletionContentPartText>;\n\n /**\n * The type of the predicted content you want to provide. This type is currently\n * always `content`.\n */\n type: 'content';\n}\n\n/**\n * The role of the author of a message\n */\nexport type ChatCompletionRole = 'developer' | 'system' | 'user' | 'assistant' | 'tool' | 'function';\n\n/**\n * A chat completion message generated by the model.\n */\nexport interface ChatCompletionStoreMessage extends ChatCompletionMessage {\n /**\n * The identifier of the chat message.\n */\n id: string;\n}\n\n/**\n * Options for streaming response. Only set this when you set `stream: true`.\n */\nexport interface ChatCompletionStreamOptions {\n /**\n * If set, an additional chunk will be streamed before the `data: [DONE]` message.\n * The `usage` field on this chunk shows the token usage statistics for the entire\n * request, and the `choices` field will always be an empty array.\n *\n * All other chunks will also include a `usage` field, but with a null value.\n * **NOTE:** If the stream is interrupted, you may not receive the final usage\n * chunk which contains the total token usage for the request.\n */\n include_usage?: boolean;\n}\n\n/**\n * Developer-provided instructions that the model should follow, regardless of\n * messages sent by the user. With o1 models and newer, use `developer` messages\n * for this purpose instead.\n */\nexport interface ChatCompletionSystemMessageParam {\n /**\n * The contents of the system message.\n */\n content: string | Array<ChatCompletionContentPartText>;\n\n /**\n * The role of the messages author, in this case `system`.\n */\n role: 'system';\n\n /**\n * An optional name for the participant. Provides the model information to\n * differentiate between participants of the same role.\n */\n name?: string;\n}\n\nexport interface ChatCompletionTokenLogprob {\n /**\n * The token.\n */\n token: string;\n\n /**\n * A list of integers representing the UTF-8 bytes representation of the token.\n * Useful in instances where characters are represented by multiple tokens and\n * their byte representations must be combined to generate the correct text\n * representation. Can be `null` if there is no bytes representation for the token.\n */\n bytes: Array<number> | null;\n\n /**\n * The log probability of this token, if it is within the top 20 most likely\n * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very\n * unlikely.\n */\n logprob: number;\n\n /**\n * List of the most likely tokens and their log probability, at this token\n * position. In rare cases, there may be fewer than the number of requested\n * `top_logprobs` returned.\n */\n top_logprobs: Array<ChatCompletionTokenLogprob.TopLogprob>;\n}\n\nexport namespace ChatCompletionTokenLogprob {\n export interface TopLogprob {\n /**\n * The token.\n */\n token: string;\n\n /**\n * A list of integers representing the UTF-8 bytes representation of the token.\n * Useful in instances where characters are represented by multiple tokens and\n * their byte representations must be combined to generate the correct text\n * representation. Can be `null` if there is no bytes representation for the token.\n */\n bytes: Array<number> | null;\n\n /**\n * The log probability of this token, if it is within the top 20 most likely\n * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very\n * unlikely.\n */\n logprob: number;\n }\n}\n\nexport interface ChatCompletionTool {\n function: Shared.FunctionDefinition;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: 'function';\n}\n\n/**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tool and instead generates a message. `auto` means the model can\n * pick between generating a message or calling one or more tools. `required` means\n * the model must call one or more tools. Specifying a particular tool via\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n *\n * `none` is the default when no tools are present. `auto` is the default if tools\n * are present.\n */\nexport type ChatCompletionToolChoiceOption = 'none' | 'auto' | 'required' | ChatCompletionNamedToolChoice;\n\nexport interface ChatCompletionToolMessageParam {\n /**\n * The contents of the tool message.\n */\n content: string | Array<ChatCompletionContentPartText>;\n\n /**\n * The role of the messages author, in this case `tool`.\n */\n role: 'tool';\n\n /**\n * Tool call that this message is responding to.\n */\n tool_call_id: string;\n}\n\n/**\n * Messages sent by an end user, containing prompts or additional context\n * information.\n */\nexport interface ChatCompletionUserMessageParam {\n /**\n * The contents of the user message.\n */\n content: string | Array<ChatCompletionContentPart>;\n\n /**\n * The role of the messages author, in this case `user`.\n */\n role: 'user';\n\n /**\n * An optional name for the participant. Provides the model information to\n * differentiate between participants of the same role.\n */\n name?: string;\n}\n\n/**\n * @deprecated ChatCompletionMessageParam should be used instead\n */\nexport type CreateChatCompletionRequestMessage = ChatCompletionMessageParam;\n\nexport type ChatCompletionReasoningEffort = Shared.ReasoningEffort | null;\n\nexport type ChatCompletionCreateParams =\n | ChatCompletionCreateParamsNonStreaming\n | ChatCompletionCreateParamsStreaming;\n\nexport interface ChatCompletionCreateParamsBase {\n /**\n * A list of messages comprising the conversation so far. Depending on the\n * [model](https://platform.openai.com/docs/models) you use, different message\n * types (modalities) are supported, like\n * [text](https://platform.openai.com/docs/guides/text-generation),\n * [images](https://platform.openai.com/docs/guides/vision), and\n * [audio](https://platform.openai.com/docs/guides/audio).\n */\n messages: Array<ChatCompletionMessageParam>;\n\n /**\n * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a\n * wide range of models with different capabilities, performance characteristics,\n * and price points. Refer to the\n * [model guide](https://platform.openai.com/docs/models) to browse and compare\n * available models.\n */\n model: (string & {}) | Shared.ChatModel;\n\n /**\n * Parameters for audio output. Required when audio output is requested with\n * `modalities: [\"audio\"]`.\n * [Learn more](https://platform.openai.com/docs/guides/audio).\n */\n audio?: ChatCompletionAudioParam | null;\n\n /**\n * Number between -2.0 and 2.0. Positive values penalize new tokens based on their\n * existing frequency in the text so far, decreasing the model's likelihood to\n * repeat the same line verbatim.\n */\n frequency_penalty?: number | null;\n\n /**\n * @deprecated Deprecated in favor of `tool_choice`.\n *\n * Controls which (if any) function is called by the model.\n *\n * `none` means the model will not call a function and instead generates a message.\n *\n * `auto` means the model can pick between generating a message or calling a\n * function.\n *\n * Specifying a particular function via `{\"name\": \"my_function\"}` forces the model\n * to call that function.\n *\n * `none` is the default when no functions are present. `auto` is the default if\n * functions are present.\n */\n function_call?: 'none' | 'auto' | ChatCompletionFunctionCallOption;\n\n /**\n * @deprecated Deprecated in favor of `tools`.\n *\n * A list of functions the model may generate JSON inputs for.\n */\n functions?: Array<ChatCompletionCreateParams.Function>;\n\n /**\n * Modify the likelihood of specified tokens appearing in the completion.\n *\n * Accepts a JSON object that maps tokens (specified by their token ID in the\n * tokenizer) to an associated bias value from -100 to 100. Mathematically, the\n * bias is added to the logits generated by the model prior to sampling. The exact\n * effect will vary per model, but values between -1 and 1 should decrease or\n * increase likelihood of selection; values like -100 or 100 should result in a ban\n * or exclusive selection of the relevant token.\n */\n logit_bias?: Record<string, number> | null;\n\n /**\n * Whether to return log probabilities of the output tokens or not. If true,\n * returns the log probabilities of each output token returned in the `content` of\n * `message`.\n */\n logprobs?: boolean | null;\n\n /**\n * An upper bound for the number of tokens that can be generated for a completion,\n * including visible output tokens and\n * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n */\n max_completion_tokens?: number | null;\n\n /**\n * @deprecated The maximum number of [tokens](/tokenizer) that can be generated in\n * the chat completion. This value can be used to control\n * [costs](https://openai.com/api/pricing/) for text generated via API.\n *\n * This value is now deprecated in favor of `max_completion_tokens`, and is not\n * compatible with\n * [o-series models](https://platform.openai.com/docs/guides/reasoning).\n */\n max_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * Output types that you would like the model to generate. Most models are capable\n * of generating text, which is the default:\n *\n * `[\"text\"]`\n *\n * The `gpt-4o-audio-preview` model can also be used to\n * [generate audio](https://platform.openai.com/docs/guides/audio). To request that\n * this model generate both text and audio responses, you can use:\n *\n * `[\"text\", \"audio\"]`\n */\n modalities?: Array<'text' | 'audio'> | null;\n\n /**\n * How many chat completion choices to generate for each input message. Note that\n * you will be charged based on the number of generated tokens across all of the\n * choices. Keep `n` as `1` to minimize costs.\n */\n n?: number | null;\n\n /**\n * Whether to enable\n * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling)\n * during tool use.\n */\n parallel_tool_calls?: boolean;\n\n /**\n * Static predicted output content, such as the content of a text file that is\n * being regenerated.\n */\n prediction?: ChatCompletionPredictionContent | null;\n\n /**\n * Number between -2.0 and 2.0. Positive values penalize new tokens based on\n * whether they appear in the text so far, increasing the model's likelihood to\n * talk about new topics.\n */\n presence_penalty?: number | null;\n\n /**\n * **o-series models only**\n *\n * Constrains effort on reasoning for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently\n * supported values are `low`, `medium`, and `high`. Reducing reasoning effort can\n * result in faster responses and fewer tokens used on reasoning in a response.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * An object specifying the format that the model must output.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\n * ensures the message the model generates is valid JSON. Using `json_schema` is\n * preferred for models that support it.\n */\n response_format?:\n | Shared.ResponseFormatText\n | Shared.ResponseFormatJSONSchema\n | Shared.ResponseFormatJSONObject;\n\n /**\n * This feature is in Beta. If specified, our system will make a best effort to\n * sample deterministically, such that repeated requests with the same `seed` and\n * parameters should return the same result. Determinism is not guaranteed, and you\n * should refer to the `system_fingerprint` response parameter to monitor changes\n * in the backend.\n */\n seed?: number | null;\n\n /**\n * Specifies the latency tier to use for processing the request. This parameter is\n * relevant for customers subscribed to the scale tier service:\n *\n * - If set to 'auto', and the Project is Scale tier enabled, the system will\n * utilize scale tier credits until they are exhausted.\n * - If set to 'auto', and the Project is not Scale tier enabled, the request will\n * be processed using the default service tier with a lower uptime SLA and no\n * latency guarentee.\n * - If set to 'default', the request will be processed using the default service\n * tier with a lower uptime SLA and no latency guarentee.\n * - If set to 'flex', the request will be processed with the Flex Processing\n * service tier.\n * [Learn more](https://platform.openai.com/docs/guides/flex-processing).\n * - When not set, the default behavior is 'auto'.\n *\n * When this parameter is set, the response body will include the `service_tier`\n * utilized.\n */\n service_tier?: 'auto' | 'default' | 'flex' | null;\n\n /**\n * Not supported with latest reasoning models `o3` and `o4-mini`.\n *\n * Up to 4 sequences where the API will stop generating further tokens. The\n * returned text will not contain the stop sequence.\n */\n stop?: string | null | Array<string>;\n\n /**\n * Whether or not to store the output of this chat completion request for use in\n * our [model distillation](https://platform.openai.com/docs/guides/distillation)\n * or [evals](https://platform.openai.com/docs/guides/evals) products.\n */\n store?: boolean | null;\n\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\n * for more information, along with the\n * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\n * guide for more information on how to handle the streaming events.\n */\n stream?: boolean | null;\n\n /**\n * Options for streaming response. Only set this when you set `stream: true`.\n */\n stream_options?: ChatCompletionStreamOptions | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic. We generally recommend altering this or `top_p` but\n * not both.\n */\n temperature?: number | null;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tool and instead generates a message. `auto` means the model can\n * pick between generating a message or calling one or more tools. `required` means\n * the model must call one or more tools. Specifying a particular tool via\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n *\n * `none` is the default when no tools are present. `auto` is the default if tools\n * are present.\n */\n tool_choice?: ChatCompletionToolChoiceOption;\n\n /**\n * A list of tools the model may call. Currently, only functions are supported as a\n * tool. Use this to provide a list of functions the model may generate JSON inputs\n * for. A max of 128 functions are supported.\n */\n tools?: Array<ChatCompletionTool>;\n\n /**\n * An integer between 0 and 20 specifying the number of most likely tokens to\n * return at each token position, each with an associated log probability.\n * `logprobs` must be set to `true` if this parameter is used.\n */\n top_logprobs?: number | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or `temperature` but not both.\n */\n top_p?: number | null;\n\n /**\n * A stable identifier for your end-users. Used to boost cache hit rates by better\n * bucketing similar requests and to help OpenAI detect and prevent abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n\n /**\n * This tool searches the web for relevant results to use in a response. Learn more\n * about the\n * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n */\n web_search_options?: ChatCompletionCreateParams.WebSearchOptions;\n}\n\nexport namespace ChatCompletionCreateParams {\n /**\n * @deprecated\n */\n export interface Function {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](https://platform.openai.com/docs/guides/function-calling) for examples,\n * and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * Omitting `parameters` defines a function with an empty parameter list.\n */\n parameters?: Shared.FunctionParameters;\n }\n\n /**\n * This tool searches the web for relevant results to use in a response. Learn more\n * about the\n * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n */\n export interface WebSearchOptions {\n /**\n * High level guidance for the amount of context window space to use for the\n * search. One of `low`, `medium`, or `high`. `medium` is the default.\n */\n search_context_size?: 'low' | 'medium' | 'high';\n\n /**\n * Approximate location parameters for the search.\n */\n user_location?: WebSearchOptions.UserLocation | null;\n }\n\n export namespace WebSearchOptions {\n /**\n * Approximate location parameters for the search.\n */\n export interface UserLocation {\n /**\n * Approximate location parameters for the search.\n */\n approximate: UserLocation.Approximate;\n\n /**\n * The type of location approximation. Always `approximate`.\n */\n type: 'approximate';\n }\n\n export namespace UserLocation {\n /**\n * Approximate location parameters for the search.\n */\n export interface Approximate {\n /**\n * Free text input for the city of the user, e.g. `San Francisco`.\n */\n city?: string;\n\n /**\n * The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of\n * the user, e.g. `US`.\n */\n country?: string;\n\n /**\n * Free text input for the region of the user, e.g. `California`.\n */\n region?: string;\n\n /**\n * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the\n * user, e.g. `America/Los_Angeles`.\n */\n timezone?: string;\n }\n }\n }\n\n export type ChatCompletionCreateParamsNonStreaming =\n CompletionsCompletionsAPI.ChatCompletionCreateParamsNonStreaming;\n export type ChatCompletionCreateParamsStreaming =\n CompletionsCompletionsAPI.ChatCompletionCreateParamsStreaming;\n}\n\n/**\n * @deprecated Use ChatCompletionCreateParams instead\n */\nexport type CompletionCreateParams = ChatCompletionCreateParams;\n\nexport interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\n * for more information, along with the\n * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\n * guide for more information on how to handle the streaming events.\n */\n stream?: false | null;\n}\n\n/**\n * @deprecated Use ChatCompletionCreateParamsNonStreaming instead\n */\nexport type CompletionCreateParamsNonStreaming = ChatCompletionCreateParamsNonStreaming;\n\nexport interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\n * for more information, along with the\n * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\n * guide for more information on how to handle the streaming events.\n */\n stream: true;\n}\n\n/**\n * @deprecated Use ChatCompletionCreateParamsStreaming instead\n */\nexport type CompletionCreateParamsStreaming = ChatCompletionCreateParamsStreaming;\n\nexport interface ChatCompletionUpdateParams {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n}\n\n/**\n * @deprecated Use ChatCompletionUpdateParams instead\n */\nexport type CompletionUpdateParams = ChatCompletionUpdateParams;\n\nexport interface ChatCompletionListParams extends CursorPageParams {\n /**\n * A list of metadata keys to filter the Chat Completions by. Example:\n *\n * `metadata[key1]=value1&metadata[key2]=value2`\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The model used to generate the Chat Completions.\n */\n model?: string;\n\n /**\n * Sort order for Chat Completions by timestamp. Use `asc` for ascending order or\n * `desc` for descending order. Defaults to `asc`.\n */\n order?: 'asc' | 'desc';\n}\n\n/**\n * @deprecated Use ChatCompletionListParams instead\n */\nexport type CompletionListParams = ChatCompletionListParams;\n\nCompletions.ChatCompletionsPage = ChatCompletionsPage;\nCompletions.Messages = Messages;\n\nexport declare namespace Completions {\n export {\n type ChatCompletion as ChatCompletion,\n type ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam,\n type ChatCompletionAudio as ChatCompletionAudio,\n type ChatCompletionAudioParam as ChatCompletionAudioParam,\n type ChatCompletionChunk as ChatCompletionChunk,\n type ChatCompletionContentPart as ChatCompletionContentPart,\n type ChatCompletionContentPartImage as ChatCompletionContentPartImage,\n type ChatCompletionContentPartInputAudio as ChatCompletionContentPartInputAudio,\n type ChatCompletionContentPartRefusal as ChatCompletionContentPartRefusal,\n type ChatCompletionContentPartText as ChatCompletionContentPartText,\n type ChatCompletionDeleted as ChatCompletionDeleted,\n type ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam,\n type ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOption,\n type ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam,\n type ChatCompletionMessage as ChatCompletionMessage,\n type ChatCompletionMessageParam as ChatCompletionMessageParam,\n type ChatCompletionMessageToolCall as ChatCompletionMessageToolCall,\n type ChatCompletionModality as ChatCompletionModality,\n type ChatCompletionNamedToolChoice as ChatCompletionNamedToolChoice,\n type ChatCompletionPredictionContent as ChatCompletionPredictionContent,\n type ChatCompletionRole as ChatCompletionRole,\n type ChatCompletionStoreMessage as ChatCompletionStoreMessage,\n type ChatCompletionStreamOptions as ChatCompletionStreamOptions,\n type ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam,\n type ChatCompletionTokenLogprob as ChatCompletionTokenLogprob,\n type ChatCompletionTool as ChatCompletionTool,\n type ChatCompletionToolChoiceOption as ChatCompletionToolChoiceOption,\n type ChatCompletionToolMessageParam as ChatCompletionToolMessageParam,\n type ChatCompletionUserMessageParam as ChatCompletionUserMessageParam,\n type CreateChatCompletionRequestMessage as CreateChatCompletionRequestMessage,\n type ChatCompletionReasoningEffort as ChatCompletionReasoningEffort,\n ChatCompletionsPage as ChatCompletionsPage,\n type ChatCompletionCreateParams as ChatCompletionCreateParams,\n type CompletionCreateParams as CompletionCreateParams,\n type ChatCompletionCreateParamsNonStreaming as ChatCompletionCreateParamsNonStreaming,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type ChatCompletionCreateParamsStreaming as ChatCompletionCreateParamsStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n type ChatCompletionUpdateParams as ChatCompletionUpdateParams,\n type CompletionUpdateParams as CompletionUpdateParams,\n type ChatCompletionListParams as ChatCompletionListParams,\n type CompletionListParams as CompletionListParams,\n };\n\n export { Messages as Messages, type MessageListParams as MessageListParams };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as Shared from '../shared';\nimport * as CompletionsAPI from './completions/completions';\nimport {\n ChatCompletion,\n ChatCompletionAssistantMessageParam,\n ChatCompletionAudio,\n ChatCompletionAudioParam,\n ChatCompletionChunk,\n ChatCompletionContentPart,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPartRefusal,\n ChatCompletionContentPartText,\n ChatCompletionCreateParams,\n ChatCompletionCreateParamsNonStreaming,\n ChatCompletionCreateParamsStreaming,\n ChatCompletionDeleted,\n ChatCompletionDeveloperMessageParam,\n ChatCompletionFunctionCallOption,\n ChatCompletionFunctionMessageParam,\n ChatCompletionListParams,\n ChatCompletionMessage,\n ChatCompletionMessageParam,\n ChatCompletionMessageToolCall,\n ChatCompletionModality,\n ChatCompletionNamedToolChoice,\n ChatCompletionPredictionContent,\n ChatCompletionReasoningEffort,\n ChatCompletionRole,\n ChatCompletionStoreMessage,\n ChatCompletionStreamOptions,\n ChatCompletionSystemMessageParam,\n ChatCompletionTokenLogprob,\n ChatCompletionTool,\n ChatCompletionToolChoiceOption,\n ChatCompletionToolMessageParam,\n ChatCompletionUpdateParams,\n ChatCompletionUserMessageParam,\n ChatCompletionsPage,\n CompletionCreateParams,\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n CompletionListParams,\n CompletionUpdateParams,\n Completions,\n CreateChatCompletionRequestMessage,\n} from './completions/completions';\n\nexport class Chat extends APIResource {\n completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client);\n}\n\nexport type ChatModel = Shared.ChatModel;\n\nChat.Completions = Completions;\nChat.ChatCompletionsPage = ChatCompletionsPage;\n\nexport declare namespace Chat {\n export { type ChatModel as ChatModel };\n\n export {\n Completions as Completions,\n type ChatCompletion as ChatCompletion,\n type ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam,\n type ChatCompletionAudio as ChatCompletionAudio,\n type ChatCompletionAudioParam as ChatCompletionAudioParam,\n type ChatCompletionChunk as ChatCompletionChunk,\n type ChatCompletionContentPart as ChatCompletionContentPart,\n type ChatCompletionContentPartImage as ChatCompletionContentPartImage,\n type ChatCompletionContentPartInputAudio as ChatCompletionContentPartInputAudio,\n type ChatCompletionContentPartRefusal as ChatCompletionContentPartRefusal,\n type ChatCompletionContentPartText as ChatCompletionContentPartText,\n type ChatCompletionDeleted as ChatCompletionDeleted,\n type ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam,\n type ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOption,\n type ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam,\n type ChatCompletionMessage as ChatCompletionMessage,\n type ChatCompletionMessageParam as ChatCompletionMessageParam,\n type ChatCompletionMessageToolCall as ChatCompletionMessageToolCall,\n type ChatCompletionModality as ChatCompletionModality,\n type ChatCompletionNamedToolChoice as ChatCompletionNamedToolChoice,\n type ChatCompletionPredictionContent as ChatCompletionPredictionContent,\n type ChatCompletionRole as ChatCompletionRole,\n type ChatCompletionStoreMessage as ChatCompletionStoreMessage,\n type ChatCompletionStreamOptions as ChatCompletionStreamOptions,\n type ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam,\n type ChatCompletionTokenLogprob as ChatCompletionTokenLogprob,\n type ChatCompletionTool as ChatCompletionTool,\n type ChatCompletionToolChoiceOption as ChatCompletionToolChoiceOption,\n type ChatCompletionToolMessageParam as ChatCompletionToolMessageParam,\n type ChatCompletionUserMessageParam as ChatCompletionUserMessageParam,\n type CreateChatCompletionRequestMessage as CreateChatCompletionRequestMessage,\n type ChatCompletionReasoningEffort as ChatCompletionReasoningEffort,\n ChatCompletionsPage as ChatCompletionsPage,\n type ChatCompletionCreateParams as ChatCompletionCreateParams,\n type CompletionCreateParams as CompletionCreateParams,\n type ChatCompletionCreateParamsNonStreaming as ChatCompletionCreateParamsNonStreaming,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type ChatCompletionCreateParamsStreaming as ChatCompletionCreateParamsStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n type ChatCompletionUpdateParams as ChatCompletionUpdateParams,\n type CompletionUpdateParams as CompletionUpdateParams,\n type ChatCompletionListParams as ChatCompletionListParams,\n type CompletionListParams as CompletionListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as Core from '../../core';\nimport { type Response } from '../../_shims/index';\n\nexport class Speech extends APIResource {\n /**\n * Generates audio from the input text.\n *\n * @example\n * ```ts\n * const speech = await client.audio.speech.create({\n * input: 'input',\n * model: 'string',\n * voice: 'ash',\n * });\n *\n * const content = await speech.blob();\n * console.log(content);\n * ```\n */\n create(body: SpeechCreateParams, options?: Core.RequestOptions): Core.APIPromise<Response> {\n return this._client.post('/audio/speech', {\n body,\n ...options,\n headers: { Accept: 'application/octet-stream', ...options?.headers },\n __binaryResponse: true,\n });\n }\n}\n\nexport type SpeechModel = 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts';\n\nexport interface SpeechCreateParams {\n /**\n * The text to generate audio for. The maximum length is 4096 characters.\n */\n input: string;\n\n /**\n * One of the available [TTS models](https://platform.openai.com/docs/models#tts):\n * `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`.\n */\n model: (string & {}) | SpeechModel;\n\n /**\n * The voice to use when generating the audio. Supported voices are `alloy`, `ash`,\n * `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and\n * `verse`. Previews of the voices are available in the\n * [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options).\n */\n voice:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n\n /**\n * Control the voice of your generated audio with additional instructions. Does not\n * work with `tts-1` or `tts-1-hd`.\n */\n instructions?: string;\n\n /**\n * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`,\n * `wav`, and `pcm`.\n */\n response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm';\n\n /**\n * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is\n * the default. Does not work with `gpt-4o-mini-tts`.\n */\n speed?: number;\n}\n\nexport declare namespace Speech {\n export { type SpeechModel as SpeechModel, type SpeechCreateParams as SpeechCreateParams };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as Core from '../../core';\nimport * as TranscriptionsAPI from './transcriptions';\nimport * as AudioAPI from './audio';\nimport { Stream } from '../../streaming';\n\nexport class Transcriptions extends APIResource {\n /**\n * Transcribes audio into the input language.\n *\n * @example\n * ```ts\n * const transcription =\n * await client.audio.transcriptions.create({\n * file: fs.createReadStream('speech.mp3'),\n * model: 'gpt-4o-transcribe',\n * });\n * ```\n */\n create(\n body: TranscriptionCreateParamsNonStreaming<'json' | undefined>,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Transcription>;\n create(\n body: TranscriptionCreateParamsNonStreaming<'verbose_json'>,\n options?: Core.RequestOptions,\n ): Core.APIPromise<TranscriptionVerbose>;\n create(\n body: TranscriptionCreateParamsNonStreaming<'srt' | 'vtt' | 'text'>,\n options?: Core.RequestOptions,\n ): Core.APIPromise<string>;\n create(\n body: TranscriptionCreateParamsNonStreaming,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Transcription>;\n create(\n body: TranscriptionCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Stream<TranscriptionStreamEvent>>;\n create(\n body: TranscriptionCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): Core.APIPromise<TranscriptionCreateResponse | string | Stream<TranscriptionStreamEvent>>;\n create(\n body: TranscriptionCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<TranscriptionCreateResponse | string | Stream<TranscriptionStreamEvent>> {\n return this._client.post(\n '/audio/transcriptions',\n Core.multipartFormRequestOptions({\n body,\n ...options,\n stream: body.stream ?? false,\n __metadata: { model: body.model },\n }),\n );\n }\n}\n\n/**\n * Represents a transcription response returned by model, based on the provided\n * input.\n */\nexport interface Transcription {\n /**\n * The transcribed text.\n */\n text: string;\n\n /**\n * The log probabilities of the tokens in the transcription. Only returned with the\n * models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added\n * to the `include` array.\n */\n logprobs?: Array<Transcription.Logprob>;\n}\n\nexport namespace Transcription {\n export interface Logprob {\n /**\n * The token in the transcription.\n */\n token?: string;\n\n /**\n * The bytes of the token.\n */\n bytes?: Array<number>;\n\n /**\n * The log probability of the token.\n */\n logprob?: number;\n }\n}\n\nexport type TranscriptionInclude = 'logprobs';\n\nexport interface TranscriptionSegment {\n /**\n * Unique identifier of the segment.\n */\n id: number;\n\n /**\n * Average logprob of the segment. If the value is lower than -1, consider the\n * logprobs failed.\n */\n avg_logprob: number;\n\n /**\n * Compression ratio of the segment. If the value is greater than 2.4, consider the\n * compression failed.\n */\n compression_ratio: number;\n\n /**\n * End time of the segment in seconds.\n */\n end: number;\n\n /**\n * Probability of no speech in the segment. If the value is higher than 1.0 and the\n * `avg_logprob` is below -1, consider this segment silent.\n */\n no_speech_prob: number;\n\n /**\n * Seek offset of the segment.\n */\n seek: number;\n\n /**\n * Start time of the segment in seconds.\n */\n start: number;\n\n /**\n * Temperature parameter used for generating the segment.\n */\n temperature: number;\n\n /**\n * Text content of the segment.\n */\n text: string;\n\n /**\n * Array of token IDs for the text content.\n */\n tokens: Array<number>;\n}\n\n/**\n * Emitted when there is an additional text delta. This is also the first event\n * emitted when the transcription starts. Only emitted when you\n * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription)\n * with the `Stream` parameter set to `true`.\n */\nexport type TranscriptionStreamEvent = TranscriptionTextDeltaEvent | TranscriptionTextDoneEvent;\n\n/**\n * Emitted when there is an additional text delta. This is also the first event\n * emitted when the transcription starts. Only emitted when you\n * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription)\n * with the `Stream` parameter set to `true`.\n */\nexport interface TranscriptionTextDeltaEvent {\n /**\n * The text delta that was additionally transcribed.\n */\n delta: string;\n\n /**\n * The type of the event. Always `transcript.text.delta`.\n */\n type: 'transcript.text.delta';\n\n /**\n * The log probabilities of the delta. Only included if you\n * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription)\n * with the `include[]` parameter set to `logprobs`.\n */\n logprobs?: Array<TranscriptionTextDeltaEvent.Logprob>;\n}\n\nexport namespace TranscriptionTextDeltaEvent {\n export interface Logprob {\n /**\n * The token that was used to generate the log probability.\n */\n token?: string;\n\n /**\n * The bytes that were used to generate the log probability.\n */\n bytes?: Array<unknown>;\n\n /**\n * The log probability of the token.\n */\n logprob?: number;\n }\n}\n\n/**\n * Emitted when the transcription is complete. Contains the complete transcription\n * text. Only emitted when you\n * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription)\n * with the `Stream` parameter set to `true`.\n */\nexport interface TranscriptionTextDoneEvent {\n /**\n * The text that was transcribed.\n */\n text: string;\n\n /**\n * The type of the event. Always `transcript.text.done`.\n */\n type: 'transcript.text.done';\n\n /**\n * The log probabilities of the individual tokens in the transcription. Only\n * included if you\n * [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription)\n * with the `include[]` parameter set to `logprobs`.\n */\n logprobs?: Array<TranscriptionTextDoneEvent.Logprob>;\n}\n\nexport namespace TranscriptionTextDoneEvent {\n export interface Logprob {\n /**\n * The token that was used to generate the log probability.\n */\n token?: string;\n\n /**\n * The bytes that were used to generate the log probability.\n */\n bytes?: Array<unknown>;\n\n /**\n * The log probability of the token.\n */\n logprob?: number;\n }\n}\n\n/**\n * Represents a verbose json transcription response returned by model, based on the\n * provided input.\n */\nexport interface TranscriptionVerbose {\n /**\n * The duration of the input audio.\n */\n duration: number;\n\n /**\n * The language of the input audio.\n */\n language: string;\n\n /**\n * The transcribed text.\n */\n text: string;\n\n /**\n * Segments of the transcribed text and their corresponding details.\n */\n segments?: Array<TranscriptionSegment>;\n\n /**\n * Extracted words and their corresponding timestamps.\n */\n words?: Array<TranscriptionWord>;\n}\n\nexport interface TranscriptionWord {\n /**\n * End time of the word in seconds.\n */\n end: number;\n\n /**\n * Start time of the word in seconds.\n */\n start: number;\n\n /**\n * The text content of the word.\n */\n word: string;\n}\n\n/**\n * Represents a transcription response returned by model, based on the provided\n * input.\n */\nexport type TranscriptionCreateResponse = Transcription | TranscriptionVerbose;\n\nexport type TranscriptionCreateParams<\n ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined,\n> = TranscriptionCreateParamsNonStreaming<ResponseFormat> | TranscriptionCreateParamsStreaming;\n\nexport interface TranscriptionCreateParamsBase<\n ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined,\n> {\n /**\n * The audio file object (not file name) to transcribe, in one of these formats:\n * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n */\n file: Core.Uploadable;\n\n /**\n * ID of the model to use. The options are `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source\n * Whisper V2 model).\n */\n model: (string & {}) | AudioAPI.AudioModel;\n\n /**\n * Controls how the audio is cut into chunks. When set to `\"auto\"`, the server\n * first normalizes loudness and then uses voice activity detection (VAD) to choose\n * boundaries. `server_vad` object can be provided to tweak VAD detection\n * parameters manually. If unset, the audio is transcribed as a single block.\n */\n chunking_strategy?: 'auto' | TranscriptionCreateParams.VadConfig | null;\n\n /**\n * Additional information to include in the transcription response. `logprobs` will\n * return the log probabilities of the tokens in the response to understand the\n * model's confidence in the transcription. `logprobs` only works with\n * response_format set to `json` and only with the models `gpt-4o-transcribe` and\n * `gpt-4o-mini-transcribe`.\n */\n include?: Array<TranscriptionInclude>;\n\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. The\n * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting)\n * should match the audio language.\n */\n prompt?: string;\n\n /**\n * The format of the output, in one of these options: `json`, `text`, `srt`,\n * `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`,\n * the only supported format is `json`.\n */\n response_format?: ResponseFormat;\n\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)\n * for more information.\n *\n * Note: Streaming is not supported for the `whisper-1` model and will be ignored.\n */\n stream?: boolean | null;\n\n /**\n * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the\n * output more random, while lower values like 0.2 will make it more focused and\n * deterministic. If set to 0, the model will use\n * [log probability](https://en.wikipedia.org/wiki/Log_probability) to\n * automatically increase the temperature until certain thresholds are hit.\n */\n temperature?: number;\n\n /**\n * The timestamp granularities to populate for this transcription.\n * `response_format` must be set `verbose_json` to use timestamp granularities.\n * Either or both of these options are supported: `word`, or `segment`. Note: There\n * is no additional latency for segment timestamps, but generating word timestamps\n * incurs additional latency.\n */\n timestamp_granularities?: Array<'word' | 'segment'>;\n}\n\nexport namespace TranscriptionCreateParams {\n export interface VadConfig {\n /**\n * Must be set to `server_vad` to enable manual chunking using server side VAD.\n */\n type: 'server_vad';\n\n /**\n * Amount of audio to include before the VAD detected speech (in milliseconds).\n */\n prefix_padding_ms?: number;\n\n /**\n * Duration of silence to detect speech stop (in milliseconds). With shorter values\n * the model will respond more quickly, but may jump in on short pauses from the\n * user.\n */\n silence_duration_ms?: number;\n\n /**\n * Sensitivity threshold (0.0 to 1.0) for voice activity detection. A higher\n * threshold will require louder audio to activate the model, and thus might\n * perform better in noisy environments.\n */\n threshold?: number;\n }\n\n export type TranscriptionCreateParamsNonStreaming = TranscriptionsAPI.TranscriptionCreateParamsNonStreaming;\n export type TranscriptionCreateParamsStreaming = TranscriptionsAPI.TranscriptionCreateParamsStreaming;\n}\n\nexport interface TranscriptionCreateParamsNonStreaming<\n ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined,\n> extends TranscriptionCreateParamsBase<ResponseFormat> {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)\n * for more information.\n *\n * Note: Streaming is not supported for the `whisper-1` model and will be ignored.\n */\n stream?: false | null;\n}\n\nexport interface TranscriptionCreateParamsStreaming extends TranscriptionCreateParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)\n * for more information.\n *\n * Note: Streaming is not supported for the `whisper-1` model and will be ignored.\n */\n stream: true;\n}\n\nexport declare namespace Transcriptions {\n export {\n type Transcription as Transcription,\n type TranscriptionInclude as TranscriptionInclude,\n type TranscriptionSegment as TranscriptionSegment,\n type TranscriptionStreamEvent as TranscriptionStreamEvent,\n type TranscriptionTextDeltaEvent as TranscriptionTextDeltaEvent,\n type TranscriptionTextDoneEvent as TranscriptionTextDoneEvent,\n type TranscriptionVerbose as TranscriptionVerbose,\n type TranscriptionWord as TranscriptionWord,\n type TranscriptionCreateResponse as TranscriptionCreateResponse,\n type TranscriptionCreateParams as TranscriptionCreateParams,\n type TranscriptionCreateParamsNonStreaming as TranscriptionCreateParamsNonStreaming,\n type TranscriptionCreateParamsStreaming as TranscriptionCreateParamsStreaming,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as Core from '../../core';\nimport * as AudioAPI from './audio';\nimport * as TranscriptionsAPI from './transcriptions';\n\nexport class Translations extends APIResource {\n /**\n * Translates audio into English.\n *\n * @example\n * ```ts\n * const translation = await client.audio.translations.create({\n * file: fs.createReadStream('speech.mp3'),\n * model: 'whisper-1',\n * });\n * ```\n */\n create(\n body: TranslationCreateParams<'json' | undefined>,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Translation>;\n create(\n body: TranslationCreateParams<'verbose_json'>,\n options?: Core.RequestOptions,\n ): Core.APIPromise<TranslationVerbose>;\n create(\n body: TranslationCreateParams<'text' | 'srt' | 'vtt'>,\n options?: Core.RequestOptions,\n ): Core.APIPromise<string>;\n create(body: TranslationCreateParams, options?: Core.RequestOptions): Core.APIPromise<Translation>;\n create(\n body: TranslationCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<TranslationCreateResponse | string> {\n return this._client.post(\n '/audio/translations',\n Core.multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }),\n );\n }\n}\n\nexport interface Translation {\n text: string;\n}\n\nexport interface TranslationVerbose {\n /**\n * The duration of the input audio.\n */\n duration: number;\n\n /**\n * The language of the output translation (always `english`).\n */\n language: string;\n\n /**\n * The translated text.\n */\n text: string;\n\n /**\n * Segments of the translated text and their corresponding details.\n */\n segments?: Array<TranscriptionsAPI.TranscriptionSegment>;\n}\n\nexport type TranslationCreateResponse = Translation | TranslationVerbose;\n\nexport interface TranslationCreateParams<\n ResponseFormat extends AudioAPI.AudioResponseFormat | undefined = AudioAPI.AudioResponseFormat | undefined,\n> {\n /**\n * The audio file object (not file name) translate, in one of these formats: flac,\n * mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n */\n file: Core.Uploadable;\n\n /**\n * ID of the model to use. Only `whisper-1` (which is powered by our open source\n * Whisper V2 model) is currently available.\n */\n model: (string & {}) | AudioAPI.AudioModel;\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. The\n * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting)\n * should be in English.\n */\n prompt?: string;\n\n /**\n * The format of the output, in one of these options: `json`, `text`, `srt`,\n * `verbose_json`, or `vtt`.\n */\n response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt';\n\n /**\n * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the\n * output more random, while lower values like 0.2 will make it more focused and\n * deterministic. If set to 0, the model will use\n * [log probability](https://en.wikipedia.org/wiki/Log_probability) to\n * automatically increase the temperature until certain thresholds are hit.\n */\n temperature?: number;\n}\n\nexport declare namespace Translations {\n export {\n type Translation as Translation,\n type TranslationVerbose as TranslationVerbose,\n type TranslationCreateResponse as TranslationCreateResponse,\n type TranslationCreateParams as TranslationCreateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as SpeechAPI from './speech';\nimport { Speech, SpeechCreateParams, SpeechModel } from './speech';\nimport * as TranscriptionsAPI from './transcriptions';\nimport {\n Transcription,\n TranscriptionCreateParams,\n TranscriptionCreateParamsNonStreaming,\n TranscriptionCreateParamsStreaming,\n TranscriptionCreateResponse,\n TranscriptionInclude,\n TranscriptionSegment,\n TranscriptionStreamEvent,\n TranscriptionTextDeltaEvent,\n TranscriptionTextDoneEvent,\n TranscriptionVerbose,\n TranscriptionWord,\n Transcriptions,\n} from './transcriptions';\nimport * as TranslationsAPI from './translations';\nimport {\n Translation,\n TranslationCreateParams,\n TranslationCreateResponse,\n TranslationVerbose,\n Translations,\n} from './translations';\n\nexport class Audio extends APIResource {\n transcriptions: TranscriptionsAPI.Transcriptions = new TranscriptionsAPI.Transcriptions(this._client);\n translations: TranslationsAPI.Translations = new TranslationsAPI.Translations(this._client);\n speech: SpeechAPI.Speech = new SpeechAPI.Speech(this._client);\n}\n\nexport type AudioModel = 'whisper-1' | 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe';\n\n/**\n * The format of the output, in one of these options: `json`, `text`, `srt`,\n * `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`,\n * the only supported format is `json`.\n */\nexport type AudioResponseFormat = 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt';\n\nAudio.Transcriptions = Transcriptions;\nAudio.Translations = Translations;\nAudio.Speech = Speech;\n\nexport declare namespace Audio {\n export { type AudioModel as AudioModel, type AudioResponseFormat as AudioResponseFormat };\n\n export {\n Transcriptions as Transcriptions,\n type Transcription as Transcription,\n type TranscriptionInclude as TranscriptionInclude,\n type TranscriptionSegment as TranscriptionSegment,\n type TranscriptionStreamEvent as TranscriptionStreamEvent,\n type TranscriptionTextDeltaEvent as TranscriptionTextDeltaEvent,\n type TranscriptionTextDoneEvent as TranscriptionTextDoneEvent,\n type TranscriptionVerbose as TranscriptionVerbose,\n type TranscriptionWord as TranscriptionWord,\n type TranscriptionCreateResponse as TranscriptionCreateResponse,\n type TranscriptionCreateParams as TranscriptionCreateParams,\n type TranscriptionCreateParamsNonStreaming as TranscriptionCreateParamsNonStreaming,\n type TranscriptionCreateParamsStreaming as TranscriptionCreateParamsStreaming,\n };\n\n export {\n Translations as Translations,\n type Translation as Translation,\n type TranslationVerbose as TranslationVerbose,\n type TranslationCreateResponse as TranslationCreateResponse,\n type TranslationCreateParams as TranslationCreateParams,\n };\n\n export { Speech as Speech, type SpeechModel as SpeechModel, type SpeechCreateParams as SpeechCreateParams };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport { isRequestOptions } from '../core';\nimport * as Core from '../core';\nimport * as BatchesAPI from './batches';\nimport * as Shared from './shared';\nimport { CursorPage, type CursorPageParams } from '../pagination';\n\nexport class Batches extends APIResource {\n /**\n * Creates and executes a batch from an uploaded file of requests\n */\n create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<Batch> {\n return this._client.post('/batches', { body, ...options });\n }\n\n /**\n * Retrieves a batch.\n */\n retrieve(batchId: string, options?: Core.RequestOptions): Core.APIPromise<Batch> {\n return this._client.get(`/batches/${batchId}`, options);\n }\n\n /**\n * List your organization's batches.\n */\n list(query?: BatchListParams, options?: Core.RequestOptions): Core.PagePromise<BatchesPage, Batch>;\n list(options?: Core.RequestOptions): Core.PagePromise<BatchesPage, Batch>;\n list(\n query: BatchListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<BatchesPage, Batch> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/batches', BatchesPage, { query, ...options });\n }\n\n /**\n * Cancels an in-progress batch. The batch will be in status `cancelling` for up to\n * 10 minutes, before changing to `cancelled`, where it will have partial results\n * (if any) available in the output file.\n */\n cancel(batchId: string, options?: Core.RequestOptions): Core.APIPromise<Batch> {\n return this._client.post(`/batches/${batchId}/cancel`, options);\n }\n}\n\nexport class BatchesPage extends CursorPage<Batch> {}\n\nexport interface Batch {\n id: string;\n\n /**\n * The time frame within which the batch should be processed.\n */\n completion_window: string;\n\n /**\n * The Unix timestamp (in seconds) for when the batch was created.\n */\n created_at: number;\n\n /**\n * The OpenAI API endpoint used by the batch.\n */\n endpoint: string;\n\n /**\n * The ID of the input file for the batch.\n */\n input_file_id: string;\n\n /**\n * The object type, which is always `batch`.\n */\n object: 'batch';\n\n /**\n * The current status of the batch.\n */\n status:\n | 'validating'\n | 'failed'\n | 'in_progress'\n | 'finalizing'\n | 'completed'\n | 'expired'\n | 'cancelling'\n | 'cancelled';\n\n /**\n * The Unix timestamp (in seconds) for when the batch was cancelled.\n */\n cancelled_at?: number;\n\n /**\n * The Unix timestamp (in seconds) for when the batch started cancelling.\n */\n cancelling_at?: number;\n\n /**\n * The Unix timestamp (in seconds) for when the batch was completed.\n */\n completed_at?: number;\n\n /**\n * The ID of the file containing the outputs of requests with errors.\n */\n error_file_id?: string;\n\n errors?: Batch.Errors;\n\n /**\n * The Unix timestamp (in seconds) for when the batch expired.\n */\n expired_at?: number;\n\n /**\n * The Unix timestamp (in seconds) for when the batch will expire.\n */\n expires_at?: number;\n\n /**\n * The Unix timestamp (in seconds) for when the batch failed.\n */\n failed_at?: number;\n\n /**\n * The Unix timestamp (in seconds) for when the batch started finalizing.\n */\n finalizing_at?: number;\n\n /**\n * The Unix timestamp (in seconds) for when the batch started processing.\n */\n in_progress_at?: number;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The ID of the file containing the outputs of successfully executed requests.\n */\n output_file_id?: string;\n\n /**\n * The request counts for different statuses within the batch.\n */\n request_counts?: BatchRequestCounts;\n}\n\nexport namespace Batch {\n export interface Errors {\n data?: Array<BatchesAPI.BatchError>;\n\n /**\n * The object type, which is always `list`.\n */\n object?: string;\n }\n}\n\nexport interface BatchError {\n /**\n * An error code identifying the error type.\n */\n code?: string;\n\n /**\n * The line number of the input file where the error occurred, if applicable.\n */\n line?: number | null;\n\n /**\n * A human-readable message providing more details about the error.\n */\n message?: string;\n\n /**\n * The name of the parameter that caused the error, if applicable.\n */\n param?: string | null;\n}\n\n/**\n * The request counts for different statuses within the batch.\n */\nexport interface BatchRequestCounts {\n /**\n * Number of requests that have been completed successfully.\n */\n completed: number;\n\n /**\n * Number of requests that have failed.\n */\n failed: number;\n\n /**\n * Total number of requests in the batch.\n */\n total: number;\n}\n\nexport interface BatchCreateParams {\n /**\n * The time frame within which the batch should be processed. Currently only `24h`\n * is supported.\n */\n completion_window: '24h';\n\n /**\n * The endpoint to be used for all requests in the batch. Currently\n * `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions`\n * are supported. Note that `/v1/embeddings` batches are also restricted to a\n * maximum of 50,000 embedding inputs across all requests in the batch.\n */\n endpoint: '/v1/responses' | '/v1/chat/completions' | '/v1/embeddings' | '/v1/completions';\n\n /**\n * The ID of an uploaded file that contains requests for the new batch.\n *\n * See [upload file](https://platform.openai.com/docs/api-reference/files/create)\n * for how to upload a file.\n *\n * Your input file must be formatted as a\n * [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input),\n * and must be uploaded with the purpose `batch`. The file can contain up to 50,000\n * requests, and can be up to 200 MB in size.\n */\n input_file_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n}\n\nexport interface BatchListParams extends CursorPageParams {}\n\nBatches.BatchesPage = BatchesPage;\n\nexport declare namespace Batches {\n export {\n type Batch as Batch,\n type BatchError as BatchError,\n type BatchRequestCounts as BatchRequestCounts,\n BatchesPage as BatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n","import { APIUserAbortError, OpenAIError } from '../error';\n\nexport class EventStream<EventTypes extends BaseEvents> {\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<void>;\n #resolveConnectedPromise: () => void = () => {};\n #rejectConnectedPromise: (error: OpenAIError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: OpenAIError) => void = () => {};\n\n #listeners: {\n [Event in keyof EventTypes]?: EventListeners<EventTypes, Event>;\n } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n\n constructor() {\n this.#connectedPromise = new Promise<void>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n }\n\n protected _run(this: EventStream<EventTypes>, executor: () => Promise<any>) {\n // Unfortunately if we call `executor()` immediately we get runtime errors about\n // references to `this` before the `super()` constructor call returns.\n setTimeout(() => {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError.bind(this));\n }, 0);\n }\n\n protected _connected(this: EventStream<EventTypes>) {\n if (this.ended) return;\n this.#resolveConnectedPromise();\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n on<Event extends keyof EventTypes>(event: Event, listener: EventListener<EventTypes, Event>): this {\n const listeners: EventListeners<EventTypes, Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n off<Event extends keyof EventTypes>(event: Event, listener: EventListener<EventTypes, Event>): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n once<Event extends keyof EventTypes>(event: Event, listener: EventListener<EventTypes, Event>): this {\n const listeners: EventListeners<EventTypes, Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof EventTypes>(\n event: Event,\n ): Promise<\n EventParameters<EventTypes, Event> extends [infer Param] ? Param\n : EventParameters<EventTypes, Event> extends [] ? void\n : EventParameters<EventTypes, Event>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n #handleError(this: EventStream<EventTypes>, error: unknown) {\n this.#errored = true;\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof OpenAIError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const openAIError: OpenAIError = new OpenAIError(error.message);\n // @ts-ignore\n openAIError.cause = error;\n return this._emit('error', openAIError);\n }\n return this._emit('error', new OpenAIError(String(error)));\n }\n\n _emit<Event extends keyof BaseEvents>(event: Event, ...args: EventParameters<BaseEvents, Event>): void;\n _emit<Event extends keyof EventTypes>(event: Event, ...args: EventParameters<EventTypes, Event>): void;\n _emit<Event extends keyof EventTypes>(\n this: EventStream<EventTypes>,\n event: Event,\n ...args: EventParameters<EventTypes, Event>\n ) {\n // make sure we don't emit any events after end\n if (this.#ended) {\n return;\n }\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: EventListeners<EventTypes, Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...(args as any)));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as OpenAIError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.finalChatCompletion()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal(): void {}\n}\n\ntype EventListener<Events, EventType extends keyof Events> = Events[EventType];\n\ntype EventListeners<Events, EventType extends keyof Events> = Array<{\n listener: EventListener<Events, EventType>;\n once?: boolean;\n}>;\n\nexport type EventParameters<Events, EventType extends keyof Events> = {\n [Event in EventType]: EventListener<Events, EventType> extends (...args: infer P) => any ? P : never;\n}[EventType];\n\nexport interface BaseEvents {\n connect: () => void;\n error: (error: OpenAIError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n","import {\n TextContentBlock,\n ImageFileContentBlock,\n Message,\n MessageContentDelta,\n Text,\n ImageFile,\n TextDelta,\n MessageDelta,\n MessageContent,\n} from '../resources/beta/threads/messages';\nimport * as Core from '../core';\nimport { RequestOptions } from '../core';\nimport {\n Run,\n RunCreateParamsBase,\n RunCreateParamsStreaming,\n Runs,\n RunSubmitToolOutputsParamsBase,\n RunSubmitToolOutputsParamsStreaming,\n} from '../resources/beta/threads/runs/runs';\nimport { type ReadableStream } from '../_shims/index';\nimport { Stream } from '../streaming';\nimport { APIUserAbortError, OpenAIError } from '../error';\nimport {\n AssistantStreamEvent,\n MessageStreamEvent,\n RunStepStreamEvent,\n RunStreamEvent,\n} from '../resources/beta/assistants';\nimport { RunStep, RunStepDelta, ToolCall, ToolCallDelta } from '../resources/beta/threads/runs/steps';\nimport { ThreadCreateAndRunParamsBase, Threads } from '../resources/beta/threads/threads';\nimport { BaseEvents, EventStream } from './EventStream';\n\nexport interface AssistantStreamEvents extends BaseEvents {\n run: (run: Run) => void;\n\n //New event structure\n messageCreated: (message: Message) => void;\n messageDelta: (message: MessageDelta, snapshot: Message) => void;\n messageDone: (message: Message) => void;\n\n runStepCreated: (runStep: RunStep) => void;\n runStepDelta: (delta: RunStepDelta, snapshot: Runs.RunStep) => void;\n runStepDone: (runStep: Runs.RunStep, snapshot: Runs.RunStep) => void;\n\n toolCallCreated: (toolCall: ToolCall) => void;\n toolCallDelta: (delta: ToolCallDelta, snapshot: ToolCall) => void;\n toolCallDone: (toolCall: ToolCall) => void;\n\n textCreated: (content: Text) => void;\n textDelta: (delta: TextDelta, snapshot: Text) => void;\n textDone: (content: Text, snapshot: Message) => void;\n\n //No created or delta as this is not streamed\n imageFileDone: (content: ImageFile, snapshot: Message) => void;\n\n event: (event: AssistantStreamEvent) => void;\n}\n\nexport type ThreadCreateAndRunParamsBaseStream = Omit<ThreadCreateAndRunParamsBase, 'stream'> & {\n stream?: true;\n};\n\nexport type RunCreateParamsBaseStream = Omit<RunCreateParamsBase, 'stream'> & {\n stream?: true;\n};\n\nexport type RunSubmitToolOutputsParamsStream = Omit<RunSubmitToolOutputsParamsBase, 'stream'> & {\n stream?: true;\n};\n\nexport class AssistantStream\n extends EventStream<AssistantStreamEvents>\n implements AsyncIterable<AssistantStreamEvent>\n{\n //Track all events in a single list for reference\n #events: AssistantStreamEvent[] = [];\n\n //Used to accumulate deltas\n //We are accumulating many types so the value here is not strict\n #runStepSnapshots: { [id: string]: Runs.RunStep } = {};\n #messageSnapshots: { [id: string]: Message } = {};\n #messageSnapshot: Message | undefined;\n #finalRun: Run | undefined;\n #currentContentIndex: number | undefined;\n #currentContent: MessageContent | undefined;\n #currentToolCallIndex: number | undefined;\n #currentToolCall: ToolCall | undefined;\n\n //For current snapshot methods\n #currentEvent: AssistantStreamEvent | undefined;\n #currentRunSnapshot: Run | undefined;\n #currentRunStepSnapshot: Runs.RunStep | undefined;\n\n [Symbol.asyncIterator](): AsyncIterator<AssistantStreamEvent> {\n const pushQueue: AssistantStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: AssistantStreamEvent | undefined) => void;\n reject: (err: unknown) => void;\n }[] = [];\n let done = false;\n\n //Catch all for passing along all events\n this.on('event', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<AssistantStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<AssistantStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n static fromReadableStream(stream: ReadableStream): AssistantStream {\n const runner = new AssistantStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this._connected();\n const stream = Stream.fromReadableStream<AssistantStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(this.#endRequest());\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n\n static createToolAssistantStream(\n threadId: string,\n runId: string,\n runs: Runs,\n params: RunSubmitToolOutputsParamsStream,\n options: RequestOptions | undefined,\n ): AssistantStream {\n const runner = new AssistantStream();\n runner._run(() =>\n runner._runToolAssistantStream(threadId, runId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }),\n );\n return runner;\n }\n\n protected async _createToolAssistantStream(\n run: Runs,\n threadId: string,\n runId: string,\n params: RunSubmitToolOutputsParamsStream,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n\n const body: RunSubmitToolOutputsParamsStreaming = { ...params, stream: true };\n const stream = await run.submitToolOutputs(threadId, runId, body, {\n ...options,\n signal: this.controller.signal,\n });\n\n this._connected();\n\n for await (const event of stream) {\n this.#addEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n\n return this._addRun(this.#endRequest());\n }\n\n static createThreadAssistantStream(\n params: ThreadCreateAndRunParamsBaseStream,\n thread: Threads,\n options?: RequestOptions,\n ): AssistantStream {\n const runner = new AssistantStream();\n runner._run(() =>\n runner._threadAssistantStream(params, thread, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }),\n );\n return runner;\n }\n\n static createAssistantStream(\n threadId: string,\n runs: Runs,\n params: RunCreateParamsBaseStream,\n options?: RequestOptions,\n ): AssistantStream {\n const runner = new AssistantStream();\n runner._run(() =>\n runner._runAssistantStream(threadId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }),\n );\n return runner;\n }\n\n currentEvent(): AssistantStreamEvent | undefined {\n return this.#currentEvent;\n }\n\n currentRun(): Run | undefined {\n return this.#currentRunSnapshot;\n }\n\n currentMessageSnapshot(): Message | undefined {\n return this.#messageSnapshot;\n }\n\n currentRunStepSnapshot(): Runs.RunStep | undefined {\n return this.#currentRunStepSnapshot;\n }\n\n async finalRunSteps(): Promise<Runs.RunStep[]> {\n await this.done();\n\n return Object.values(this.#runStepSnapshots);\n }\n\n async finalMessages(): Promise<Message[]> {\n await this.done();\n\n return Object.values(this.#messageSnapshots);\n }\n\n async finalRun(): Promise<Run> {\n await this.done();\n if (!this.#finalRun) throw Error('Final run was not received.');\n\n return this.#finalRun;\n }\n\n protected async _createThreadAssistantStream(\n thread: Threads,\n params: ThreadCreateAndRunParamsBase,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n\n const body: RunCreateParamsStreaming = { ...params, stream: true };\n const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });\n\n this._connected();\n\n for await (const event of stream) {\n this.#addEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n\n return this._addRun(this.#endRequest());\n }\n\n protected async _createAssistantStream(\n run: Runs,\n threadId: string,\n params: RunCreateParamsBase,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n\n const body: RunCreateParamsStreaming = { ...params, stream: true };\n const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });\n\n this._connected();\n\n for await (const event of stream) {\n this.#addEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n\n return this._addRun(this.#endRequest());\n }\n\n #addEvent(event: AssistantStreamEvent) {\n if (this.ended) return;\n\n this.#currentEvent = event;\n\n this.#handleEvent(event);\n\n switch (event.event) {\n case 'thread.created':\n //No action on this event.\n break;\n\n case 'thread.run.created':\n case 'thread.run.queued':\n case 'thread.run.in_progress':\n case 'thread.run.requires_action':\n case 'thread.run.completed':\n case 'thread.run.incomplete':\n case 'thread.run.failed':\n case 'thread.run.cancelling':\n case 'thread.run.cancelled':\n case 'thread.run.expired':\n this.#handleRun(event);\n break;\n\n case 'thread.run.step.created':\n case 'thread.run.step.in_progress':\n case 'thread.run.step.delta':\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n this.#handleRunStep(event);\n break;\n\n case 'thread.message.created':\n case 'thread.message.in_progress':\n case 'thread.message.delta':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n this.#handleMessage(event);\n break;\n\n case 'error':\n //This is included for completeness, but errors are processed in the SSE event processing so this should not occur\n throw new Error(\n 'Encountered an error event in event processing - errors should be processed earlier',\n );\n default:\n assertNever(event);\n }\n }\n\n #endRequest(): Run {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n\n if (!this.#finalRun) throw Error('Final run has not been received');\n\n return this.#finalRun;\n }\n\n #handleMessage(this: AssistantStream, event: MessageStreamEvent) {\n const [accumulatedMessage, newContent] = this.#accumulateMessage(event, this.#messageSnapshot);\n this.#messageSnapshot = accumulatedMessage;\n this.#messageSnapshots[accumulatedMessage.id] = accumulatedMessage;\n\n for (const content of newContent) {\n const snapshotContent = accumulatedMessage.content[content.index];\n if (snapshotContent?.type == 'text') {\n this._emit('textCreated', snapshotContent.text);\n }\n }\n\n switch (event.event) {\n case 'thread.message.created':\n this._emit('messageCreated', event.data);\n break;\n\n case 'thread.message.in_progress':\n break;\n\n case 'thread.message.delta':\n this._emit('messageDelta', event.data.delta, accumulatedMessage);\n\n if (event.data.delta.content) {\n for (const content of event.data.delta.content) {\n //If it is text delta, emit a text delta event\n if (content.type == 'text' && content.text) {\n let textDelta = content.text;\n let snapshot = accumulatedMessage.content[content.index];\n if (snapshot && snapshot.type == 'text') {\n this._emit('textDelta', textDelta, snapshot.text);\n } else {\n throw Error('The snapshot associated with this text delta is not text or missing');\n }\n }\n\n if (content.index != this.#currentContentIndex) {\n //See if we have in progress content\n if (this.#currentContent) {\n switch (this.#currentContent.type) {\n case 'text':\n this._emit('textDone', this.#currentContent.text, this.#messageSnapshot);\n break;\n case 'image_file':\n this._emit('imageFileDone', this.#currentContent.image_file, this.#messageSnapshot);\n break;\n }\n }\n\n this.#currentContentIndex = content.index;\n }\n\n this.#currentContent = accumulatedMessage.content[content.index];\n }\n }\n\n break;\n\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //We emit the latest content we were working on on completion (including incomplete)\n if (this.#currentContentIndex !== undefined) {\n const currentContent = event.data.content[this.#currentContentIndex];\n if (currentContent) {\n switch (currentContent.type) {\n case 'image_file':\n this._emit('imageFileDone', currentContent.image_file, this.#messageSnapshot);\n break;\n case 'text':\n this._emit('textDone', currentContent.text, this.#messageSnapshot);\n break;\n }\n }\n }\n\n if (this.#messageSnapshot) {\n this._emit('messageDone', event.data);\n }\n\n this.#messageSnapshot = undefined;\n }\n }\n\n #handleRunStep(this: AssistantStream, event: RunStepStreamEvent) {\n const accumulatedRunStep = this.#accumulateRunStep(event);\n this.#currentRunStepSnapshot = accumulatedRunStep;\n\n switch (event.event) {\n case 'thread.run.step.created':\n this._emit('runStepCreated', event.data);\n break;\n case 'thread.run.step.delta':\n const delta = event.data.delta;\n if (\n delta.step_details &&\n delta.step_details.type == 'tool_calls' &&\n delta.step_details.tool_calls &&\n accumulatedRunStep.step_details.type == 'tool_calls'\n ) {\n for (const toolCall of delta.step_details.tool_calls) {\n if (toolCall.index == this.#currentToolCallIndex) {\n this._emit(\n 'toolCallDelta',\n toolCall,\n accumulatedRunStep.step_details.tool_calls[toolCall.index] as ToolCall,\n );\n } else {\n if (this.#currentToolCall) {\n this._emit('toolCallDone', this.#currentToolCall);\n }\n\n this.#currentToolCallIndex = toolCall.index;\n this.#currentToolCall = accumulatedRunStep.step_details.tool_calls[toolCall.index];\n if (this.#currentToolCall) this._emit('toolCallCreated', this.#currentToolCall);\n }\n }\n }\n\n this._emit('runStepDelta', event.data.delta, accumulatedRunStep);\n break;\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n this.#currentRunStepSnapshot = undefined;\n const details = event.data.step_details;\n if (details.type == 'tool_calls') {\n if (this.#currentToolCall) {\n this._emit('toolCallDone', this.#currentToolCall as ToolCall);\n this.#currentToolCall = undefined;\n }\n }\n this._emit('runStepDone', event.data, accumulatedRunStep);\n break;\n case 'thread.run.step.in_progress':\n break;\n }\n }\n\n #handleEvent(this: AssistantStream, event: AssistantStreamEvent) {\n this.#events.push(event);\n this._emit('event', event);\n }\n\n #accumulateRunStep(event: RunStepStreamEvent): Runs.RunStep {\n switch (event.event) {\n case 'thread.run.step.created':\n this.#runStepSnapshots[event.data.id] = event.data;\n return event.data;\n\n case 'thread.run.step.delta':\n let snapshot = this.#runStepSnapshots[event.data.id] as Runs.RunStep;\n if (!snapshot) {\n throw Error('Received a RunStepDelta before creation of a snapshot');\n }\n\n let data = event.data;\n\n if (data.delta) {\n const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta) as Runs.RunStep;\n this.#runStepSnapshots[event.data.id] = accumulated;\n }\n\n return this.#runStepSnapshots[event.data.id] as Runs.RunStep;\n\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n case 'thread.run.step.in_progress':\n this.#runStepSnapshots[event.data.id] = event.data;\n break;\n }\n\n if (this.#runStepSnapshots[event.data.id]) return this.#runStepSnapshots[event.data.id] as Runs.RunStep;\n throw new Error('No snapshot available');\n }\n\n #accumulateMessage(\n event: AssistantStreamEvent,\n snapshot: Message | undefined,\n ): [Message, MessageContentDelta[]] {\n let newContent: MessageContentDelta[] = [];\n\n switch (event.event) {\n case 'thread.message.created':\n //On creation the snapshot is just the initial message\n return [event.data, newContent];\n\n case 'thread.message.delta':\n if (!snapshot) {\n throw Error(\n 'Received a delta with no existing snapshot (there should be one from message creation)',\n );\n }\n\n let data = event.data;\n\n //If this delta does not have content, nothing to process\n if (data.delta.content) {\n for (const contentElement of data.delta.content) {\n if (contentElement.index in snapshot.content) {\n let currentContent = snapshot.content[contentElement.index];\n snapshot.content[contentElement.index] = this.#accumulateContent(\n contentElement,\n currentContent,\n );\n } else {\n snapshot.content[contentElement.index] = contentElement as MessageContent;\n // This is a new element\n newContent.push(contentElement);\n }\n }\n }\n\n return [snapshot, newContent];\n\n case 'thread.message.in_progress':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //No changes on other thread events\n if (snapshot) {\n return [snapshot, newContent];\n } else {\n throw Error('Received thread message event with no existing snapshot');\n }\n }\n throw Error('Tried to accumulate a non-message event');\n }\n\n #accumulateContent(\n contentElement: MessageContentDelta,\n currentContent: MessageContent | undefined,\n ): TextContentBlock | ImageFileContentBlock {\n return AssistantStream.accumulateDelta(currentContent as unknown as Record<any, any>, contentElement) as\n | TextContentBlock\n | ImageFileContentBlock;\n }\n\n static accumulateDelta(acc: Record<string, any>, delta: Record<string, any>): Record<string, any> {\n for (const [key, deltaValue] of Object.entries(delta)) {\n if (!acc.hasOwnProperty(key)) {\n acc[key] = deltaValue;\n continue;\n }\n\n let accValue = acc[key];\n if (accValue === null || accValue === undefined) {\n acc[key] = deltaValue;\n continue;\n }\n\n // We don't accumulate these special properties\n if (key === 'index' || key === 'type') {\n acc[key] = deltaValue;\n continue;\n }\n\n // Type-specific accumulation logic\n if (typeof accValue === 'string' && typeof deltaValue === 'string') {\n accValue += deltaValue;\n } else if (typeof accValue === 'number' && typeof deltaValue === 'number') {\n accValue += deltaValue;\n } else if (Core.isObj(accValue) && Core.isObj(deltaValue)) {\n accValue = this.accumulateDelta(accValue as Record<string, any>, deltaValue as Record<string, any>);\n } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {\n if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) {\n accValue.push(...deltaValue); // Use spread syntax for efficient addition\n continue;\n }\n\n for (const deltaEntry of deltaValue) {\n if (!Core.isObj(deltaEntry)) {\n throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);\n }\n\n const index = deltaEntry['index'];\n if (index == null) {\n console.error(deltaEntry);\n throw new Error('Expected array delta entry to have an `index` property');\n }\n\n if (typeof index !== 'number') {\n throw new Error(`Expected array delta entry \\`index\\` property to be a number but got ${index}`);\n }\n\n const accEntry = accValue[index];\n if (accEntry == null) {\n accValue.push(deltaEntry);\n } else {\n accValue[index] = this.accumulateDelta(accEntry, deltaEntry);\n }\n }\n continue;\n } else {\n throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);\n }\n acc[key] = accValue;\n }\n\n return acc;\n }\n\n #handleRun(this: AssistantStream, event: RunStreamEvent) {\n this.#currentRunSnapshot = event.data;\n switch (event.event) {\n case 'thread.run.created':\n break;\n case 'thread.run.queued':\n break;\n case 'thread.run.in_progress':\n break;\n case 'thread.run.requires_action':\n case 'thread.run.cancelled':\n case 'thread.run.failed':\n case 'thread.run.completed':\n case 'thread.run.expired':\n this.#finalRun = event.data;\n if (this.#currentToolCall) {\n this._emit('toolCallDone', this.#currentToolCall);\n this.#currentToolCall = undefined;\n }\n break;\n case 'thread.run.cancelling':\n break;\n }\n }\n\n protected _addRun(run: Run): Run {\n return run;\n }\n\n protected async _threadAssistantStream(\n params: ThreadCreateAndRunParamsBase,\n thread: Threads,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n return await this._createThreadAssistantStream(thread, params, options);\n }\n\n protected async _runAssistantStream(\n threadId: string,\n runs: Runs,\n params: RunCreateParamsBase,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n return await this._createAssistantStream(runs, threadId, params, options);\n }\n\n protected async _runToolAssistantStream(\n threadId: string,\n runId: string,\n runs: Runs,\n params: RunSubmitToolOutputsParamsStream,\n options?: Core.RequestOptions,\n ): Promise<Run> {\n return await this._createToolAssistantStream(runs, threadId, runId, params, options);\n }\n}\n\nfunction assertNever(_x: never) {}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { isRequestOptions } from '../../core';\nimport * as Core from '../../core';\nimport * as Shared from '../shared';\nimport * as MessagesAPI from './threads/messages';\nimport * as ThreadsAPI from './threads/threads';\nimport * as RunsAPI from './threads/runs/runs';\nimport * as StepsAPI from './threads/runs/steps';\nimport { CursorPage, type CursorPageParams } from '../../pagination';\nimport { AssistantStream } from '../../lib/AssistantStream';\n\nexport class Assistants extends APIResource {\n /**\n * Create an assistant with a model and instructions.\n *\n * @example\n * ```ts\n * const assistant = await client.beta.assistants.create({\n * model: 'gpt-4o',\n * });\n * ```\n */\n create(body: AssistantCreateParams, options?: Core.RequestOptions): Core.APIPromise<Assistant> {\n return this._client.post('/assistants', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Retrieves an assistant.\n *\n * @example\n * ```ts\n * const assistant = await client.beta.assistants.retrieve(\n * 'assistant_id',\n * );\n * ```\n */\n retrieve(assistantId: string, options?: Core.RequestOptions): Core.APIPromise<Assistant> {\n return this._client.get(`/assistants/${assistantId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Modifies an assistant.\n *\n * @example\n * ```ts\n * const assistant = await client.beta.assistants.update(\n * 'assistant_id',\n * );\n * ```\n */\n update(\n assistantId: string,\n body: AssistantUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Assistant> {\n return this._client.post(`/assistants/${assistantId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Returns a list of assistants.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const assistant of client.beta.assistants.list()) {\n * // ...\n * }\n * ```\n */\n list(\n query?: AssistantListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<AssistantsPage, Assistant>;\n list(options?: Core.RequestOptions): Core.PagePromise<AssistantsPage, Assistant>;\n list(\n query: AssistantListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<AssistantsPage, Assistant> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/assistants', AssistantsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Delete an assistant.\n *\n * @example\n * ```ts\n * const assistantDeleted = await client.beta.assistants.del(\n * 'assistant_id',\n * );\n * ```\n */\n del(assistantId: string, options?: Core.RequestOptions): Core.APIPromise<AssistantDeleted> {\n return this._client.delete(`/assistants/${assistantId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n\nexport class AssistantsPage extends CursorPage<Assistant> {}\n\n/**\n * Represents an `assistant` that can call the model and use tools.\n */\nexport interface Assistant {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the assistant was created.\n */\n created_at: number;\n\n /**\n * The description of the assistant. The maximum length is 512 characters.\n */\n description: string | null;\n\n /**\n * The system instructions that the assistant uses. The maximum length is 256,000\n * characters.\n */\n instructions: string | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * ID of the model to use. You can use the\n * [List models](https://platform.openai.com/docs/api-reference/models/list) API to\n * see all of your available models, or see our\n * [Model overview](https://platform.openai.com/docs/models) for descriptions of\n * them.\n */\n model: string;\n\n /**\n * The name of the assistant. The maximum length is 256 characters.\n */\n name: string | null;\n\n /**\n * The object type, which is always `assistant`.\n */\n object: 'assistant';\n\n /**\n * A list of tool enabled on the assistant. There can be a maximum of 128 tools per\n * assistant. Tools can be of types `code_interpreter`, `file_search`, or\n * `function`.\n */\n tools: Array<AssistantTool>;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n tool_resources?: Assistant.ToolResources | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n}\n\nexport namespace Assistant {\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter`` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n }\n }\n}\n\nexport interface AssistantDeleted {\n id: string;\n\n deleted: boolean;\n\n object: 'assistant.deleted';\n}\n\n/**\n * Represents an event emitted when streaming a Run.\n *\n * Each event in a server-sent events stream has an `event` and `data` property:\n *\n * ```\n * event: thread.created\n * data: {\"id\": \"thread_123\", \"object\": \"thread\", ...}\n * ```\n *\n * We emit events whenever a new object is created, transitions to a new state, or\n * is being streamed in parts (deltas). For example, we emit `thread.run.created`\n * when a new run is created, `thread.run.completed` when a run completes, and so\n * on. When an Assistant chooses to create a message during a run, we emit a\n * `thread.message.created event`, a `thread.message.in_progress` event, many\n * `thread.message.delta` events, and finally a `thread.message.completed` event.\n *\n * We may add additional events over time, so we recommend handling unknown events\n * gracefully in your code. See the\n * [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview)\n * to learn how to integrate the Assistants API with streaming.\n */\nexport type AssistantStreamEvent =\n | AssistantStreamEvent.ThreadCreated\n | AssistantStreamEvent.ThreadRunCreated\n | AssistantStreamEvent.ThreadRunQueued\n | AssistantStreamEvent.ThreadRunInProgress\n | AssistantStreamEvent.ThreadRunRequiresAction\n | AssistantStreamEvent.ThreadRunCompleted\n | AssistantStreamEvent.ThreadRunIncomplete\n | AssistantStreamEvent.ThreadRunFailed\n | AssistantStreamEvent.ThreadRunCancelling\n | AssistantStreamEvent.ThreadRunCancelled\n | AssistantStreamEvent.ThreadRunExpired\n | AssistantStreamEvent.ThreadRunStepCreated\n | AssistantStreamEvent.ThreadRunStepInProgress\n | AssistantStreamEvent.ThreadRunStepDelta\n | AssistantStreamEvent.ThreadRunStepCompleted\n | AssistantStreamEvent.ThreadRunStepFailed\n | AssistantStreamEvent.ThreadRunStepCancelled\n | AssistantStreamEvent.ThreadRunStepExpired\n | AssistantStreamEvent.ThreadMessageCreated\n | AssistantStreamEvent.ThreadMessageInProgress\n | AssistantStreamEvent.ThreadMessageDelta\n | AssistantStreamEvent.ThreadMessageCompleted\n | AssistantStreamEvent.ThreadMessageIncomplete\n | AssistantStreamEvent.ErrorEvent;\n\nexport namespace AssistantStreamEvent {\n /**\n * Occurs when a new\n * [thread](https://platform.openai.com/docs/api-reference/threads/object) is\n * created.\n */\n export interface ThreadCreated {\n /**\n * Represents a thread that contains\n * [messages](https://platform.openai.com/docs/api-reference/messages).\n */\n data: ThreadsAPI.Thread;\n\n event: 'thread.created';\n\n /**\n * Whether to enable input audio transcription.\n */\n enabled?: boolean;\n }\n\n /**\n * Occurs when a new\n * [run](https://platform.openai.com/docs/api-reference/runs/object) is created.\n */\n export interface ThreadRunCreated {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.created';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to a `queued` status.\n */\n export interface ThreadRunQueued {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.queued';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to an `in_progress` status.\n */\n export interface ThreadRunInProgress {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.in_progress';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to a `requires_action` status.\n */\n export interface ThreadRunRequiresAction {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.requires_action';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * is completed.\n */\n export interface ThreadRunCompleted {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.completed';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * ends with status `incomplete`.\n */\n export interface ThreadRunIncomplete {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.incomplete';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * fails.\n */\n export interface ThreadRunFailed {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.failed';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to a `cancelling` status.\n */\n export interface ThreadRunCancelling {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.cancelling';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * is cancelled.\n */\n export interface ThreadRunCancelled {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.cancelled';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * expires.\n */\n export interface ThreadRunExpired {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.expired';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is created.\n */\n export interface ThreadRunStepCreated {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.created';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * moves to an `in_progress` state.\n */\n export interface ThreadRunStepInProgress {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.in_progress';\n }\n\n /**\n * Occurs when parts of a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * are being streamed.\n */\n export interface ThreadRunStepDelta {\n /**\n * Represents a run step delta i.e. any changed fields on a run step during\n * streaming.\n */\n data: StepsAPI.RunStepDeltaEvent;\n\n event: 'thread.run.step.delta';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is completed.\n */\n export interface ThreadRunStepCompleted {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.completed';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * fails.\n */\n export interface ThreadRunStepFailed {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.failed';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is cancelled.\n */\n export interface ThreadRunStepCancelled {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.cancelled';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * expires.\n */\n export interface ThreadRunStepExpired {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.expired';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) is\n * created.\n */\n export interface ThreadMessageCreated {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.created';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) moves\n * to an `in_progress` state.\n */\n export interface ThreadMessageInProgress {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.in_progress';\n }\n\n /**\n * Occurs when parts of a\n * [Message](https://platform.openai.com/docs/api-reference/messages/object) are\n * being streamed.\n */\n export interface ThreadMessageDelta {\n /**\n * Represents a message delta i.e. any changed fields on a message during\n * streaming.\n */\n data: MessagesAPI.MessageDeltaEvent;\n\n event: 'thread.message.delta';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) is\n * completed.\n */\n export interface ThreadMessageCompleted {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.completed';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) ends\n * before it is completed.\n */\n export interface ThreadMessageIncomplete {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.incomplete';\n }\n\n /**\n * Occurs when an\n * [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs.\n * This can happen due to an internal server error or a timeout.\n */\n export interface ErrorEvent {\n data: Shared.ErrorObject;\n\n event: 'error';\n }\n}\n\nexport type AssistantTool = CodeInterpreterTool | FileSearchTool | FunctionTool;\n\nexport interface CodeInterpreterTool {\n /**\n * The type of tool being defined: `code_interpreter`\n */\n type: 'code_interpreter';\n}\n\nexport interface FileSearchTool {\n /**\n * The type of tool being defined: `file_search`\n */\n type: 'file_search';\n\n /**\n * Overrides for the file search tool.\n */\n file_search?: FileSearchTool.FileSearch;\n}\n\nexport namespace FileSearchTool {\n /**\n * Overrides for the file search tool.\n */\n export interface FileSearch {\n /**\n * The maximum number of results the file search tool should output. The default is\n * 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between\n * 1 and 50 inclusive.\n *\n * Note that the file search tool may output fewer than `max_num_results` results.\n * See the\n * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)\n * for more information.\n */\n max_num_results?: number;\n\n /**\n * The ranking options for the file search. If not specified, the file search tool\n * will use the `auto` ranker and a score_threshold of 0.\n *\n * See the\n * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)\n * for more information.\n */\n ranking_options?: FileSearch.RankingOptions;\n }\n\n export namespace FileSearch {\n /**\n * The ranking options for the file search. If not specified, the file search tool\n * will use the `auto` ranker and a score_threshold of 0.\n *\n * See the\n * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)\n * for more information.\n */\n export interface RankingOptions {\n /**\n * The score threshold for the file search. All values must be a floating point\n * number between 0 and 1.\n */\n score_threshold: number;\n\n /**\n * The ranker to use for the file search. If not specified will use the `auto`\n * ranker.\n */\n ranker?: 'auto' | 'default_2024_08_21';\n }\n }\n}\n\nexport interface FunctionTool {\n function: Shared.FunctionDefinition;\n\n /**\n * The type of tool being defined: `function`\n */\n type: 'function';\n}\n\n/**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) is\n * created.\n */\nexport type MessageStreamEvent =\n | MessageStreamEvent.ThreadMessageCreated\n | MessageStreamEvent.ThreadMessageInProgress\n | MessageStreamEvent.ThreadMessageDelta\n | MessageStreamEvent.ThreadMessageCompleted\n | MessageStreamEvent.ThreadMessageIncomplete;\n\nexport namespace MessageStreamEvent {\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) is\n * created.\n */\n export interface ThreadMessageCreated {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.created';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) moves\n * to an `in_progress` state.\n */\n export interface ThreadMessageInProgress {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.in_progress';\n }\n\n /**\n * Occurs when parts of a\n * [Message](https://platform.openai.com/docs/api-reference/messages/object) are\n * being streamed.\n */\n export interface ThreadMessageDelta {\n /**\n * Represents a message delta i.e. any changed fields on a message during\n * streaming.\n */\n data: MessagesAPI.MessageDeltaEvent;\n\n event: 'thread.message.delta';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) is\n * completed.\n */\n export interface ThreadMessageCompleted {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.completed';\n }\n\n /**\n * Occurs when a\n * [message](https://platform.openai.com/docs/api-reference/messages/object) ends\n * before it is completed.\n */\n export interface ThreadMessageIncomplete {\n /**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: MessagesAPI.Message;\n\n event: 'thread.message.incomplete';\n }\n}\n\n/**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is created.\n */\nexport type RunStepStreamEvent =\n | RunStepStreamEvent.ThreadRunStepCreated\n | RunStepStreamEvent.ThreadRunStepInProgress\n | RunStepStreamEvent.ThreadRunStepDelta\n | RunStepStreamEvent.ThreadRunStepCompleted\n | RunStepStreamEvent.ThreadRunStepFailed\n | RunStepStreamEvent.ThreadRunStepCancelled\n | RunStepStreamEvent.ThreadRunStepExpired;\n\nexport namespace RunStepStreamEvent {\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is created.\n */\n export interface ThreadRunStepCreated {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.created';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * moves to an `in_progress` state.\n */\n export interface ThreadRunStepInProgress {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.in_progress';\n }\n\n /**\n * Occurs when parts of a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * are being streamed.\n */\n export interface ThreadRunStepDelta {\n /**\n * Represents a run step delta i.e. any changed fields on a run step during\n * streaming.\n */\n data: StepsAPI.RunStepDeltaEvent;\n\n event: 'thread.run.step.delta';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is completed.\n */\n export interface ThreadRunStepCompleted {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.completed';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * fails.\n */\n export interface ThreadRunStepFailed {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.failed';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * is cancelled.\n */\n export interface ThreadRunStepCancelled {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.cancelled';\n }\n\n /**\n * Occurs when a\n * [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object)\n * expires.\n */\n export interface ThreadRunStepExpired {\n /**\n * Represents a step in execution of a run.\n */\n data: StepsAPI.RunStep;\n\n event: 'thread.run.step.expired';\n }\n}\n\n/**\n * Occurs when a new\n * [run](https://platform.openai.com/docs/api-reference/runs/object) is created.\n */\nexport type RunStreamEvent =\n | RunStreamEvent.ThreadRunCreated\n | RunStreamEvent.ThreadRunQueued\n | RunStreamEvent.ThreadRunInProgress\n | RunStreamEvent.ThreadRunRequiresAction\n | RunStreamEvent.ThreadRunCompleted\n | RunStreamEvent.ThreadRunIncomplete\n | RunStreamEvent.ThreadRunFailed\n | RunStreamEvent.ThreadRunCancelling\n | RunStreamEvent.ThreadRunCancelled\n | RunStreamEvent.ThreadRunExpired;\n\nexport namespace RunStreamEvent {\n /**\n * Occurs when a new\n * [run](https://platform.openai.com/docs/api-reference/runs/object) is created.\n */\n export interface ThreadRunCreated {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.created';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to a `queued` status.\n */\n export interface ThreadRunQueued {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.queued';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to an `in_progress` status.\n */\n export interface ThreadRunInProgress {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.in_progress';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to a `requires_action` status.\n */\n export interface ThreadRunRequiresAction {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.requires_action';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * is completed.\n */\n export interface ThreadRunCompleted {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.completed';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * ends with status `incomplete`.\n */\n export interface ThreadRunIncomplete {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.incomplete';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * fails.\n */\n export interface ThreadRunFailed {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.failed';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * moves to a `cancelling` status.\n */\n export interface ThreadRunCancelling {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.cancelling';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * is cancelled.\n */\n export interface ThreadRunCancelled {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.cancelled';\n }\n\n /**\n * Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object)\n * expires.\n */\n export interface ThreadRunExpired {\n /**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\n data: RunsAPI.Run;\n\n event: 'thread.run.expired';\n }\n}\n\n/**\n * Occurs when a new\n * [thread](https://platform.openai.com/docs/api-reference/threads/object) is\n * created.\n */\nexport interface ThreadStreamEvent {\n /**\n * Represents a thread that contains\n * [messages](https://platform.openai.com/docs/api-reference/messages).\n */\n data: ThreadsAPI.Thread;\n\n event: 'thread.created';\n\n /**\n * Whether to enable input audio transcription.\n */\n enabled?: boolean;\n}\n\nexport interface AssistantCreateParams {\n /**\n * ID of the model to use. You can use the\n * [List models](https://platform.openai.com/docs/api-reference/models/list) API to\n * see all of your available models, or see our\n * [Model overview](https://platform.openai.com/docs/models) for descriptions of\n * them.\n */\n model: (string & {}) | Shared.ChatModel;\n\n /**\n * The description of the assistant. The maximum length is 512 characters.\n */\n description?: string | null;\n\n /**\n * The system instructions that the assistant uses. The maximum length is 256,000\n * characters.\n */\n instructions?: string | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The name of the assistant. The maximum length is 256 characters.\n */\n name?: string | null;\n\n /**\n * **o-series models only**\n *\n * Constrains effort on reasoning for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently\n * supported values are `low`, `medium`, and `high`. Reducing reasoning effort can\n * result in faster responses and fewer tokens used on reasoning in a response.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n tool_resources?: AssistantCreateParams.ToolResources | null;\n\n /**\n * A list of tool enabled on the assistant. There can be a maximum of 128 tools per\n * assistant. Tools can be of types `code_interpreter`, `file_search`, or\n * `function`.\n */\n tools?: Array<AssistantTool>;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n}\n\nexport namespace AssistantCreateParams {\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n\n /**\n * A helper to create a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * with file_ids and attach it to this assistant. There can be a maximum of 1\n * vector store attached to the assistant.\n */\n vector_stores?: Array<FileSearch.VectorStore>;\n }\n\n export namespace FileSearch {\n export interface VectorStore {\n /**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy.\n */\n chunking_strategy?: VectorStore.Auto | VectorStore.Static;\n\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to\n * add to the vector store. There can be a maximum of 10000 files in a vector\n * store.\n */\n file_ids?: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n export namespace VectorStore {\n /**\n * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of\n * `800` and `chunk_overlap_tokens` of `400`.\n */\n export interface Auto {\n /**\n * Always `auto`.\n */\n type: 'auto';\n }\n\n export interface Static {\n static: Static.Static;\n\n /**\n * Always `static`.\n */\n type: 'static';\n }\n\n export namespace Static {\n export interface Static {\n /**\n * The number of tokens that overlap between chunks. The default value is `400`.\n *\n * Note that the overlap must not exceed half of `max_chunk_size_tokens`.\n */\n chunk_overlap_tokens: number;\n\n /**\n * The maximum number of tokens in each chunk. The default value is `800`. The\n * minimum value is `100` and the maximum value is `4096`.\n */\n max_chunk_size_tokens: number;\n }\n }\n }\n }\n }\n}\n\nexport interface AssistantUpdateParams {\n /**\n * The description of the assistant. The maximum length is 512 characters.\n */\n description?: string | null;\n\n /**\n * The system instructions that the assistant uses. The maximum length is 256,000\n * characters.\n */\n instructions?: string | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * ID of the model to use. You can use the\n * [List models](https://platform.openai.com/docs/api-reference/models/list) API to\n * see all of your available models, or see our\n * [Model overview](https://platform.openai.com/docs/models) for descriptions of\n * them.\n */\n model?:\n | (string & {})\n | 'gpt-4.1'\n | 'gpt-4.1-mini'\n | 'gpt-4.1-nano'\n | 'gpt-4.1-2025-04-14'\n | 'gpt-4.1-mini-2025-04-14'\n | 'gpt-4.1-nano-2025-04-14'\n | 'o3-mini'\n | 'o3-mini-2025-01-31'\n | 'o1'\n | 'o1-2024-12-17'\n | 'gpt-4o'\n | 'gpt-4o-2024-11-20'\n | 'gpt-4o-2024-08-06'\n | 'gpt-4o-2024-05-13'\n | 'gpt-4o-mini'\n | 'gpt-4o-mini-2024-07-18'\n | 'gpt-4.5-preview'\n | 'gpt-4.5-preview-2025-02-27'\n | 'gpt-4-turbo'\n | 'gpt-4-turbo-2024-04-09'\n | 'gpt-4-0125-preview'\n | 'gpt-4-turbo-preview'\n | 'gpt-4-1106-preview'\n | 'gpt-4-vision-preview'\n | 'gpt-4'\n | 'gpt-4-0314'\n | 'gpt-4-0613'\n | 'gpt-4-32k'\n | 'gpt-4-32k-0314'\n | 'gpt-4-32k-0613'\n | 'gpt-3.5-turbo'\n | 'gpt-3.5-turbo-16k'\n | 'gpt-3.5-turbo-0613'\n | 'gpt-3.5-turbo-1106'\n | 'gpt-3.5-turbo-0125'\n | 'gpt-3.5-turbo-16k-0613';\n\n /**\n * The name of the assistant. The maximum length is 256 characters.\n */\n name?: string | null;\n\n /**\n * **o-series models only**\n *\n * Constrains effort on reasoning for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently\n * supported values are `low`, `medium`, and `high`. Reducing reasoning effort can\n * result in faster responses and fewer tokens used on reasoning in a response.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n tool_resources?: AssistantUpdateParams.ToolResources | null;\n\n /**\n * A list of tool enabled on the assistant. There can be a maximum of 128 tools per\n * assistant. Tools can be of types `code_interpreter`, `file_search`, or\n * `function`.\n */\n tools?: Array<AssistantTool>;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n}\n\nexport namespace AssistantUpdateParams {\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * Overrides the list of\n * [file](https://platform.openai.com/docs/api-reference/files) IDs made available\n * to the `code_interpreter` tool. There can be a maximum of 20 files associated\n * with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * Overrides the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n }\n }\n}\n\nexport interface AssistantListParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nAssistants.AssistantsPage = AssistantsPage;\n\nexport declare namespace Assistants {\n export {\n type Assistant as Assistant,\n type AssistantDeleted as AssistantDeleted,\n type AssistantStreamEvent as AssistantStreamEvent,\n type AssistantTool as AssistantTool,\n type CodeInterpreterTool as CodeInterpreterTool,\n type FileSearchTool as FileSearchTool,\n type FunctionTool as FunctionTool,\n type MessageStreamEvent as MessageStreamEvent,\n type RunStepStreamEvent as RunStepStreamEvent,\n type RunStreamEvent as RunStreamEvent,\n type ThreadStreamEvent as ThreadStreamEvent,\n AssistantsPage as AssistantsPage,\n type AssistantCreateParams as AssistantCreateParams,\n type AssistantUpdateParams as AssistantUpdateParams,\n type AssistantListParams as AssistantListParams,\n };\n\n export { AssistantStream };\n}\n","import { type ChatCompletionRunner } from './ChatCompletionRunner';\nimport { type ChatCompletionStreamingRunner } from './ChatCompletionStreamingRunner';\nimport { JSONSchema } from './jsonschema';\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type RunnableFunctionWithParse<Args extends object> = {\n /**\n * @param args the return value from `parse`.\n * @param runner the runner evaluating this callback.\n * @returns a string to send back to OpenAI.\n */\n function: (\n args: Args,\n runner: ChatCompletionRunner<unknown> | ChatCompletionStreamingRunner<unknown>,\n ) => PromiseOrValue<unknown>;\n /**\n * @param input the raw args from the OpenAI function call.\n * @returns the parsed arguments to pass to `function`\n */\n parse: (input: string) => PromiseOrValue<Args>;\n /**\n * The parameters the function accepts, describes as a JSON Schema object.\n */\n parameters: JSONSchema;\n /**\n * A description of what the function does, used by the model to choose when and how to call the function.\n */\n description: string;\n /**\n * The name of the function to be called. Will default to function.name if omitted.\n */\n name?: string | undefined;\n strict?: boolean | undefined;\n};\n\nexport type RunnableFunctionWithoutParse = {\n /**\n * @param args the raw args from the OpenAI function call.\n * @returns a string to send back to OpenAI\n */\n function: (\n args: string,\n runner: ChatCompletionRunner<unknown> | ChatCompletionStreamingRunner<unknown>,\n ) => PromiseOrValue<unknown>;\n /**\n * The parameters the function accepts, describes as a JSON Schema object.\n */\n parameters: JSONSchema;\n /**\n * A description of what the function does, used by the model to choose when and how to call the function.\n */\n description: string;\n /**\n * The name of the function to be called. Will default to function.name if omitted.\n */\n name?: string | undefined;\n strict?: boolean | undefined;\n};\n\nexport type RunnableFunction<Args extends object | string> =\n Args extends string ? RunnableFunctionWithoutParse\n : Args extends object ? RunnableFunctionWithParse<Args>\n : never;\n\nexport type RunnableToolFunction<Args extends object | string> =\n Args extends string ? RunnableToolFunctionWithoutParse\n : Args extends object ? RunnableToolFunctionWithParse<Args>\n : never;\n\nexport type RunnableToolFunctionWithoutParse = {\n type: 'function';\n function: RunnableFunctionWithoutParse;\n};\nexport type RunnableToolFunctionWithParse<Args extends object> = {\n type: 'function';\n function: RunnableFunctionWithParse<Args>;\n};\n\nexport function isRunnableFunctionWithParse<Args extends object>(\n fn: any,\n): fn is RunnableFunctionWithParse<Args> {\n return typeof (fn as any).parse === 'function';\n}\n\nexport type BaseFunctionsArgs = readonly (object | string)[];\n\nexport type RunnableFunctions<FunctionsArgs extends BaseFunctionsArgs> =\n [any[]] extends [FunctionsArgs] ? readonly RunnableFunction<any>[]\n : {\n [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction<FunctionsArgs[Index]>\n : FunctionsArgs[Index];\n };\n\nexport type RunnableTools<FunctionsArgs extends BaseFunctionsArgs> =\n [any[]] extends [FunctionsArgs] ? readonly RunnableToolFunction<any>[]\n : {\n [Index in keyof FunctionsArgs]: Index extends number ? RunnableToolFunction<FunctionsArgs[Index]>\n : FunctionsArgs[Index];\n };\n\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n *\n * @deprecated - please use ParsingToolFunction instead.\n */\nexport class ParsingFunction<Args extends object> {\n function: RunnableFunctionWithParse<Args>['function'];\n parse: RunnableFunctionWithParse<Args>['parse'];\n parameters: RunnableFunctionWithParse<Args>['parameters'];\n description: RunnableFunctionWithParse<Args>['description'];\n name?: RunnableFunctionWithParse<Args>['name'];\n\n constructor(input: RunnableFunctionWithParse<Args>) {\n this.function = input.function;\n this.parse = input.parse;\n this.parameters = input.parameters;\n this.description = input.description;\n this.name = input.name;\n }\n}\n\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n */\nexport class ParsingToolFunction<Args extends object> {\n type: 'function';\n function: RunnableFunctionWithParse<Args>;\n\n constructor(input: RunnableFunctionWithParse<Args>) {\n this.type = 'function';\n this.function = input;\n }\n}\n","import {\n type ChatCompletionAssistantMessageParam,\n type ChatCompletionFunctionMessageParam,\n type ChatCompletionMessageParam,\n type ChatCompletionToolMessageParam,\n} from '../resources';\n\nexport const isAssistantMessage = (\n message: ChatCompletionMessageParam | null | undefined,\n): message is ChatCompletionAssistantMessageParam => {\n return message?.role === 'assistant';\n};\n\nexport const isFunctionMessage = (\n message: ChatCompletionMessageParam | null | undefined,\n): message is ChatCompletionFunctionMessageParam => {\n return message?.role === 'function';\n};\n\nexport const isToolMessage = (\n message: ChatCompletionMessageParam | null | undefined,\n): message is ChatCompletionToolMessageParam => {\n return message?.role === 'tool';\n};\n\nexport function isPresent<T>(obj: T | null | undefined): obj is T {\n return obj != null;\n}\n","import {\n ChatCompletion,\n ChatCompletionCreateParams,\n ChatCompletionMessageToolCall,\n ChatCompletionTool,\n} from '../resources/chat/completions';\nimport {\n ChatCompletionStreamingToolRunnerParams,\n ChatCompletionStreamParams,\n ChatCompletionToolRunnerParams,\n ParsedChatCompletion,\n ParsedChoice,\n ParsedFunctionToolCall,\n} from '../resources/beta/chat/completions';\nimport { ResponseFormatJSONSchema } from '../resources/shared';\nimport { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from '../error';\nimport { type ResponseFormatTextJSONSchemaConfig } from '../resources/responses/responses';\n\ntype AnyChatCompletionCreateParams =\n | ChatCompletionCreateParams\n | ChatCompletionToolRunnerParams<any>\n | ChatCompletionStreamingToolRunnerParams<any>\n | ChatCompletionStreamParams;\n\nexport type ExtractParsedContentFromParams<Params extends AnyChatCompletionCreateParams> =\n Params['response_format'] extends AutoParseableResponseFormat<infer P> ? P : null;\n\nexport type AutoParseableResponseFormat<ParsedT> = ResponseFormatJSONSchema & {\n __output: ParsedT; // type-level only\n\n $brand: 'auto-parseable-response-format';\n $parseRaw(content: string): ParsedT;\n};\n\nexport function makeParseableResponseFormat<ParsedT>(\n response_format: ResponseFormatJSONSchema,\n parser: (content: string) => ParsedT,\n): AutoParseableResponseFormat<ParsedT> {\n const obj = { ...response_format };\n\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n\n return obj as AutoParseableResponseFormat<ParsedT>;\n}\n\nexport type AutoParseableTextFormat<ParsedT> = ResponseFormatTextJSONSchemaConfig & {\n __output: ParsedT; // type-level only\n\n $brand: 'auto-parseable-response-format';\n $parseRaw(content: string): ParsedT;\n};\n\nexport function makeParseableTextFormat<ParsedT>(\n response_format: ResponseFormatTextJSONSchemaConfig,\n parser: (content: string) => ParsedT,\n): AutoParseableTextFormat<ParsedT> {\n const obj = { ...response_format };\n\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n\n return obj as AutoParseableTextFormat<ParsedT>;\n}\n\nexport function isAutoParsableResponseFormat<ParsedT>(\n response_format: any,\n): response_format is AutoParseableResponseFormat<ParsedT> {\n return response_format?.['$brand'] === 'auto-parseable-response-format';\n}\n\ntype ToolOptions = {\n name: string;\n arguments: any;\n function?: ((args: any) => any) | undefined;\n};\n\nexport type AutoParseableTool<\n OptionsT extends ToolOptions,\n HasFunction = OptionsT['function'] extends Function ? true : false,\n> = ChatCompletionTool & {\n __arguments: OptionsT['arguments']; // type-level only\n __name: OptionsT['name']; // type-level only\n __hasFunction: HasFunction; // type-level only\n\n $brand: 'auto-parseable-tool';\n $callback: ((args: OptionsT['arguments']) => any) | undefined;\n $parseRaw(args: string): OptionsT['arguments'];\n};\n\nexport function makeParseableTool<OptionsT extends ToolOptions>(\n tool: ChatCompletionTool,\n {\n parser,\n callback,\n }: {\n parser: (content: string) => OptionsT['arguments'];\n callback: ((args: any) => any) | undefined;\n },\n): AutoParseableTool<OptionsT['arguments']> {\n const obj = { ...tool };\n\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n\n return obj as AutoParseableTool<OptionsT['arguments']>;\n}\n\nexport function isAutoParsableTool(tool: any): tool is AutoParseableTool<any> {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\n\nexport function maybeParseChatCompletion<\n Params extends ChatCompletionCreateParams | null,\n ParsedT = Params extends null ? null : ExtractParsedContentFromParams<NonNullable<Params>>,\n>(completion: ChatCompletion, params: Params): ParsedChatCompletion<ParsedT> {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...completion,\n choices: completion.choices.map((choice) => ({\n ...choice,\n message: {\n ...choice.message,\n parsed: null,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls,\n }\n : undefined),\n },\n })),\n };\n }\n\n return parseChatCompletion(completion, params);\n}\n\nexport function parseChatCompletion<\n Params extends ChatCompletionCreateParams,\n ParsedT = ExtractParsedContentFromParams<Params>,\n>(completion: ChatCompletion, params: Params): ParsedChatCompletion<ParsedT> {\n const choices: Array<ParsedChoice<ParsedT>> = completion.choices.map((choice): ParsedChoice<ParsedT> => {\n if (choice.finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n\n if (choice.finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n\n return {\n ...choice,\n message: {\n ...choice.message,\n ...(choice.message.tool_calls ?\n {\n tool_calls:\n choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined,\n }\n : undefined),\n parsed:\n choice.message.content && !choice.message.refusal ?\n parseResponseFormat(params, choice.message.content)\n : null,\n },\n };\n });\n\n return { ...completion, choices };\n}\n\nfunction parseResponseFormat<\n Params extends ChatCompletionCreateParams,\n ParsedT = ExtractParsedContentFromParams<Params>,\n>(params: Params, content: string): ParsedT | null {\n if (params.response_format?.type !== 'json_schema') {\n return null;\n }\n\n if (params.response_format?.type === 'json_schema') {\n if ('$parseRaw' in params.response_format) {\n const response_format = params.response_format as AutoParseableResponseFormat<ParsedT>;\n\n return response_format.$parseRaw(content);\n }\n\n return JSON.parse(content);\n }\n\n return null;\n}\n\nfunction parseToolCall<Params extends ChatCompletionCreateParams>(\n params: Params,\n toolCall: ChatCompletionMessageToolCall,\n): ParsedFunctionToolCall {\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return {\n ...toolCall,\n function: {\n ...toolCall.function,\n parsed_arguments:\n isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)\n : null,\n },\n };\n}\n\nexport function shouldParseToolCall(\n params: ChatCompletionCreateParams | null | undefined,\n toolCall: ChatCompletionMessageToolCall,\n): boolean {\n if (!params) {\n return false;\n }\n\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;\n}\n\nexport function hasAutoParseableInput(params: AnyChatCompletionCreateParams): boolean {\n if (isAutoParsableResponseFormat(params.response_format)) {\n return true;\n }\n\n return (\n params.tools?.some(\n (t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true),\n ) ?? false\n );\n}\n\nexport function validateInputTools(tools: ChatCompletionTool[] | undefined) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(\n `Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``,\n );\n }\n\n if (tool.function.strict !== true) {\n throw new OpenAIError(\n `The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`,\n );\n }\n }\n}\n","import * as Core from '../core';\nimport { type CompletionUsage } from '../resources/completions';\nimport {\n type ChatCompletion,\n type ChatCompletionMessage,\n type ChatCompletionMessageParam,\n type ChatCompletionCreateParams,\n type ChatCompletionTool,\n} from '../resources/chat/completions';\nimport { OpenAIError } from '../error';\nimport {\n type RunnableFunction,\n isRunnableFunctionWithParse,\n type BaseFunctionsArgs,\n RunnableToolFunction,\n} from './RunnableFunction';\nimport { ChatCompletionFunctionRunnerParams, ChatCompletionToolRunnerParams } from './ChatCompletionRunner';\nimport {\n ChatCompletionStreamingFunctionRunnerParams,\n ChatCompletionStreamingToolRunnerParams,\n} from './ChatCompletionStreamingRunner';\nimport { isAssistantMessage, isFunctionMessage, isToolMessage } from './chatCompletionUtils';\nimport { BaseEvents, EventStream } from './EventStream';\nimport { ParsedChatCompletion } from '../resources/beta/chat/completions';\nimport OpenAI from '../index';\nimport { isAutoParsableTool, parseChatCompletion } from '../lib/parser';\n\nconst DEFAULT_MAX_CHAT_COMPLETIONS = 10;\nexport interface RunnerOptions extends Core.RequestOptions {\n /** How many requests to make before canceling. Default 10. */\n maxChatCompletions?: number;\n}\n\nexport class AbstractChatCompletionRunner<\n EventTypes extends AbstractChatCompletionRunnerEvents,\n ParsedT,\n> extends EventStream<EventTypes> {\n protected _chatCompletions: ParsedChatCompletion<ParsedT>[] = [];\n messages: ChatCompletionMessageParam[] = [];\n\n protected _addChatCompletion(\n this: AbstractChatCompletionRunner<AbstractChatCompletionRunnerEvents, ParsedT>,\n chatCompletion: ParsedChatCompletion<ParsedT>,\n ): ParsedChatCompletion<ParsedT> {\n this._chatCompletions.push(chatCompletion);\n this._emit('chatCompletion', chatCompletion);\n const message = chatCompletion.choices[0]?.message;\n if (message) this._addMessage(message as ChatCompletionMessageParam);\n return chatCompletion;\n }\n\n protected _addMessage(\n this: AbstractChatCompletionRunner<AbstractChatCompletionRunnerEvents, ParsedT>,\n message: ChatCompletionMessageParam,\n emit = true,\n ) {\n if (!('content' in message)) message.content = null;\n\n this.messages.push(message);\n\n if (emit) {\n this._emit('message', message);\n if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) {\n // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function.\n this._emit('functionCallResult', message.content as string);\n } else if (isAssistantMessage(message) && message.function_call) {\n this._emit('functionCall', message.function_call);\n } else if (isAssistantMessage(message) && message.tool_calls) {\n for (const tool_call of message.tool_calls) {\n if (tool_call.type === 'function') {\n this._emit('functionCall', tool_call.function);\n }\n }\n }\n }\n }\n\n /**\n * @returns a promise that resolves with the final ChatCompletion, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletion.\n */\n async finalChatCompletion(): Promise<ParsedChatCompletion<ParsedT>> {\n await this.done();\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (!completion) throw new OpenAIError('stream ended without producing a ChatCompletion');\n return completion;\n }\n\n #getFinalContent(): string | null {\n return this.#getFinalMessage().content ?? null;\n }\n\n /**\n * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalContent(): Promise<string | null> {\n await this.done();\n return this.#getFinalContent();\n }\n\n #getFinalMessage(): ChatCompletionMessage {\n let i = this.messages.length;\n while (i-- > 0) {\n const message = this.messages[i];\n if (isAssistantMessage(message)) {\n const { function_call, ...rest } = message;\n\n // TODO: support audio here\n const ret: Omit<ChatCompletionMessage, 'audio'> = {\n ...rest,\n content: (message as ChatCompletionMessage).content ?? null,\n refusal: (message as ChatCompletionMessage).refusal ?? null,\n };\n if (function_call) {\n ret.function_call = function_call;\n }\n return ret;\n }\n }\n throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,\n * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalMessage(): Promise<ChatCompletionMessage> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalFunctionCall(): ChatCompletionMessage.FunctionCall | undefined {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isAssistantMessage(message) && message?.function_call) {\n return message.function_call;\n }\n if (isAssistantMessage(message) && message?.tool_calls?.length) {\n return message.tool_calls.at(-1)?.function;\n }\n }\n\n return;\n }\n\n /**\n * @returns a promise that resolves with the content of the final FunctionCall, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalFunctionCall(): Promise<ChatCompletionMessage.FunctionCall | undefined> {\n await this.done();\n return this.#getFinalFunctionCall();\n }\n\n #getFinalFunctionCallResult(): string | undefined {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isFunctionMessage(message) && message.content != null) {\n return message.content;\n }\n if (\n isToolMessage(message) &&\n message.content != null &&\n typeof message.content === 'string' &&\n this.messages.some(\n (x) =>\n x.role === 'assistant' &&\n x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id),\n )\n ) {\n return message.content;\n }\n }\n\n return;\n }\n\n async finalFunctionCallResult(): Promise<string | undefined> {\n await this.done();\n return this.#getFinalFunctionCallResult();\n }\n\n #calculateTotalUsage(): CompletionUsage {\n const total: CompletionUsage = {\n completion_tokens: 0,\n prompt_tokens: 0,\n total_tokens: 0,\n };\n for (const { usage } of this._chatCompletions) {\n if (usage) {\n total.completion_tokens += usage.completion_tokens;\n total.prompt_tokens += usage.prompt_tokens;\n total.total_tokens += usage.total_tokens;\n }\n }\n return total;\n }\n\n async totalUsage(): Promise<CompletionUsage> {\n await this.done();\n return this.#calculateTotalUsage();\n }\n\n allChatCompletions(): ChatCompletion[] {\n return [...this._chatCompletions];\n }\n\n protected override _emitFinal(\n this: AbstractChatCompletionRunner<AbstractChatCompletionRunnerEvents, ParsedT>,\n ) {\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (completion) this._emit('finalChatCompletion', completion);\n const finalMessage = this.#getFinalMessage();\n if (finalMessage) this._emit('finalMessage', finalMessage);\n const finalContent = this.#getFinalContent();\n if (finalContent) this._emit('finalContent', finalContent);\n\n const finalFunctionCall = this.#getFinalFunctionCall();\n if (finalFunctionCall) this._emit('finalFunctionCall', finalFunctionCall);\n\n const finalFunctionCallResult = this.#getFinalFunctionCallResult();\n if (finalFunctionCallResult != null) this._emit('finalFunctionCallResult', finalFunctionCallResult);\n\n if (this._chatCompletions.some((c) => c.usage)) {\n this._emit('totalUsage', this.#calculateTotalUsage());\n }\n }\n\n #validateParams(params: ChatCompletionCreateParams): void {\n if (params.n != null && params.n > 1) {\n throw new OpenAIError(\n 'ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.',\n );\n }\n }\n\n protected async _createChatCompletion(\n client: OpenAI,\n params: ChatCompletionCreateParams,\n options?: Core.RequestOptions,\n ): Promise<ParsedChatCompletion<ParsedT>> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#validateParams(params);\n\n const chatCompletion = await client.chat.completions.create(\n { ...params, stream: false },\n { ...options, signal: this.controller.signal },\n );\n this._connected();\n return this._addChatCompletion(parseChatCompletion(chatCompletion, params));\n }\n\n protected async _runChatCompletion(\n client: OpenAI,\n params: ChatCompletionCreateParams,\n options?: Core.RequestOptions,\n ): Promise<ChatCompletion> {\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n return await this._createChatCompletion(client, params, options);\n }\n\n protected async _runFunctions<FunctionsArgs extends BaseFunctionsArgs>(\n client: OpenAI,\n params:\n | ChatCompletionFunctionRunnerParams<FunctionsArgs>\n | ChatCompletionStreamingFunctionRunnerParams<FunctionsArgs>,\n options?: RunnerOptions,\n ) {\n const role = 'function' as const;\n const { function_call = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n\n const functionsByName: Record<string, RunnableFunction<any>> = {};\n for (const f of params.functions) {\n functionsByName[f.name || f.function.name] = f;\n }\n\n const functions: ChatCompletionCreateParams.Function[] = params.functions.map(\n (f): ChatCompletionCreateParams.Function => ({\n name: f.name || f.function.name,\n parameters: f.parameters as Record<string, unknown>,\n description: f.description,\n }),\n );\n\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion: ChatCompletion = await this._createChatCompletion(\n client,\n {\n ...restParams,\n function_call,\n functions,\n messages: [...this.messages],\n },\n options,\n );\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.function_call) return;\n const { name, arguments: args } = message.function_call;\n const fn = functionsByName[name];\n if (!fn) {\n const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions\n .map((f) => JSON.stringify(f.name))\n .join(', ')}. Please try again`;\n\n this._addMessage({ role, name, content });\n continue;\n } else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(\n singleFunctionToCall,\n )} requested. Please try again`;\n\n this._addMessage({ role, name, content });\n continue;\n }\n\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n } catch (error) {\n this._addMessage({\n role,\n name,\n content: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = this.#stringifyFunctionCallResult(rawContent);\n\n this._addMessage({ role, name, content });\n\n if (singleFunctionToCall) return;\n }\n }\n\n protected async _runTools<FunctionsArgs extends BaseFunctionsArgs>(\n client: OpenAI,\n params:\n | ChatCompletionToolRunnerParams<FunctionsArgs>\n | ChatCompletionStreamingToolRunnerParams<FunctionsArgs>,\n options?: RunnerOptions,\n ) {\n const role = 'tool' as const;\n const { tool_choice = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n\n // TODO(someday): clean this logic up\n const inputTools = params.tools.map((tool): RunnableToolFunction<any> => {\n if (isAutoParsableTool(tool)) {\n if (!tool.$callback) {\n throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function');\n }\n\n return {\n type: 'function',\n function: {\n function: tool.$callback,\n name: tool.function.name,\n description: tool.function.description || '',\n parameters: tool.function.parameters as any,\n parse: tool.$parseRaw,\n strict: true,\n },\n };\n }\n\n return tool as any as RunnableToolFunction<any>;\n });\n\n const functionsByName: Record<string, RunnableFunction<any>> = {};\n for (const f of inputTools) {\n if (f.type === 'function') {\n functionsByName[f.function.name || f.function.function.name] = f.function;\n }\n }\n\n const tools: ChatCompletionTool[] =\n 'tools' in params ?\n inputTools.map((t) =>\n t.type === 'function' ?\n {\n type: 'function',\n function: {\n name: t.function.name || t.function.function.name,\n parameters: t.function.parameters as Record<string, unknown>,\n description: t.function.description,\n strict: t.function.strict,\n },\n }\n : (t as unknown as ChatCompletionTool),\n )\n : (undefined as any);\n\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion: ChatCompletion = await this._createChatCompletion(\n client,\n {\n ...restParams,\n tool_choice,\n tools,\n messages: [...this.messages],\n },\n options,\n );\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.tool_calls?.length) {\n return;\n }\n\n for (const tool_call of message.tool_calls) {\n if (tool_call.type !== 'function') continue;\n const tool_call_id = tool_call.id;\n const { name, arguments: args } = tool_call.function;\n const fn = functionsByName[name];\n\n if (!fn) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(\n functionsByName,\n )\n .map((name) => JSON.stringify(name))\n .join(', ')}. Please try again`;\n\n this._addMessage({ role, tool_call_id, content });\n continue;\n } else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(\n singleFunctionToCall,\n )} requested. Please try again`;\n\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n } catch (error) {\n const content = error instanceof Error ? error.message : String(error);\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = this.#stringifyFunctionCallResult(rawContent);\n this._addMessage({ role, tool_call_id, content });\n\n if (singleFunctionToCall) {\n return;\n }\n }\n }\n\n return;\n }\n\n #stringifyFunctionCallResult(rawContent: unknown): string {\n return (\n typeof rawContent === 'string' ? rawContent\n : rawContent === undefined ? 'undefined'\n : JSON.stringify(rawContent)\n );\n }\n}\n\nexport interface AbstractChatCompletionRunnerEvents extends BaseEvents {\n functionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void;\n message: (message: ChatCompletionMessageParam) => void;\n chatCompletion: (completion: ChatCompletion) => void;\n finalContent: (contentSnapshot: string) => void;\n finalMessage: (message: ChatCompletionMessageParam) => void;\n finalChatCompletion: (completion: ChatCompletion) => void;\n finalFunctionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void;\n functionCallResult: (content: string) => void;\n finalFunctionCallResult: (content: string) => void;\n totalUsage: (usage: CompletionUsage) => void;\n}\n","import {\n type ChatCompletionMessageParam,\n type ChatCompletionCreateParamsNonStreaming,\n} from '../resources/chat/completions';\nimport { type RunnableFunctions, type BaseFunctionsArgs, RunnableTools } from './RunnableFunction';\nimport {\n AbstractChatCompletionRunner,\n AbstractChatCompletionRunnerEvents,\n RunnerOptions,\n} from './AbstractChatCompletionRunner';\nimport { isAssistantMessage } from './chatCompletionUtils';\nimport OpenAI from '../index';\nimport { AutoParseableTool } from '../lib/parser';\n\nexport interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents {\n content: (content: string) => void;\n}\n\nexport type ChatCompletionFunctionRunnerParams<FunctionsArgs extends BaseFunctionsArgs> = Omit<\n ChatCompletionCreateParamsNonStreaming,\n 'functions'\n> & {\n functions: RunnableFunctions<FunctionsArgs>;\n};\n\nexport type ChatCompletionToolRunnerParams<FunctionsArgs extends BaseFunctionsArgs> = Omit<\n ChatCompletionCreateParamsNonStreaming,\n 'tools'\n> & {\n tools: RunnableTools<FunctionsArgs> | AutoParseableTool<any, true>[];\n};\n\nexport class ChatCompletionRunner<ParsedT = null> extends AbstractChatCompletionRunner<\n ChatCompletionRunnerEvents,\n ParsedT\n> {\n /** @deprecated - please use `runTools` instead. */\n static runFunctions(\n client: OpenAI,\n params: ChatCompletionFunctionRunnerParams<any[]>,\n options?: RunnerOptions,\n ): ChatCompletionRunner<null> {\n const runner = new ChatCompletionRunner();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' },\n };\n runner._run(() => runner._runFunctions(client, params, opts));\n return runner;\n }\n\n static runTools<ParsedT>(\n client: OpenAI,\n params: ChatCompletionToolRunnerParams<any[]>,\n options?: RunnerOptions,\n ): ChatCompletionRunner<ParsedT> {\n const runner = new ChatCompletionRunner<ParsedT>();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n\n override _addMessage(\n this: ChatCompletionRunner<ParsedT>,\n message: ChatCompletionMessageParam,\n emit: boolean = true,\n ) {\n super._addMessage(message, emit);\n if (isAssistantMessage(message) && message.content) {\n this._emit('content', message.content as string);\n }\n }\n}\n","const STR = 0b000000001;\nconst NUM = 0b000000010;\nconst ARR = 0b000000100;\nconst OBJ = 0b000001000;\nconst NULL = 0b000010000;\nconst BOOL = 0b000100000;\nconst NAN = 0b001000000;\nconst INFINITY = 0b010000000;\nconst MINUS_INFINITY = 0b100000000;\n\nconst INF = INFINITY | MINUS_INFINITY;\nconst SPECIAL = NULL | BOOL | INF | NAN;\nconst ATOM = STR | NUM | SPECIAL;\nconst COLLECTION = ARR | OBJ;\nconst ALL = ATOM | COLLECTION;\n\nconst Allow = {\n STR,\n NUM,\n ARR,\n OBJ,\n NULL,\n BOOL,\n NAN,\n INFINITY,\n MINUS_INFINITY,\n INF,\n SPECIAL,\n ATOM,\n COLLECTION,\n ALL,\n};\n\n// The JSON string segment was unable to be parsed completely\nclass PartialJSON extends Error {}\n\nclass MalformedJSON extends Error {}\n\n/**\n * Parse incomplete JSON\n * @param {string} jsonString Partial JSON to be parsed\n * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details\n * @returns The parsed JSON\n * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)\n * @throws {MalformedJSON} If the JSON is malformed\n */\nfunction parseJSON(jsonString: string, allowPartial: number = Allow.ALL): any {\n if (typeof jsonString !== 'string') {\n throw new TypeError(`expecting str, got ${typeof jsonString}`);\n }\n if (!jsonString.trim()) {\n throw new Error(`${jsonString} is empty`);\n }\n return _parseJSON(jsonString.trim(), allowPartial);\n}\n\nconst _parseJSON = (jsonString: string, allow: number) => {\n const length = jsonString.length;\n let index = 0;\n\n const markPartialJSON = (msg: string) => {\n throw new PartialJSON(`${msg} at position ${index}`);\n };\n\n const throwMalformedError = (msg: string) => {\n throw new MalformedJSON(`${msg} at position ${index}`);\n };\n\n const parseAny: () => any = () => {\n skipBlank();\n if (index >= length) markPartialJSON('Unexpected end of input');\n if (jsonString[index] === '\"') return parseStr();\n if (jsonString[index] === '{') return parseObj();\n if (jsonString[index] === '[') return parseArr();\n if (\n jsonString.substring(index, index + 4) === 'null' ||\n (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))\n ) {\n index += 4;\n return null;\n }\n if (\n jsonString.substring(index, index + 4) === 'true' ||\n (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))\n ) {\n index += 4;\n return true;\n }\n if (\n jsonString.substring(index, index + 5) === 'false' ||\n (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))\n ) {\n index += 5;\n return false;\n }\n if (\n jsonString.substring(index, index + 8) === 'Infinity' ||\n (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))\n ) {\n index += 8;\n return Infinity;\n }\n if (\n jsonString.substring(index, index + 9) === '-Infinity' ||\n (Allow.MINUS_INFINITY & allow &&\n 1 < length - index &&\n length - index < 9 &&\n '-Infinity'.startsWith(jsonString.substring(index)))\n ) {\n index += 9;\n return -Infinity;\n }\n if (\n jsonString.substring(index, index + 3) === 'NaN' ||\n (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))\n ) {\n index += 3;\n return NaN;\n }\n return parseNum();\n };\n\n const parseStr: () => string = () => {\n const start = index;\n let escape = false;\n index++; // skip initial quote\n while (index < length && (jsonString[index] !== '\"' || (escape && jsonString[index - 1] === '\\\\'))) {\n escape = jsonString[index] === '\\\\' ? !escape : false;\n index++;\n }\n if (jsonString.charAt(index) == '\"') {\n try {\n return JSON.parse(jsonString.substring(start, ++index - Number(escape)));\n } catch (e) {\n throwMalformedError(String(e));\n }\n } else if (Allow.STR & allow) {\n try {\n return JSON.parse(jsonString.substring(start, index - Number(escape)) + '\"');\n } catch (e) {\n // SyntaxError: Invalid escape sequence\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\\\')) + '\"');\n }\n }\n markPartialJSON('Unterminated string literal');\n };\n\n const parseObj = () => {\n index++; // skip initial brace\n skipBlank();\n const obj: Record<string, any> = {};\n try {\n while (jsonString[index] !== '}') {\n skipBlank();\n if (index >= length && Allow.OBJ & allow) return obj;\n const key = parseStr();\n skipBlank();\n index++; // skip colon\n try {\n const value = parseAny();\n Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });\n } catch (e) {\n if (Allow.OBJ & allow) return obj;\n else throw e;\n }\n skipBlank();\n if (jsonString[index] === ',') index++; // skip comma\n }\n } catch (e) {\n if (Allow.OBJ & allow) return obj;\n else markPartialJSON(\"Expected '}' at end of object\");\n }\n index++; // skip final brace\n return obj;\n };\n\n const parseArr = () => {\n index++; // skip initial bracket\n const arr = [];\n try {\n while (jsonString[index] !== ']') {\n arr.push(parseAny());\n skipBlank();\n if (jsonString[index] === ',') {\n index++; // skip comma\n }\n }\n } catch (e) {\n if (Allow.ARR & allow) {\n return arr;\n }\n markPartialJSON(\"Expected ']' at end of array\");\n }\n index++; // skip final bracket\n return arr;\n };\n\n const parseNum = () => {\n if (index === 0) {\n if (jsonString === '-' && Allow.NUM & allow) markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString);\n } catch (e) {\n if (Allow.NUM & allow) {\n try {\n if ('.' === jsonString[jsonString.length - 1])\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.')));\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e')));\n } catch (e) {}\n }\n throwMalformedError(String(e));\n }\n }\n\n const start = index;\n\n if (jsonString[index] === '-') index++;\n while (jsonString[index] && !',]}'.includes(jsonString[index]!)) index++;\n\n if (index == length && !(Allow.NUM & allow)) markPartialJSON('Unterminated number literal');\n\n try {\n return JSON.parse(jsonString.substring(start, index));\n } catch (e) {\n if (jsonString.substring(start, index) === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e')));\n } catch (e) {\n throwMalformedError(String(e));\n }\n }\n };\n\n const skipBlank = () => {\n while (index < length && ' \\n\\r\\t'.includes(jsonString[index]!)) {\n index++;\n }\n };\n\n return parseAny();\n};\n\n// using this function with malformed JSON is undefined behavior\nconst partialParse = (input: string) => parseJSON(input, Allow.ALL ^ Allow.NUM);\n\nexport { partialParse, PartialJSON, MalformedJSON };\n","import * as Core from '../core';\nimport {\n OpenAIError,\n APIUserAbortError,\n LengthFinishReasonError,\n ContentFilterFinishReasonError,\n} from '../error';\nimport {\n ChatCompletionTokenLogprob,\n type ChatCompletion,\n type ChatCompletionChunk,\n type ChatCompletionCreateParams,\n type ChatCompletionCreateParamsStreaming,\n type ChatCompletionCreateParamsBase,\n type ChatCompletionRole,\n} from '../resources/chat/completions/completions';\nimport {\n AbstractChatCompletionRunner,\n type AbstractChatCompletionRunnerEvents,\n} from './AbstractChatCompletionRunner';\nimport { type ReadableStream } from '../_shims/index';\nimport { Stream } from '../streaming';\nimport OpenAI from '../index';\nimport { ParsedChatCompletion } from '../resources/beta/chat/completions';\nimport {\n AutoParseableResponseFormat,\n hasAutoParseableInput,\n isAutoParsableResponseFormat,\n isAutoParsableTool,\n maybeParseChatCompletion,\n shouldParseToolCall,\n} from '../lib/parser';\nimport { partialParse } from '../_vendor/partial-json-parser/parser';\n\nexport interface ContentDeltaEvent {\n delta: string;\n snapshot: string;\n parsed: unknown | null;\n}\n\nexport interface ContentDoneEvent<ParsedT = null> {\n content: string;\n parsed: ParsedT | null;\n}\n\nexport interface RefusalDeltaEvent {\n delta: string;\n snapshot: string;\n}\n\nexport interface RefusalDoneEvent {\n refusal: string;\n}\n\nexport interface FunctionToolCallArgumentsDeltaEvent {\n name: string;\n\n index: number;\n\n arguments: string;\n\n parsed_arguments: unknown;\n\n arguments_delta: string;\n}\n\nexport interface FunctionToolCallArgumentsDoneEvent {\n name: string;\n\n index: number;\n\n arguments: string;\n\n parsed_arguments: unknown;\n}\n\nexport interface LogProbsContentDeltaEvent {\n content: Array<ChatCompletionTokenLogprob>;\n snapshot: Array<ChatCompletionTokenLogprob>;\n}\n\nexport interface LogProbsContentDoneEvent {\n content: Array<ChatCompletionTokenLogprob>;\n}\n\nexport interface LogProbsRefusalDeltaEvent {\n refusal: Array<ChatCompletionTokenLogprob>;\n snapshot: Array<ChatCompletionTokenLogprob>;\n}\n\nexport interface LogProbsRefusalDoneEvent {\n refusal: Array<ChatCompletionTokenLogprob>;\n}\n\nexport interface ChatCompletionStreamEvents<ParsedT = null> extends AbstractChatCompletionRunnerEvents {\n content: (contentDelta: string, contentSnapshot: string) => void;\n chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void;\n\n 'content.delta': (props: ContentDeltaEvent) => void;\n 'content.done': (props: ContentDoneEvent<ParsedT>) => void;\n\n 'refusal.delta': (props: RefusalDeltaEvent) => void;\n 'refusal.done': (props: RefusalDoneEvent) => void;\n\n 'tool_calls.function.arguments.delta': (props: FunctionToolCallArgumentsDeltaEvent) => void;\n 'tool_calls.function.arguments.done': (props: FunctionToolCallArgumentsDoneEvent) => void;\n\n 'logprobs.content.delta': (props: LogProbsContentDeltaEvent) => void;\n 'logprobs.content.done': (props: LogProbsContentDoneEvent) => void;\n\n 'logprobs.refusal.delta': (props: LogProbsRefusalDeltaEvent) => void;\n 'logprobs.refusal.done': (props: LogProbsRefusalDoneEvent) => void;\n}\n\nexport type ChatCompletionStreamParams = Omit<ChatCompletionCreateParamsBase, 'stream'> & {\n stream?: true;\n};\n\ninterface ChoiceEventState {\n content_done: boolean;\n refusal_done: boolean;\n logprobs_content_done: boolean;\n logprobs_refusal_done: boolean;\n current_tool_call_index: number | null;\n done_tool_calls: Set<number>;\n}\n\nexport class ChatCompletionStream<ParsedT = null>\n extends AbstractChatCompletionRunner<ChatCompletionStreamEvents<ParsedT>, ParsedT>\n implements AsyncIterable<ChatCompletionChunk>\n{\n #params: ChatCompletionCreateParams | null;\n #choiceEventStates: ChoiceEventState[];\n #currentChatCompletionSnapshot: ChatCompletionSnapshot | undefined;\n\n constructor(params: ChatCompletionCreateParams | null) {\n super();\n this.#params = params;\n this.#choiceEventStates = [];\n }\n\n get currentChatCompletionSnapshot(): ChatCompletionSnapshot | undefined {\n return this.#currentChatCompletionSnapshot;\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): ChatCompletionStream<null> {\n const runner = new ChatCompletionStream(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createChatCompletion<ParsedT>(\n client: OpenAI,\n params: ChatCompletionStreamParams,\n options?: Core.RequestOptions,\n ): ChatCompletionStream<ParsedT> {\n const runner = new ChatCompletionStream<ParsedT>(params as ChatCompletionCreateParamsStreaming);\n runner._run(() =>\n runner._runChatCompletion(\n client,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } },\n ),\n );\n return runner;\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentChatCompletionSnapshot = undefined;\n }\n\n #getChoiceEventState(choice: ChatCompletionSnapshot.Choice): ChoiceEventState {\n let state = this.#choiceEventStates[choice.index];\n if (state) {\n return state;\n }\n\n state = {\n content_done: false,\n refusal_done: false,\n logprobs_content_done: false,\n logprobs_refusal_done: false,\n done_tool_calls: new Set(),\n current_tool_call_index: null,\n };\n this.#choiceEventStates[choice.index] = state;\n return state;\n }\n\n #addChunk(this: ChatCompletionStream<ParsedT>, chunk: ChatCompletionChunk) {\n if (this.ended) return;\n\n const completion = this.#accumulateChatCompletion(chunk);\n this._emit('chunk', chunk, completion);\n\n for (const choice of chunk.choices) {\n const choiceSnapshot = completion.choices[choice.index]!;\n\n if (\n choice.delta.content != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.content\n ) {\n this._emit('content', choice.delta.content, choiceSnapshot.message.content);\n this._emit('content.delta', {\n delta: choice.delta.content,\n snapshot: choiceSnapshot.message.content,\n parsed: choiceSnapshot.message.parsed,\n });\n }\n\n if (\n choice.delta.refusal != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.refusal\n ) {\n this._emit('refusal.delta', {\n delta: choice.delta.refusal,\n snapshot: choiceSnapshot.message.refusal,\n });\n }\n\n if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.content.delta', {\n content: choice.logprobs?.content,\n snapshot: choiceSnapshot.logprobs?.content ?? [],\n });\n }\n\n if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.refusal.delta', {\n refusal: choice.logprobs?.refusal,\n snapshot: choiceSnapshot.logprobs?.refusal ?? [],\n });\n }\n\n const state = this.#getChoiceEventState(choiceSnapshot);\n\n if (choiceSnapshot.finish_reason) {\n this.#emitContentDoneEvents(choiceSnapshot);\n\n if (state.current_tool_call_index != null) {\n this.#emitToolCallDoneEvent(choiceSnapshot, state.current_tool_call_index);\n }\n }\n\n for (const toolCall of choice.delta.tool_calls ?? []) {\n if (state.current_tool_call_index !== toolCall.index) {\n this.#emitContentDoneEvents(choiceSnapshot);\n\n // new tool call started, the previous one is done\n if (state.current_tool_call_index != null) {\n this.#emitToolCallDoneEvent(choiceSnapshot, state.current_tool_call_index);\n }\n }\n\n state.current_tool_call_index = toolCall.index;\n }\n\n for (const toolCallDelta of choice.delta.tool_calls ?? []) {\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];\n if (!toolCallSnapshot?.type) {\n continue;\n }\n\n if (toolCallSnapshot?.type === 'function') {\n this._emit('tool_calls.function.arguments.delta', {\n name: toolCallSnapshot.function?.name,\n index: toolCallDelta.index,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: toolCallSnapshot.function.parsed_arguments,\n arguments_delta: toolCallDelta.function?.arguments ?? '',\n });\n } else {\n assertNever(toolCallSnapshot?.type);\n }\n }\n }\n }\n\n #emitToolCallDoneEvent(choiceSnapshot: ChatCompletionSnapshot.Choice, toolCallIndex: number) {\n const state = this.#getChoiceEventState(choiceSnapshot);\n if (state.done_tool_calls.has(toolCallIndex)) {\n // we've already fired the done event\n return;\n }\n\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];\n if (!toolCallSnapshot) {\n throw new Error('no tool call snapshot');\n }\n if (!toolCallSnapshot.type) {\n throw new Error('tool call snapshot missing `type`');\n }\n\n if (toolCallSnapshot.type === 'function') {\n const inputTool = this.#params?.tools?.find(\n (tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name,\n );\n\n this._emit('tool_calls.function.arguments.done', {\n name: toolCallSnapshot.function.name,\n index: toolCallIndex,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments:\n isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)\n : null,\n });\n } else {\n assertNever(toolCallSnapshot.type);\n }\n }\n\n #emitContentDoneEvents(choiceSnapshot: ChatCompletionSnapshot.Choice) {\n const state = this.#getChoiceEventState(choiceSnapshot);\n\n if (choiceSnapshot.message.content && !state.content_done) {\n state.content_done = true;\n\n const responseFormat = this.#getAutoParseableResponseFormat();\n\n this._emit('content.done', {\n content: choiceSnapshot.message.content,\n parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : (null as any),\n });\n }\n\n if (choiceSnapshot.message.refusal && !state.refusal_done) {\n state.refusal_done = true;\n\n this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal });\n }\n\n if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {\n state.logprobs_content_done = true;\n\n this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content });\n }\n\n if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {\n state.logprobs_refusal_done = true;\n\n this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal });\n }\n }\n\n #endRequest(): ParsedChatCompletion<ParsedT> {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentChatCompletionSnapshot;\n if (!snapshot) {\n throw new OpenAIError(`request ended without sending any chunks`);\n }\n this.#currentChatCompletionSnapshot = undefined;\n this.#choiceEventStates = [];\n return finalizeChatCompletion(snapshot, this.#params);\n }\n\n protected override async _createChatCompletion(\n client: OpenAI,\n params: ChatCompletionCreateParams,\n options?: Core.RequestOptions,\n ): Promise<ParsedChatCompletion<ParsedT>> {\n super._createChatCompletion;\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n\n const stream = await client.chat.completions.create(\n { ...params, stream: true },\n { ...options, signal: this.controller.signal },\n );\n this._connected();\n for await (const chunk of stream) {\n this.#addChunk(chunk);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(this.#endRequest());\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: Core.RequestOptions,\n ): Promise<ChatCompletion> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n this._connected();\n const stream = Stream.fromReadableStream<ChatCompletionChunk>(readableStream, this.controller);\n let chatId;\n for await (const chunk of stream) {\n if (chatId && chatId !== chunk.id) {\n // A new request has been made.\n this._addChatCompletion(this.#endRequest());\n }\n\n this.#addChunk(chunk);\n chatId = chunk.id;\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(this.#endRequest());\n }\n\n #getAutoParseableResponseFormat(): AutoParseableResponseFormat<ParsedT> | null {\n const responseFormat = this.#params?.response_format;\n if (isAutoParsableResponseFormat<ParsedT>(responseFormat)) {\n return responseFormat;\n }\n\n return null;\n }\n\n #accumulateChatCompletion(chunk: ChatCompletionChunk): ChatCompletionSnapshot {\n let snapshot = this.#currentChatCompletionSnapshot;\n const { choices, ...rest } = chunk;\n if (!snapshot) {\n snapshot = this.#currentChatCompletionSnapshot = {\n ...rest,\n choices: [],\n };\n } else {\n Object.assign(snapshot, rest);\n }\n\n for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {\n let choice = snapshot.choices[index];\n if (!choice) {\n choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };\n }\n\n if (logprobs) {\n if (!choice.logprobs) {\n choice.logprobs = Object.assign({}, logprobs);\n } else {\n const { content, refusal, ...rest } = logprobs;\n assertIsEmpty(rest);\n Object.assign(choice.logprobs, rest);\n\n if (content) {\n choice.logprobs.content ??= [];\n choice.logprobs.content.push(...content);\n }\n\n if (refusal) {\n choice.logprobs.refusal ??= [];\n choice.logprobs.refusal.push(...refusal);\n }\n }\n }\n\n if (finish_reason) {\n choice.finish_reason = finish_reason;\n\n if (this.#params && hasAutoParseableInput(this.#params)) {\n if (finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n\n if (finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n }\n }\n\n Object.assign(choice, other);\n\n if (!delta) continue; // Shouldn't happen; just in case.\n\n const { content, refusal, function_call, role, tool_calls, ...rest } = delta;\n assertIsEmpty(rest);\n Object.assign(choice.message, rest);\n\n if (refusal) {\n choice.message.refusal = (choice.message.refusal || '') + refusal;\n }\n\n if (role) choice.message.role = role;\n if (function_call) {\n if (!choice.message.function_call) {\n choice.message.function_call = function_call;\n } else {\n if (function_call.name) choice.message.function_call.name = function_call.name;\n if (function_call.arguments) {\n choice.message.function_call.arguments ??= '';\n choice.message.function_call.arguments += function_call.arguments;\n }\n }\n }\n if (content) {\n choice.message.content = (choice.message.content || '') + content;\n\n if (!choice.message.refusal && this.#getAutoParseableResponseFormat()) {\n choice.message.parsed = partialParse(choice.message.content);\n }\n }\n\n if (tool_calls) {\n if (!choice.message.tool_calls) choice.message.tool_calls = [];\n\n for (const { index, id, type, function: fn, ...rest } of tool_calls) {\n const tool_call = (choice.message.tool_calls[index] ??=\n {} as ChatCompletionSnapshot.Choice.Message.ToolCall);\n Object.assign(tool_call, rest);\n if (id) tool_call.id = id;\n if (type) tool_call.type = type;\n if (fn) tool_call.function ??= { name: fn.name ?? '', arguments: '' };\n if (fn?.name) tool_call.function!.name = fn.name;\n if (fn?.arguments) {\n tool_call.function!.arguments += fn.arguments;\n\n if (shouldParseToolCall(this.#params, tool_call)) {\n tool_call.function!.parsed_arguments = partialParse(tool_call.function!.arguments);\n }\n }\n }\n }\n }\n return snapshot;\n }\n\n [Symbol.asyncIterator](this: ChatCompletionStream<ParsedT>): AsyncIterator<ChatCompletionChunk> {\n const pushQueue: ChatCompletionChunk[] = [];\n const readQueue: {\n resolve: (chunk: ChatCompletionChunk | undefined) => void;\n reject: (err: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('chunk', (chunk) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(chunk);\n } else {\n pushQueue.push(chunk);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<ChatCompletionChunk>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<ChatCompletionChunk | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\nfunction finalizeChatCompletion<ParsedT>(\n snapshot: ChatCompletionSnapshot,\n params: ChatCompletionCreateParams | null,\n): ParsedChatCompletion<ParsedT> {\n const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;\n const completion: ChatCompletion = {\n ...rest,\n id,\n choices: choices.map(\n ({ message, finish_reason, index, logprobs, ...choiceRest }): ChatCompletion.Choice => {\n if (!finish_reason) {\n throw new OpenAIError(`missing finish_reason for choice ${index}`);\n }\n\n const { content = null, function_call, tool_calls, ...messageRest } = message;\n const role = message.role as 'assistant'; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine.\n if (!role) {\n throw new OpenAIError(`missing role for choice ${index}`);\n }\n\n if (function_call) {\n const { arguments: args, name } = function_call;\n if (args == null) {\n throw new OpenAIError(`missing function_call.arguments for choice ${index}`);\n }\n\n if (!name) {\n throw new OpenAIError(`missing function_call.name for choice ${index}`);\n }\n\n return {\n ...choiceRest,\n message: {\n content,\n function_call: { arguments: args, name },\n role,\n refusal: message.refusal ?? null,\n },\n finish_reason,\n index,\n logprobs,\n };\n }\n\n if (tool_calls) {\n return {\n ...choiceRest,\n index,\n finish_reason,\n logprobs,\n message: {\n ...messageRest,\n role,\n content,\n refusal: message.refusal ?? null,\n tool_calls: tool_calls.map((tool_call, i) => {\n const { function: fn, type, id, ...toolRest } = tool_call;\n const { arguments: args, name, ...fnRest } = fn || {};\n if (id == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\\n${str(snapshot)}`);\n }\n if (type == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\\n${str(snapshot)}`);\n }\n if (name == null) {\n throw new OpenAIError(\n `missing choices[${index}].tool_calls[${i}].function.name\\n${str(snapshot)}`,\n );\n }\n if (args == null) {\n throw new OpenAIError(\n `missing choices[${index}].tool_calls[${i}].function.arguments\\n${str(snapshot)}`,\n );\n }\n\n return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };\n }),\n },\n };\n }\n return {\n ...choiceRest,\n message: { ...messageRest, content, role, refusal: message.refusal ?? null },\n finish_reason,\n index,\n logprobs,\n };\n },\n ),\n created,\n model,\n object: 'chat.completion',\n ...(system_fingerprint ? { system_fingerprint } : {}),\n };\n\n return maybeParseChatCompletion(completion, params);\n}\n\nfunction str(x: unknown) {\n return JSON.stringify(x);\n}\n\n/**\n * Represents a streamed chunk of a chat completion response returned by model,\n * based on the provided input.\n */\nexport interface ChatCompletionSnapshot {\n /**\n * A unique identifier for the chat completion.\n */\n id: string;\n\n /**\n * A list of chat completion choices. Can be more than one if `n` is greater\n * than 1.\n */\n choices: Array<ChatCompletionSnapshot.Choice>;\n\n /**\n * The Unix timestamp (in seconds) of when the chat completion was created.\n */\n created: number;\n\n /**\n * The model to generate the completion.\n */\n model: string;\n\n // Note we do not include an \"object\" type on the snapshot,\n // because the object is not a valid \"chat.completion\" until finalized.\n // object: 'chat.completion';\n\n /**\n * This fingerprint represents the backend configuration that the model runs with.\n *\n * Can be used in conjunction with the `seed` request parameter to understand when\n * backend changes have been made that might impact determinism.\n */\n system_fingerprint?: string;\n}\n\nexport namespace ChatCompletionSnapshot {\n export interface Choice {\n /**\n * A chat completion delta generated by streamed model responses.\n */\n message: Choice.Message;\n\n /**\n * The reason the model stopped generating tokens. This will be `stop` if the model\n * hit a natural stop point or a provided stop sequence, `length` if the maximum\n * number of tokens specified in the request was reached, `content_filter` if\n * content was omitted due to a flag from our content filters, or `function_call`\n * if the model called a function.\n */\n finish_reason: ChatCompletion.Choice['finish_reason'] | null;\n\n /**\n * Log probability information for the choice.\n */\n logprobs: ChatCompletion.Choice.Logprobs | null;\n\n /**\n * The index of the choice in the list of choices.\n */\n index: number;\n }\n\n export namespace Choice {\n /**\n * A chat completion delta generated by streamed model responses.\n */\n export interface Message {\n /**\n * The contents of the chunk message.\n */\n content?: string | null;\n\n refusal?: string | null;\n\n parsed?: unknown | null;\n\n /**\n * The name and arguments of a function that should be called, as generated by the\n * model.\n */\n function_call?: Message.FunctionCall;\n\n tool_calls?: Array<Message.ToolCall>;\n\n /**\n * The role of the author of this message.\n */\n role?: ChatCompletionRole;\n }\n\n export namespace Message {\n export interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n function: ToolCall.Function;\n\n /**\n * The type of the tool.\n */\n type: 'function';\n }\n\n export namespace ToolCall {\n export interface Function {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n parsed_arguments?: unknown;\n\n /**\n * The name of the function to call.\n */\n name: string;\n }\n }\n\n /**\n * The name and arguments of a function that should be called, as generated by the\n * model.\n */\n export interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments?: string;\n\n /**\n * The name of the function to call.\n */\n name?: string;\n }\n }\n }\n}\n\ntype AssertIsEmpty<T extends {}> = keyof T extends never ? T : never;\n\n/**\n * Ensures the given argument is an empty object, useful for\n * asserting that all known properties on an object have been\n * destructured.\n */\nfunction assertIsEmpty<T extends {}>(obj: AssertIsEmpty<T>): asserts obj is AssertIsEmpty<T> {\n return;\n}\n\nfunction assertNever(_x: never) {}\n","import {\n type ChatCompletionChunk,\n type ChatCompletionCreateParamsStreaming,\n} from '../resources/chat/completions';\nimport { RunnerOptions, type AbstractChatCompletionRunnerEvents } from './AbstractChatCompletionRunner';\nimport { type ReadableStream } from '../_shims/index';\nimport { RunnableTools, type BaseFunctionsArgs, type RunnableFunctions } from './RunnableFunction';\nimport { ChatCompletionSnapshot, ChatCompletionStream } from './ChatCompletionStream';\nimport OpenAI from '../index';\nimport { AutoParseableTool } from '../lib/parser';\n\nexport interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents {\n content: (contentDelta: string, contentSnapshot: string) => void;\n chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void;\n}\n\nexport type ChatCompletionStreamingFunctionRunnerParams<FunctionsArgs extends BaseFunctionsArgs> = Omit<\n ChatCompletionCreateParamsStreaming,\n 'functions'\n> & {\n functions: RunnableFunctions<FunctionsArgs>;\n};\n\nexport type ChatCompletionStreamingToolRunnerParams<FunctionsArgs extends BaseFunctionsArgs> = Omit<\n ChatCompletionCreateParamsStreaming,\n 'tools'\n> & {\n tools: RunnableTools<FunctionsArgs> | AutoParseableTool<any, true>[];\n};\n\nexport class ChatCompletionStreamingRunner<ParsedT = null>\n extends ChatCompletionStream<ParsedT>\n implements AsyncIterable<ChatCompletionChunk>\n{\n static override fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner<null> {\n const runner = new ChatCompletionStreamingRunner(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n /** @deprecated - please use `runTools` instead. */\n static runFunctions<T extends (string | object)[]>(\n client: OpenAI,\n params: ChatCompletionStreamingFunctionRunnerParams<T>,\n options?: RunnerOptions,\n ): ChatCompletionStreamingRunner<null> {\n const runner = new ChatCompletionStreamingRunner(null);\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' },\n };\n runner._run(() => runner._runFunctions(client, params, opts));\n return runner;\n }\n\n static runTools<T extends (string | object)[], ParsedT = null>(\n client: OpenAI,\n params: ChatCompletionStreamingToolRunnerParams<T>,\n options?: RunnerOptions,\n ): ChatCompletionStreamingRunner<ParsedT> {\n const runner = new ChatCompletionStreamingRunner<ParsedT>(\n // @ts-expect-error TODO these types are incompatible\n params,\n );\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport * as Core from '../../../core';\nimport { APIResource } from '../../../resource';\nimport { ChatCompletionRunner, ChatCompletionFunctionRunnerParams } from '../../../lib/ChatCompletionRunner';\nimport {\n ChatCompletionStreamingRunner,\n ChatCompletionStreamingFunctionRunnerParams,\n} from '../../../lib/ChatCompletionStreamingRunner';\nimport { BaseFunctionsArgs } from '../../../lib/RunnableFunction';\nimport { RunnerOptions } from '../../../lib/AbstractChatCompletionRunner';\nimport { ChatCompletionToolRunnerParams } from '../../../lib/ChatCompletionRunner';\nimport { ChatCompletionStreamingToolRunnerParams } from '../../../lib/ChatCompletionStreamingRunner';\nimport { ChatCompletionStream, type ChatCompletionStreamParams } from '../../../lib/ChatCompletionStream';\nimport {\n ChatCompletion,\n ChatCompletionCreateParamsNonStreaming,\n ChatCompletionMessage,\n ChatCompletionMessageToolCall,\n} from '../../chat/completions';\nimport { ExtractParsedContentFromParams, parseChatCompletion, validateInputTools } from '../../../lib/parser';\n\nexport {\n ChatCompletionStreamingRunner,\n type ChatCompletionStreamingFunctionRunnerParams,\n} from '../../../lib/ChatCompletionStreamingRunner';\nexport {\n type RunnableFunction,\n type RunnableFunctions,\n type RunnableFunctionWithParse,\n type RunnableFunctionWithoutParse,\n ParsingFunction,\n ParsingToolFunction,\n} from '../../../lib/RunnableFunction';\nexport { type ChatCompletionToolRunnerParams } from '../../../lib/ChatCompletionRunner';\nexport { type ChatCompletionStreamingToolRunnerParams } from '../../../lib/ChatCompletionStreamingRunner';\nexport { ChatCompletionStream, type ChatCompletionStreamParams } from '../../../lib/ChatCompletionStream';\nexport {\n ChatCompletionRunner,\n type ChatCompletionFunctionRunnerParams,\n} from '../../../lib/ChatCompletionRunner';\n\nexport interface ParsedFunction extends ChatCompletionMessageToolCall.Function {\n parsed_arguments?: unknown;\n}\n\nexport interface ParsedFunctionToolCall extends ChatCompletionMessageToolCall {\n function: ParsedFunction;\n}\n\nexport interface ParsedChatCompletionMessage<ParsedT> extends ChatCompletionMessage {\n parsed: ParsedT | null;\n tool_calls?: Array<ParsedFunctionToolCall>;\n}\n\nexport interface ParsedChoice<ParsedT> extends ChatCompletion.Choice {\n message: ParsedChatCompletionMessage<ParsedT>;\n}\n\nexport interface ParsedChatCompletion<ParsedT> extends ChatCompletion {\n choices: Array<ParsedChoice<ParsedT>>;\n}\n\nexport type ChatCompletionParseParams = ChatCompletionCreateParamsNonStreaming;\n\nexport class Completions extends APIResource {\n parse<Params extends ChatCompletionParseParams, ParsedT = ExtractParsedContentFromParams<Params>>(\n body: Params,\n options?: Core.RequestOptions,\n ): Core.APIPromise<ParsedChatCompletion<ParsedT>> {\n validateInputTools(body.tools);\n\n return this._client.chat.completions\n .create(body, {\n ...options,\n headers: {\n ...options?.headers,\n 'X-Stainless-Helper-Method': 'beta.chat.completions.parse',\n },\n })\n ._thenUnwrap((completion) => parseChatCompletion(completion, body));\n }\n\n /**\n * @deprecated - use `runTools` instead.\n */\n runFunctions<FunctionsArgs extends BaseFunctionsArgs>(\n body: ChatCompletionFunctionRunnerParams<FunctionsArgs>,\n options?: Core.RequestOptions,\n ): ChatCompletionRunner<null>;\n runFunctions<FunctionsArgs extends BaseFunctionsArgs>(\n body: ChatCompletionStreamingFunctionRunnerParams<FunctionsArgs>,\n options?: Core.RequestOptions,\n ): ChatCompletionStreamingRunner<null>;\n runFunctions<FunctionsArgs extends BaseFunctionsArgs>(\n body:\n | ChatCompletionFunctionRunnerParams<FunctionsArgs>\n | ChatCompletionStreamingFunctionRunnerParams<FunctionsArgs>,\n options?: Core.RequestOptions,\n ): ChatCompletionRunner<null> | ChatCompletionStreamingRunner<null> {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runFunctions(\n this._client,\n body as ChatCompletionStreamingFunctionRunnerParams<FunctionsArgs>,\n options,\n );\n }\n return ChatCompletionRunner.runFunctions(\n this._client,\n body as ChatCompletionFunctionRunnerParams<FunctionsArgs>,\n options,\n );\n }\n\n /**\n * A convenience helper for using tool calls with the /chat/completions endpoint\n * which automatically calls the JavaScript functions you provide and sends their\n * results back to the /chat/completions endpoint, looping as long as the model\n * requests function calls.\n *\n * For more details and examples, see\n * [the docs](https://github.com/openai/openai-node#automated-function-calls)\n */\n runTools<\n Params extends ChatCompletionToolRunnerParams<any>,\n ParsedT = ExtractParsedContentFromParams<Params>,\n >(body: Params, options?: RunnerOptions): ChatCompletionRunner<ParsedT>;\n\n runTools<\n Params extends ChatCompletionStreamingToolRunnerParams<any>,\n ParsedT = ExtractParsedContentFromParams<Params>,\n >(body: Params, options?: RunnerOptions): ChatCompletionStreamingRunner<ParsedT>;\n\n runTools<\n Params extends ChatCompletionToolRunnerParams<any> | ChatCompletionStreamingToolRunnerParams<any>,\n ParsedT = ExtractParsedContentFromParams<Params>,\n >(\n body: Params,\n options?: RunnerOptions,\n ): ChatCompletionRunner<ParsedT> | ChatCompletionStreamingRunner<ParsedT> {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runTools(\n this._client,\n body as ChatCompletionStreamingToolRunnerParams<any>,\n options,\n );\n }\n\n return ChatCompletionRunner.runTools(this._client, body as ChatCompletionToolRunnerParams<any>, options);\n }\n\n /**\n * Creates a chat completion stream\n */\n stream<Params extends ChatCompletionStreamParams, ParsedT = ExtractParsedContentFromParams<Params>>(\n body: Params,\n options?: Core.RequestOptions,\n ): ChatCompletionStream<ParsedT> {\n return ChatCompletionStream.createChatCompletion(this._client, body, options);\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as CompletionsAPI from './completions';\n\nexport class Chat extends APIResource {\n completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client);\n}\n\nexport namespace Chat {\n export import Completions = CompletionsAPI.Completions;\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as Core from '../../../core';\n\nexport class Sessions extends APIResource {\n /**\n * Create an ephemeral API token for use in client-side applications with the\n * Realtime API. Can be configured with the same session parameters as the\n * `session.update` client event.\n *\n * It responds with a session object, plus a `client_secret` key which contains a\n * usable ephemeral API token that can be used to authenticate browser clients for\n * the Realtime API.\n *\n * @example\n * ```ts\n * const session =\n * await client.beta.realtime.sessions.create();\n * ```\n */\n create(body: SessionCreateParams, options?: Core.RequestOptions): Core.APIPromise<SessionCreateResponse> {\n return this._client.post('/realtime/sessions', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n\n/**\n * Realtime session object configuration.\n */\nexport interface Session {\n /**\n * Unique identifier for the session that looks like `sess_1234567890abcdef`.\n */\n id?: string;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For\n * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel\n * (mono), and little-endian byte order.\n */\n input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n input_audio_noise_reduction?: Session.InputAudioNoiseReduction;\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through\n * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)\n * and should be treated as guidance of input audio content rather than precisely\n * what the model heard. The client can optionally set the language and prompt for\n * transcription, these offer additional guidance to the transcription service.\n */\n input_audio_transcription?: Session.InputAudioTranscription;\n\n /**\n * The default system instructions (i.e. system message) prepended to model calls.\n * This field allows the client to guide the model on desired responses. The model\n * can be instructed on response content and format, (e.g. \"be extremely succinct\",\n * \"act friendly\", \"here are examples of good responses\") and on audio behavior\n * (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The\n * instructions are not guaranteed to be followed by the model, but they provide\n * guidance to the model on the desired behavior.\n *\n * Note that the server sets default instructions which will be used if this field\n * is not set and are visible in the `session.created` event at the start of the\n * session.\n */\n instructions?: string;\n\n /**\n * Maximum number of output tokens for a single assistant response, inclusive of\n * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or\n * `inf` for the maximum available tokens for a given model. Defaults to `inf`.\n */\n max_response_output_tokens?: number | 'inf';\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * The Realtime model used for this session.\n */\n model?:\n | 'gpt-4o-realtime-preview'\n | 'gpt-4o-realtime-preview-2024-10-01'\n | 'gpt-4o-realtime-preview-2024-12-17'\n | 'gpt-4o-mini-realtime-preview'\n | 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n /**\n * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n * For `pcm16`, output audio is sampled at a rate of 24kHz.\n */\n output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a\n * temperature of 0.8 is highly recommended for best performance.\n */\n temperature?: number;\n\n /**\n * How the model chooses tools. Options are `auto`, `none`, `required`, or specify\n * a function.\n */\n tool_choice?: string;\n\n /**\n * Tools (functions) available to the model.\n */\n tools?: Array<Session.Tool>;\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n turn_detection?: Session.TurnDetection;\n\n /**\n * The voice the model uses to respond. Voice cannot be changed during the session\n * once the model has responded with audio at least once. Current voice options are\n * `alloy`, `ash`, `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`.\n */\n voice?:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n}\n\nexport namespace Session {\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n export interface InputAudioNoiseReduction {\n /**\n * Type of noise reduction. `near_field` is for close-talking microphones such as\n * headphones, `far_field` is for far-field microphones such as laptop or\n * conference room microphones.\n */\n type?: 'near_field' | 'far_field';\n }\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through\n * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)\n * and should be treated as guidance of input audio content rather than precisely\n * what the model heard. The client can optionally set the language and prompt for\n * transcription, these offer additional guidance to the transcription service.\n */\n export interface InputAudioTranscription {\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * The model to use for transcription, current options are `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, and `whisper-1`.\n */\n model?: string;\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. For `whisper-1`, the\n * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\n * For `gpt-4o-transcribe` models, the prompt is a free text string, for example\n * \"expect words related to technology\".\n */\n prompt?: string;\n }\n\n export interface Tool {\n /**\n * The description of the function, including guidance on when and how to call it,\n * and guidance about what to tell the user when calling (if anything).\n */\n description?: string;\n\n /**\n * The name of the function.\n */\n name?: string;\n\n /**\n * Parameters of the function in JSON Schema.\n */\n parameters?: unknown;\n\n /**\n * The type of the tool, i.e. `function`.\n */\n type?: 'function';\n }\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n export interface TurnDetection {\n /**\n * Whether or not to automatically generate a response when a VAD stop event\n * occurs.\n */\n create_response?: boolean;\n\n /**\n * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low`\n * will wait longer for the user to continue speaking, `high` will respond more\n * quickly. `auto` is the default and is equivalent to `medium`.\n */\n eagerness?: 'low' | 'medium' | 'high' | 'auto';\n\n /**\n * Whether or not to automatically interrupt any ongoing response with output to\n * the default conversation (i.e. `conversation` of `auto`) when a VAD start event\n * occurs.\n */\n interrupt_response?: boolean;\n\n /**\n * Used only for `server_vad` mode. Amount of audio to include before the VAD\n * detected speech (in milliseconds). Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Duration of silence to detect speech stop (in\n * milliseconds). Defaults to 500ms. With shorter values the model will respond\n * more quickly, but may jump in on short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this\n * defaults to 0.5. A higher threshold will require louder audio to activate the\n * model, and thus might perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection.\n */\n type?: 'server_vad' | 'semantic_vad';\n }\n}\n\n/**\n * A new Realtime session configuration, with an ephermeral key. Default TTL for\n * keys is one minute.\n */\nexport interface SessionCreateResponse {\n /**\n * Ephemeral key returned by the API.\n */\n client_secret: SessionCreateResponse.ClientSecret;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n */\n input_audio_format?: string;\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through Whisper and should be treated as rough guidance rather\n * than the representation understood by the model.\n */\n input_audio_transcription?: SessionCreateResponse.InputAudioTranscription;\n\n /**\n * The default system instructions (i.e. system message) prepended to model calls.\n * This field allows the client to guide the model on desired responses. The model\n * can be instructed on response content and format, (e.g. \"be extremely succinct\",\n * \"act friendly\", \"here are examples of good responses\") and on audio behavior\n * (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The\n * instructions are not guaranteed to be followed by the model, but they provide\n * guidance to the model on the desired behavior.\n *\n * Note that the server sets default instructions which will be used if this field\n * is not set and are visible in the `session.created` event at the start of the\n * session.\n */\n instructions?: string;\n\n /**\n * Maximum number of output tokens for a single assistant response, inclusive of\n * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or\n * `inf` for the maximum available tokens for a given model. Defaults to `inf`.\n */\n max_response_output_tokens?: number | 'inf';\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n */\n output_audio_format?: string;\n\n /**\n * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n */\n temperature?: number;\n\n /**\n * How the model chooses tools. Options are `auto`, `none`, `required`, or specify\n * a function.\n */\n tool_choice?: string;\n\n /**\n * Tools (functions) available to the model.\n */\n tools?: Array<SessionCreateResponse.Tool>;\n\n /**\n * Configuration for turn detection. Can be set to `null` to turn off. Server VAD\n * means that the model will detect the start and end of speech based on audio\n * volume and respond at the end of user speech.\n */\n turn_detection?: SessionCreateResponse.TurnDetection;\n\n /**\n * The voice the model uses to respond. Voice cannot be changed during the session\n * once the model has responded with audio at least once. Current voice options are\n * `alloy`, `ash`, `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`.\n */\n voice?:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n}\n\nexport namespace SessionCreateResponse {\n /**\n * Ephemeral key returned by the API.\n */\n export interface ClientSecret {\n /**\n * Timestamp for when the token expires. Currently, all tokens expire after one\n * minute.\n */\n expires_at: number;\n\n /**\n * Ephemeral key usable in client environments to authenticate connections to the\n * Realtime API. Use this in client-side environments rather than a standard API\n * token, which should only be used server-side.\n */\n value: string;\n }\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through Whisper and should be treated as rough guidance rather\n * than the representation understood by the model.\n */\n export interface InputAudioTranscription {\n /**\n * The model to use for transcription, `whisper-1` is the only currently supported\n * model.\n */\n model?: string;\n }\n\n export interface Tool {\n /**\n * The description of the function, including guidance on when and how to call it,\n * and guidance about what to tell the user when calling (if anything).\n */\n description?: string;\n\n /**\n * The name of the function.\n */\n name?: string;\n\n /**\n * Parameters of the function in JSON Schema.\n */\n parameters?: unknown;\n\n /**\n * The type of the tool, i.e. `function`.\n */\n type?: 'function';\n }\n\n /**\n * Configuration for turn detection. Can be set to `null` to turn off. Server VAD\n * means that the model will detect the start and end of speech based on audio\n * volume and respond at the end of user speech.\n */\n export interface TurnDetection {\n /**\n * Amount of audio to include before the VAD detected speech (in milliseconds).\n * Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms.\n * With shorter values the model will respond more quickly, but may jump in on\n * short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher\n * threshold will require louder audio to activate the model, and thus might\n * perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection, only `server_vad` is currently supported.\n */\n type?: string;\n }\n}\n\nexport interface SessionCreateParams {\n /**\n * Configuration options for the generated client secret.\n */\n client_secret?: SessionCreateParams.ClientSecret;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For\n * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel\n * (mono), and little-endian byte order.\n */\n input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n input_audio_noise_reduction?: SessionCreateParams.InputAudioNoiseReduction;\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through\n * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)\n * and should be treated as guidance of input audio content rather than precisely\n * what the model heard. The client can optionally set the language and prompt for\n * transcription, these offer additional guidance to the transcription service.\n */\n input_audio_transcription?: SessionCreateParams.InputAudioTranscription;\n\n /**\n * The default system instructions (i.e. system message) prepended to model calls.\n * This field allows the client to guide the model on desired responses. The model\n * can be instructed on response content and format, (e.g. \"be extremely succinct\",\n * \"act friendly\", \"here are examples of good responses\") and on audio behavior\n * (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The\n * instructions are not guaranteed to be followed by the model, but they provide\n * guidance to the model on the desired behavior.\n *\n * Note that the server sets default instructions which will be used if this field\n * is not set and are visible in the `session.created` event at the start of the\n * session.\n */\n instructions?: string;\n\n /**\n * Maximum number of output tokens for a single assistant response, inclusive of\n * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or\n * `inf` for the maximum available tokens for a given model. Defaults to `inf`.\n */\n max_response_output_tokens?: number | 'inf';\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * The Realtime model used for this session.\n */\n model?:\n | 'gpt-4o-realtime-preview'\n | 'gpt-4o-realtime-preview-2024-10-01'\n | 'gpt-4o-realtime-preview-2024-12-17'\n | 'gpt-4o-mini-realtime-preview'\n | 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n /**\n * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n * For `pcm16`, output audio is sampled at a rate of 24kHz.\n */\n output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a\n * temperature of 0.8 is highly recommended for best performance.\n */\n temperature?: number;\n\n /**\n * How the model chooses tools. Options are `auto`, `none`, `required`, or specify\n * a function.\n */\n tool_choice?: string;\n\n /**\n * Tools (functions) available to the model.\n */\n tools?: Array<SessionCreateParams.Tool>;\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n turn_detection?: SessionCreateParams.TurnDetection;\n\n /**\n * The voice the model uses to respond. Voice cannot be changed during the session\n * once the model has responded with audio at least once. Current voice options are\n * `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`,\n * `shimmer`, and `verse`.\n */\n voice?:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n}\n\nexport namespace SessionCreateParams {\n /**\n * Configuration options for the generated client secret.\n */\n export interface ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n expires_at?: ClientSecret.ExpiresAt;\n }\n\n export namespace ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n export interface ExpiresAt {\n /**\n * The anchor point for the ephemeral token expiration. Only `created_at` is\n * currently supported.\n */\n anchor?: 'created_at';\n\n /**\n * The number of seconds from the anchor point to the expiration. Select a value\n * between `10` and `7200`.\n */\n seconds?: number;\n }\n }\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n export interface InputAudioNoiseReduction {\n /**\n * Type of noise reduction. `near_field` is for close-talking microphones such as\n * headphones, `far_field` is for far-field microphones such as laptop or\n * conference room microphones.\n */\n type?: 'near_field' | 'far_field';\n }\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through\n * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)\n * and should be treated as guidance of input audio content rather than precisely\n * what the model heard. The client can optionally set the language and prompt for\n * transcription, these offer additional guidance to the transcription service.\n */\n export interface InputAudioTranscription {\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * The model to use for transcription, current options are `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, and `whisper-1`.\n */\n model?: string;\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. For `whisper-1`, the\n * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\n * For `gpt-4o-transcribe` models, the prompt is a free text string, for example\n * \"expect words related to technology\".\n */\n prompt?: string;\n }\n\n export interface Tool {\n /**\n * The description of the function, including guidance on when and how to call it,\n * and guidance about what to tell the user when calling (if anything).\n */\n description?: string;\n\n /**\n * The name of the function.\n */\n name?: string;\n\n /**\n * Parameters of the function in JSON Schema.\n */\n parameters?: unknown;\n\n /**\n * The type of the tool, i.e. `function`.\n */\n type?: 'function';\n }\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n export interface TurnDetection {\n /**\n * Whether or not to automatically generate a response when a VAD stop event\n * occurs.\n */\n create_response?: boolean;\n\n /**\n * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low`\n * will wait longer for the user to continue speaking, `high` will respond more\n * quickly. `auto` is the default and is equivalent to `medium`.\n */\n eagerness?: 'low' | 'medium' | 'high' | 'auto';\n\n /**\n * Whether or not to automatically interrupt any ongoing response with output to\n * the default conversation (i.e. `conversation` of `auto`) when a VAD start event\n * occurs.\n */\n interrupt_response?: boolean;\n\n /**\n * Used only for `server_vad` mode. Amount of audio to include before the VAD\n * detected speech (in milliseconds). Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Duration of silence to detect speech stop (in\n * milliseconds). Defaults to 500ms. With shorter values the model will respond\n * more quickly, but may jump in on short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this\n * defaults to 0.5. A higher threshold will require louder audio to activate the\n * model, and thus might perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection.\n */\n type?: 'server_vad' | 'semantic_vad';\n }\n}\n\nexport declare namespace Sessions {\n export {\n type Session as Session,\n type SessionCreateResponse as SessionCreateResponse,\n type SessionCreateParams as SessionCreateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as Core from '../../../core';\n\nexport class TranscriptionSessions extends APIResource {\n /**\n * Create an ephemeral API token for use in client-side applications with the\n * Realtime API specifically for realtime transcriptions. Can be configured with\n * the same session parameters as the `transcription_session.update` client event.\n *\n * It responds with a session object, plus a `client_secret` key which contains a\n * usable ephemeral API token that can be used to authenticate browser clients for\n * the Realtime API.\n *\n * @example\n * ```ts\n * const transcriptionSession =\n * await client.beta.realtime.transcriptionSessions.create();\n * ```\n */\n create(\n body: TranscriptionSessionCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<TranscriptionSession> {\n return this._client.post('/realtime/transcription_sessions', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n\n/**\n * A new Realtime transcription session configuration.\n *\n * When a session is created on the server via REST API, the session object also\n * contains an ephemeral key. Default TTL for keys is 10 minutes. This property is\n * not present when a session is updated via the WebSocket API.\n */\nexport interface TranscriptionSession {\n /**\n * Ephemeral key returned by the API. Only present when the session is created on\n * the server via REST API.\n */\n client_secret: TranscriptionSession.ClientSecret;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n */\n input_audio_format?: string;\n\n /**\n * Configuration of the transcription model.\n */\n input_audio_transcription?: TranscriptionSession.InputAudioTranscription;\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * Configuration for turn detection. Can be set to `null` to turn off. Server VAD\n * means that the model will detect the start and end of speech based on audio\n * volume and respond at the end of user speech.\n */\n turn_detection?: TranscriptionSession.TurnDetection;\n}\n\nexport namespace TranscriptionSession {\n /**\n * Ephemeral key returned by the API. Only present when the session is created on\n * the server via REST API.\n */\n export interface ClientSecret {\n /**\n * Timestamp for when the token expires. Currently, all tokens expire after one\n * minute.\n */\n expires_at: number;\n\n /**\n * Ephemeral key usable in client environments to authenticate connections to the\n * Realtime API. Use this in client-side environments rather than a standard API\n * token, which should only be used server-side.\n */\n value: string;\n }\n\n /**\n * Configuration of the transcription model.\n */\n export interface InputAudioTranscription {\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * The model to use for transcription. Can be `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, or `whisper-1`.\n */\n model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1';\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. The\n * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting)\n * should match the audio language.\n */\n prompt?: string;\n }\n\n /**\n * Configuration for turn detection. Can be set to `null` to turn off. Server VAD\n * means that the model will detect the start and end of speech based on audio\n * volume and respond at the end of user speech.\n */\n export interface TurnDetection {\n /**\n * Amount of audio to include before the VAD detected speech (in milliseconds).\n * Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms.\n * With shorter values the model will respond more quickly, but may jump in on\n * short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher\n * threshold will require louder audio to activate the model, and thus might\n * perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection, only `server_vad` is currently supported.\n */\n type?: string;\n }\n}\n\nexport interface TranscriptionSessionCreateParams {\n /**\n * Configuration options for the generated client secret.\n */\n client_secret?: TranscriptionSessionCreateParams.ClientSecret;\n\n /**\n * The set of items to include in the transcription. Current available items are:\n *\n * - `item.input_audio_transcription.logprobs`\n */\n include?: Array<string>;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For\n * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel\n * (mono), and little-endian byte order.\n */\n input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n input_audio_noise_reduction?: TranscriptionSessionCreateParams.InputAudioNoiseReduction;\n\n /**\n * Configuration for input audio transcription. The client can optionally set the\n * language and prompt for transcription, these offer additional guidance to the\n * transcription service.\n */\n input_audio_transcription?: TranscriptionSessionCreateParams.InputAudioTranscription;\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n turn_detection?: TranscriptionSessionCreateParams.TurnDetection;\n}\n\nexport namespace TranscriptionSessionCreateParams {\n /**\n * Configuration options for the generated client secret.\n */\n export interface ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n expires_at?: ClientSecret.ExpiresAt;\n }\n\n export namespace ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n export interface ExpiresAt {\n /**\n * The anchor point for the ephemeral token expiration. Only `created_at` is\n * currently supported.\n */\n anchor?: 'created_at';\n\n /**\n * The number of seconds from the anchor point to the expiration. Select a value\n * between `10` and `7200`.\n */\n seconds?: number;\n }\n }\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n export interface InputAudioNoiseReduction {\n /**\n * Type of noise reduction. `near_field` is for close-talking microphones such as\n * headphones, `far_field` is for far-field microphones such as laptop or\n * conference room microphones.\n */\n type?: 'near_field' | 'far_field';\n }\n\n /**\n * Configuration for input audio transcription. The client can optionally set the\n * language and prompt for transcription, these offer additional guidance to the\n * transcription service.\n */\n export interface InputAudioTranscription {\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * The model to use for transcription, current options are `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, and `whisper-1`.\n */\n model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1';\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. For `whisper-1`, the\n * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\n * For `gpt-4o-transcribe` models, the prompt is a free text string, for example\n * \"expect words related to technology\".\n */\n prompt?: string;\n }\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n export interface TurnDetection {\n /**\n * Whether or not to automatically generate a response when a VAD stop event\n * occurs. Not available for transcription sessions.\n */\n create_response?: boolean;\n\n /**\n * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low`\n * will wait longer for the user to continue speaking, `high` will respond more\n * quickly. `auto` is the default and is equivalent to `medium`.\n */\n eagerness?: 'low' | 'medium' | 'high' | 'auto';\n\n /**\n * Whether or not to automatically interrupt any ongoing response with output to\n * the default conversation (i.e. `conversation` of `auto`) when a VAD start event\n * occurs. Not available for transcription sessions.\n */\n interrupt_response?: boolean;\n\n /**\n * Used only for `server_vad` mode. Amount of audio to include before the VAD\n * detected speech (in milliseconds). Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Duration of silence to detect speech stop (in\n * milliseconds). Defaults to 500ms. With shorter values the model will respond\n * more quickly, but may jump in on short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this\n * defaults to 0.5. A higher threshold will require louder audio to activate the\n * model, and thus might perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection.\n */\n type?: 'server_vad' | 'semantic_vad';\n }\n}\n\nexport declare namespace TranscriptionSessions {\n export {\n type TranscriptionSession as TranscriptionSession,\n type TranscriptionSessionCreateParams as TranscriptionSessionCreateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as RealtimeAPI from './realtime';\nimport * as Shared from '../../shared';\nimport * as SessionsAPI from './sessions';\nimport {\n Session as SessionsAPISession,\n SessionCreateParams,\n SessionCreateResponse,\n Sessions,\n} from './sessions';\nimport * as TranscriptionSessionsAPI from './transcription-sessions';\nimport {\n TranscriptionSession,\n TranscriptionSessionCreateParams,\n TranscriptionSessions,\n} from './transcription-sessions';\n\nexport class Realtime extends APIResource {\n sessions: SessionsAPI.Sessions = new SessionsAPI.Sessions(this._client);\n transcriptionSessions: TranscriptionSessionsAPI.TranscriptionSessions =\n new TranscriptionSessionsAPI.TranscriptionSessions(this._client);\n}\n\n/**\n * Returned when a conversation is created. Emitted right after session creation.\n */\nexport interface ConversationCreatedEvent {\n /**\n * The conversation resource.\n */\n conversation: ConversationCreatedEvent.Conversation;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The event type, must be `conversation.created`.\n */\n type: 'conversation.created';\n}\n\nexport namespace ConversationCreatedEvent {\n /**\n * The conversation resource.\n */\n export interface Conversation {\n /**\n * The unique ID of the conversation.\n */\n id?: string;\n\n /**\n * The object type, must be `realtime.conversation`.\n */\n object?: 'realtime.conversation';\n }\n}\n\n/**\n * The item to add to the conversation.\n */\nexport interface ConversationItem {\n /**\n * The unique ID of the item, this can be generated by the client to help manage\n * server-side context, but is not required because the server will generate one if\n * not provided.\n */\n id?: string;\n\n /**\n * The arguments of the function call (for `function_call` items).\n */\n arguments?: string;\n\n /**\n * The ID of the function call (for `function_call` and `function_call_output`\n * items). If passed on a `function_call_output` item, the server will check that a\n * `function_call` item with the same ID exists in the conversation history.\n */\n call_id?: string;\n\n /**\n * The content of the message, applicable for `message` items.\n *\n * - Message items of role `system` support only `input_text` content\n * - Message items of role `user` support `input_text` and `input_audio` content\n * - Message items of role `assistant` support `text` content.\n */\n content?: Array<ConversationItemContent>;\n\n /**\n * The name of the function being called (for `function_call` items).\n */\n name?: string;\n\n /**\n * Identifier for the API object being returned - always `realtime.item`.\n */\n object?: 'realtime.item';\n\n /**\n * The output of the function call (for `function_call_output` items).\n */\n output?: string;\n\n /**\n * The role of the message sender (`user`, `assistant`, `system`), only applicable\n * for `message` items.\n */\n role?: 'user' | 'assistant' | 'system';\n\n /**\n * The status of the item (`completed`, `incomplete`). These have no effect on the\n * conversation, but are accepted for consistency with the\n * `conversation.item.created` event.\n */\n status?: 'completed' | 'incomplete';\n\n /**\n * The type of the item (`message`, `function_call`, `function_call_output`).\n */\n type?: 'message' | 'function_call' | 'function_call_output';\n}\n\nexport interface ConversationItemContent {\n /**\n * ID of a previous conversation item to reference (for `item_reference` content\n * types in `response.create` events). These can reference both client and server\n * created items.\n */\n id?: string;\n\n /**\n * Base64-encoded audio bytes, used for `input_audio` content type.\n */\n audio?: string;\n\n /**\n * The text content, used for `input_text` and `text` content types.\n */\n text?: string;\n\n /**\n * The transcript of the audio, used for `input_audio` content type.\n */\n transcript?: string;\n\n /**\n * The content type (`input_text`, `input_audio`, `item_reference`, `text`).\n */\n type?: 'input_text' | 'input_audio' | 'item_reference' | 'text';\n}\n\n/**\n * Add a new Item to the Conversation's context, including messages, function\n * calls, and function call responses. This event can be used both to populate a\n * \"history\" of the conversation and to add new items mid-stream, but has the\n * current limitation that it cannot populate assistant audio messages.\n *\n * If successful, the server will respond with a `conversation.item.created` event,\n * otherwise an `error` event will be sent.\n */\nexport interface ConversationItemCreateEvent {\n /**\n * The item to add to the conversation.\n */\n item: ConversationItem;\n\n /**\n * The event type, must be `conversation.item.create`.\n */\n type: 'conversation.item.create';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n\n /**\n * The ID of the preceding item after which the new item will be inserted. If not\n * set, the new item will be appended to the end of the conversation. If set to\n * `root`, the new item will be added to the beginning of the conversation. If set\n * to an existing ID, it allows an item to be inserted mid-conversation. If the ID\n * cannot be found, an error will be returned and the item will not be added.\n */\n previous_item_id?: string;\n}\n\n/**\n * Returned when a conversation item is created. There are several scenarios that\n * produce this event:\n *\n * - The server is generating a Response, which if successful will produce either\n * one or two Items, which will be of type `message` (role `assistant`) or type\n * `function_call`.\n * - The input audio buffer has been committed, either by the client or the server\n * (in `server_vad` mode). The server will take the content of the input audio\n * buffer and add it to a new user message Item.\n * - The client has sent a `conversation.item.create` event to add a new Item to\n * the Conversation.\n */\nexport interface ConversationItemCreatedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The item to add to the conversation.\n */\n item: ConversationItem;\n\n /**\n * The ID of the preceding item in the Conversation context, allows the client to\n * understand the order of the conversation.\n */\n previous_item_id: string;\n\n /**\n * The event type, must be `conversation.item.created`.\n */\n type: 'conversation.item.created';\n}\n\n/**\n * Send this event when you want to remove any item from the conversation history.\n * The server will respond with a `conversation.item.deleted` event, unless the\n * item does not exist in the conversation history, in which case the server will\n * respond with an error.\n */\nexport interface ConversationItemDeleteEvent {\n /**\n * The ID of the item to delete.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.delete`.\n */\n type: 'conversation.item.delete';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\n/**\n * Returned when an item in the conversation is deleted by the client with a\n * `conversation.item.delete` event. This event is used to synchronize the server's\n * understanding of the conversation history with the client's view.\n */\nexport interface ConversationItemDeletedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item that was deleted.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.deleted`.\n */\n type: 'conversation.item.deleted';\n}\n\n/**\n * This event is the output of audio transcription for user audio written to the\n * user audio buffer. Transcription begins when the input audio buffer is committed\n * by the client or server (in `server_vad` mode). Transcription runs\n * asynchronously with Response creation, so this event may come before or after\n * the Response events.\n *\n * Realtime API models accept audio natively, and thus input transcription is a\n * separate process run on a separate ASR (Automatic Speech Recognition) model,\n * currently always `whisper-1`. Thus the transcript may diverge somewhat from the\n * model's interpretation, and should be treated as a rough guide.\n */\nexport interface ConversationItemInputAudioTranscriptionCompletedEvent {\n /**\n * The index of the content part containing the audio.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the user message item containing the audio.\n */\n item_id: string;\n\n /**\n * The transcribed text.\n */\n transcript: string;\n\n /**\n * The event type, must be `conversation.item.input_audio_transcription.completed`.\n */\n type: 'conversation.item.input_audio_transcription.completed';\n\n /**\n * The log probabilities of the transcription.\n */\n logprobs?: Array<ConversationItemInputAudioTranscriptionCompletedEvent.Logprob> | null;\n}\n\nexport namespace ConversationItemInputAudioTranscriptionCompletedEvent {\n /**\n * A log probability object.\n */\n export interface Logprob {\n /**\n * The token that was used to generate the log probability.\n */\n token: string;\n\n /**\n * The bytes that were used to generate the log probability.\n */\n bytes: Array<number>;\n\n /**\n * The log probability of the token.\n */\n logprob: number;\n }\n}\n\n/**\n * Returned when the text value of an input audio transcription content part is\n * updated.\n */\nexport interface ConversationItemInputAudioTranscriptionDeltaEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.input_audio_transcription.delta`.\n */\n type: 'conversation.item.input_audio_transcription.delta';\n\n /**\n * The index of the content part in the item's content array.\n */\n content_index?: number;\n\n /**\n * The text delta.\n */\n delta?: string;\n\n /**\n * The log probabilities of the transcription.\n */\n logprobs?: Array<ConversationItemInputAudioTranscriptionDeltaEvent.Logprob> | null;\n}\n\nexport namespace ConversationItemInputAudioTranscriptionDeltaEvent {\n /**\n * A log probability object.\n */\n export interface Logprob {\n /**\n * The token that was used to generate the log probability.\n */\n token: string;\n\n /**\n * The bytes that were used to generate the log probability.\n */\n bytes: Array<number>;\n\n /**\n * The log probability of the token.\n */\n logprob: number;\n }\n}\n\n/**\n * Returned when input audio transcription is configured, and a transcription\n * request for a user message failed. These events are separate from other `error`\n * events so that the client can identify the related Item.\n */\nexport interface ConversationItemInputAudioTranscriptionFailedEvent {\n /**\n * The index of the content part containing the audio.\n */\n content_index: number;\n\n /**\n * Details of the transcription error.\n */\n error: ConversationItemInputAudioTranscriptionFailedEvent.Error;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the user message item.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.input_audio_transcription.failed`.\n */\n type: 'conversation.item.input_audio_transcription.failed';\n}\n\nexport namespace ConversationItemInputAudioTranscriptionFailedEvent {\n /**\n * Details of the transcription error.\n */\n export interface Error {\n /**\n * Error code, if any.\n */\n code?: string;\n\n /**\n * A human-readable error message.\n */\n message?: string;\n\n /**\n * Parameter related to the error, if any.\n */\n param?: string;\n\n /**\n * The type of error.\n */\n type?: string;\n }\n}\n\n/**\n * Send this event when you want to retrieve the server's representation of a\n * specific item in the conversation history. This is useful, for example, to\n * inspect user audio after noise cancellation and VAD. The server will respond\n * with a `conversation.item.retrieved` event, unless the item does not exist in\n * the conversation history, in which case the server will respond with an error.\n */\nexport interface ConversationItemRetrieveEvent {\n /**\n * The ID of the item to retrieve.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.retrieve`.\n */\n type: 'conversation.item.retrieve';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\n/**\n * Send this event to truncate a previous assistant message’s audio. The server\n * will produce audio faster than realtime, so this event is useful when the user\n * interrupts to truncate audio that has already been sent to the client but not\n * yet played. This will synchronize the server's understanding of the audio with\n * the client's playback.\n *\n * Truncating audio will delete the server-side text transcript to ensure there is\n * not text in the context that hasn't been heard by the user.\n *\n * If successful, the server will respond with a `conversation.item.truncated`\n * event.\n */\nexport interface ConversationItemTruncateEvent {\n /**\n * Inclusive duration up to which audio is truncated, in milliseconds. If the\n * audio_end_ms is greater than the actual audio duration, the server will respond\n * with an error.\n */\n audio_end_ms: number;\n\n /**\n * The index of the content part to truncate. Set this to 0.\n */\n content_index: number;\n\n /**\n * The ID of the assistant message item to truncate. Only assistant message items\n * can be truncated.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.truncate`.\n */\n type: 'conversation.item.truncate';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\n/**\n * Returned when an earlier assistant audio message item is truncated by the client\n * with a `conversation.item.truncate` event. This event is used to synchronize the\n * server's understanding of the audio with the client's playback.\n *\n * This action will truncate the audio and remove the server-side text transcript\n * to ensure there is no text in the context that hasn't been heard by the user.\n */\nexport interface ConversationItemTruncatedEvent {\n /**\n * The duration up to which the audio was truncated, in milliseconds.\n */\n audio_end_ms: number;\n\n /**\n * The index of the content part that was truncated.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the assistant message item that was truncated.\n */\n item_id: string;\n\n /**\n * The event type, must be `conversation.item.truncated`.\n */\n type: 'conversation.item.truncated';\n}\n\n/**\n * The item to add to the conversation.\n */\nexport interface ConversationItemWithReference {\n /**\n * For an item of type (`message` | `function_call` | `function_call_output`) this\n * field allows the client to assign the unique ID of the item. It is not required\n * because the server will generate one if not provided.\n *\n * For an item of type `item_reference`, this field is required and is a reference\n * to any item that has previously existed in the conversation.\n */\n id?: string;\n\n /**\n * The arguments of the function call (for `function_call` items).\n */\n arguments?: string;\n\n /**\n * The ID of the function call (for `function_call` and `function_call_output`\n * items). If passed on a `function_call_output` item, the server will check that a\n * `function_call` item with the same ID exists in the conversation history.\n */\n call_id?: string;\n\n /**\n * The content of the message, applicable for `message` items.\n *\n * - Message items of role `system` support only `input_text` content\n * - Message items of role `user` support `input_text` and `input_audio` content\n * - Message items of role `assistant` support `text` content.\n */\n content?: Array<ConversationItemContent>;\n\n /**\n * The name of the function being called (for `function_call` items).\n */\n name?: string;\n\n /**\n * Identifier for the API object being returned - always `realtime.item`.\n */\n object?: 'realtime.item';\n\n /**\n * The output of the function call (for `function_call_output` items).\n */\n output?: string;\n\n /**\n * The role of the message sender (`user`, `assistant`, `system`), only applicable\n * for `message` items.\n */\n role?: 'user' | 'assistant' | 'system';\n\n /**\n * The status of the item (`completed`, `incomplete`). These have no effect on the\n * conversation, but are accepted for consistency with the\n * `conversation.item.created` event.\n */\n status?: 'completed' | 'incomplete';\n\n /**\n * The type of the item (`message`, `function_call`, `function_call_output`,\n * `item_reference`).\n */\n type?: 'message' | 'function_call' | 'function_call_output' | 'item_reference';\n}\n\n/**\n * Returned when an error occurs, which could be a client problem or a server\n * problem. Most errors are recoverable and the session will stay open, we\n * recommend to implementors to monitor and log error messages by default.\n */\nexport interface ErrorEvent {\n /**\n * Details of the error.\n */\n error: ErrorEvent.Error;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The event type, must be `error`.\n */\n type: 'error';\n}\n\nexport namespace ErrorEvent {\n /**\n * Details of the error.\n */\n export interface Error {\n /**\n * A human-readable error message.\n */\n message: string;\n\n /**\n * The type of error (e.g., \"invalid_request_error\", \"server_error\").\n */\n type: string;\n\n /**\n * Error code, if any.\n */\n code?: string | null;\n\n /**\n * The event_id of the client event that caused the error, if applicable.\n */\n event_id?: string | null;\n\n /**\n * Parameter related to the error, if any.\n */\n param?: string | null;\n }\n}\n\n/**\n * Send this event to append audio bytes to the input audio buffer. The audio\n * buffer is temporary storage you can write to and later commit. In Server VAD\n * mode, the audio buffer is used to detect speech and the server will decide when\n * to commit. When Server VAD is disabled, you must commit the audio buffer\n * manually.\n *\n * The client may choose how much audio to place in each event up to a maximum of\n * 15 MiB, for example streaming smaller chunks from the client may allow the VAD\n * to be more responsive. Unlike made other client events, the server will not send\n * a confirmation response to this event.\n */\nexport interface InputAudioBufferAppendEvent {\n /**\n * Base64-encoded audio bytes. This must be in the format specified by the\n * `input_audio_format` field in the session configuration.\n */\n audio: string;\n\n /**\n * The event type, must be `input_audio_buffer.append`.\n */\n type: 'input_audio_buffer.append';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\n/**\n * Send this event to clear the audio bytes in the buffer. The server will respond\n * with an `input_audio_buffer.cleared` event.\n */\nexport interface InputAudioBufferClearEvent {\n /**\n * The event type, must be `input_audio_buffer.clear`.\n */\n type: 'input_audio_buffer.clear';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\n/**\n * Returned when the input audio buffer is cleared by the client with a\n * `input_audio_buffer.clear` event.\n */\nexport interface InputAudioBufferClearedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The event type, must be `input_audio_buffer.cleared`.\n */\n type: 'input_audio_buffer.cleared';\n}\n\n/**\n * Send this event to commit the user input audio buffer, which will create a new\n * user message item in the conversation. This event will produce an error if the\n * input audio buffer is empty. When in Server VAD mode, the client does not need\n * to send this event, the server will commit the audio buffer automatically.\n *\n * Committing the input audio buffer will trigger input audio transcription (if\n * enabled in session configuration), but it will not create a response from the\n * model. The server will respond with an `input_audio_buffer.committed` event.\n */\nexport interface InputAudioBufferCommitEvent {\n /**\n * The event type, must be `input_audio_buffer.commit`.\n */\n type: 'input_audio_buffer.commit';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\n/**\n * Returned when an input audio buffer is committed, either by the client or\n * automatically in server VAD mode. The `item_id` property is the ID of the user\n * message item that will be created, thus a `conversation.item.created` event will\n * also be sent to the client.\n */\nexport interface InputAudioBufferCommittedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the user message item that will be created.\n */\n item_id: string;\n\n /**\n * The ID of the preceding item after which the new item will be inserted.\n */\n previous_item_id: string;\n\n /**\n * The event type, must be `input_audio_buffer.committed`.\n */\n type: 'input_audio_buffer.committed';\n}\n\n/**\n * Sent by the server when in `server_vad` mode to indicate that speech has been\n * detected in the audio buffer. This can happen any time audio is added to the\n * buffer (unless speech is already detected). The client may want to use this\n * event to interrupt audio playback or provide visual feedback to the user.\n *\n * The client should expect to receive a `input_audio_buffer.speech_stopped` event\n * when speech stops. The `item_id` property is the ID of the user message item\n * that will be created when speech stops and will also be included in the\n * `input_audio_buffer.speech_stopped` event (unless the client manually commits\n * the audio buffer during VAD activation).\n */\nexport interface InputAudioBufferSpeechStartedEvent {\n /**\n * Milliseconds from the start of all audio written to the buffer during the\n * session when speech was first detected. This will correspond to the beginning of\n * audio sent to the model, and thus includes the `prefix_padding_ms` configured in\n * the Session.\n */\n audio_start_ms: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the user message item that will be created when speech stops.\n */\n item_id: string;\n\n /**\n * The event type, must be `input_audio_buffer.speech_started`.\n */\n type: 'input_audio_buffer.speech_started';\n}\n\n/**\n * Returned in `server_vad` mode when the server detects the end of speech in the\n * audio buffer. The server will also send an `conversation.item.created` event\n * with the user message item that is created from the audio buffer.\n */\nexport interface InputAudioBufferSpeechStoppedEvent {\n /**\n * Milliseconds since the session started when speech stopped. This will correspond\n * to the end of audio sent to the model, and thus includes the\n * `min_silence_duration_ms` configured in the Session.\n */\n audio_end_ms: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the user message item that will be created.\n */\n item_id: string;\n\n /**\n * The event type, must be `input_audio_buffer.speech_stopped`.\n */\n type: 'input_audio_buffer.speech_stopped';\n}\n\n/**\n * Emitted at the beginning of a Response to indicate the updated rate limits. When\n * a Response is created some tokens will be \"reserved\" for the output tokens, the\n * rate limits shown here reflect that reservation, which is then adjusted\n * accordingly once the Response is completed.\n */\nexport interface RateLimitsUpdatedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * List of rate limit information.\n */\n rate_limits: Array<RateLimitsUpdatedEvent.RateLimit>;\n\n /**\n * The event type, must be `rate_limits.updated`.\n */\n type: 'rate_limits.updated';\n}\n\nexport namespace RateLimitsUpdatedEvent {\n export interface RateLimit {\n /**\n * The maximum allowed value for the rate limit.\n */\n limit?: number;\n\n /**\n * The name of the rate limit (`requests`, `tokens`).\n */\n name?: 'requests' | 'tokens';\n\n /**\n * The remaining value before the limit is reached.\n */\n remaining?: number;\n\n /**\n * Seconds until the rate limit resets.\n */\n reset_seconds?: number;\n }\n}\n\n/**\n * A realtime client event.\n */\nexport type RealtimeClientEvent =\n | ConversationItemCreateEvent\n | ConversationItemDeleteEvent\n | ConversationItemRetrieveEvent\n | ConversationItemTruncateEvent\n | InputAudioBufferAppendEvent\n | InputAudioBufferClearEvent\n | RealtimeClientEvent.OutputAudioBufferClear\n | InputAudioBufferCommitEvent\n | ResponseCancelEvent\n | ResponseCreateEvent\n | SessionUpdateEvent\n | TranscriptionSessionUpdate;\n\nexport namespace RealtimeClientEvent {\n /**\n * **WebRTC Only:** Emit to cut off the current audio response. This will trigger\n * the server to stop generating audio and emit a `output_audio_buffer.cleared`\n * event. This event should be preceded by a `response.cancel` client event to stop\n * the generation of the current response.\n * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n */\n export interface OutputAudioBufferClear {\n /**\n * The event type, must be `output_audio_buffer.clear`.\n */\n type: 'output_audio_buffer.clear';\n\n /**\n * The unique ID of the client event used for error handling.\n */\n event_id?: string;\n }\n}\n\n/**\n * The response resource.\n */\nexport interface RealtimeResponse {\n /**\n * The unique ID of the response.\n */\n id?: string;\n\n /**\n * Which conversation the response is added to, determined by the `conversation`\n * field in the `response.create` event. If `auto`, the response will be added to\n * the default conversation and the value of `conversation_id` will be an id like\n * `conv_1234`. If `none`, the response will not be added to any conversation and\n * the value of `conversation_id` will be `null`. If responses are being triggered\n * by server VAD, the response will be added to the default conversation, thus the\n * `conversation_id` will be an id like `conv_1234`.\n */\n conversation_id?: string;\n\n /**\n * Maximum number of output tokens for a single assistant response, inclusive of\n * tool calls, that was used in this response.\n */\n max_output_tokens?: number | 'inf';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The set of modalities the model used to respond. If there are multiple\n * modalities, the model will pick one, for example if `modalities` is\n * `[\"text\", \"audio\"]`, the model could be responding in either text or audio.\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * The object type, must be `realtime.response`.\n */\n object?: 'realtime.response';\n\n /**\n * The list of output items generated by the response.\n */\n output?: Array<ConversationItem>;\n\n /**\n * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n */\n output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * The final status of the response (`completed`, `cancelled`, `failed`, or\n * `incomplete`).\n */\n status?: 'completed' | 'cancelled' | 'failed' | 'incomplete';\n\n /**\n * Additional details about the status.\n */\n status_details?: RealtimeResponseStatus;\n\n /**\n * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n */\n temperature?: number;\n\n /**\n * Usage statistics for the Response, this will correspond to billing. A Realtime\n * API session will maintain a conversation context and append new Items to the\n * Conversation, thus output from previous turns (text and audio tokens) will\n * become the input for later turns.\n */\n usage?: RealtimeResponseUsage;\n\n /**\n * The voice the model used to respond. Current voice options are `alloy`, `ash`,\n * `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and\n * `verse`.\n */\n voice?:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n}\n\n/**\n * Additional details about the status.\n */\nexport interface RealtimeResponseStatus {\n /**\n * A description of the error that caused the response to fail, populated when the\n * `status` is `failed`.\n */\n error?: RealtimeResponseStatus.Error;\n\n /**\n * The reason the Response did not complete. For a `cancelled` Response, one of\n * `turn_detected` (the server VAD detected a new start of speech) or\n * `client_cancelled` (the client sent a cancel event). For an `incomplete`\n * Response, one of `max_output_tokens` or `content_filter` (the server-side safety\n * filter activated and cut off the response).\n */\n reason?: 'turn_detected' | 'client_cancelled' | 'max_output_tokens' | 'content_filter';\n\n /**\n * The type of error that caused the response to fail, corresponding with the\n * `status` field (`completed`, `cancelled`, `incomplete`, `failed`).\n */\n type?: 'completed' | 'cancelled' | 'incomplete' | 'failed';\n}\n\nexport namespace RealtimeResponseStatus {\n /**\n * A description of the error that caused the response to fail, populated when the\n * `status` is `failed`.\n */\n export interface Error {\n /**\n * Error code, if any.\n */\n code?: string;\n\n /**\n * The type of error.\n */\n type?: string;\n }\n}\n\n/**\n * Usage statistics for the Response, this will correspond to billing. A Realtime\n * API session will maintain a conversation context and append new Items to the\n * Conversation, thus output from previous turns (text and audio tokens) will\n * become the input for later turns.\n */\nexport interface RealtimeResponseUsage {\n /**\n * Details about the input tokens used in the Response.\n */\n input_token_details?: RealtimeResponseUsage.InputTokenDetails;\n\n /**\n * The number of input tokens used in the Response, including text and audio\n * tokens.\n */\n input_tokens?: number;\n\n /**\n * Details about the output tokens used in the Response.\n */\n output_token_details?: RealtimeResponseUsage.OutputTokenDetails;\n\n /**\n * The number of output tokens sent in the Response, including text and audio\n * tokens.\n */\n output_tokens?: number;\n\n /**\n * The total number of tokens in the Response including input and output text and\n * audio tokens.\n */\n total_tokens?: number;\n}\n\nexport namespace RealtimeResponseUsage {\n /**\n * Details about the input tokens used in the Response.\n */\n export interface InputTokenDetails {\n /**\n * The number of audio tokens used in the Response.\n */\n audio_tokens?: number;\n\n /**\n * The number of cached tokens used in the Response.\n */\n cached_tokens?: number;\n\n /**\n * The number of text tokens used in the Response.\n */\n text_tokens?: number;\n }\n\n /**\n * Details about the output tokens used in the Response.\n */\n export interface OutputTokenDetails {\n /**\n * The number of audio tokens used in the Response.\n */\n audio_tokens?: number;\n\n /**\n * The number of text tokens used in the Response.\n */\n text_tokens?: number;\n }\n}\n\n/**\n * A realtime server event.\n */\nexport type RealtimeServerEvent =\n | ConversationCreatedEvent\n | ConversationItemCreatedEvent\n | ConversationItemDeletedEvent\n | ConversationItemInputAudioTranscriptionCompletedEvent\n | ConversationItemInputAudioTranscriptionDeltaEvent\n | ConversationItemInputAudioTranscriptionFailedEvent\n | RealtimeServerEvent.ConversationItemRetrieved\n | ConversationItemTruncatedEvent\n | ErrorEvent\n | InputAudioBufferClearedEvent\n | InputAudioBufferCommittedEvent\n | InputAudioBufferSpeechStartedEvent\n | InputAudioBufferSpeechStoppedEvent\n | RateLimitsUpdatedEvent\n | ResponseAudioDeltaEvent\n | ResponseAudioDoneEvent\n | ResponseAudioTranscriptDeltaEvent\n | ResponseAudioTranscriptDoneEvent\n | ResponseContentPartAddedEvent\n | ResponseContentPartDoneEvent\n | ResponseCreatedEvent\n | ResponseDoneEvent\n | ResponseFunctionCallArgumentsDeltaEvent\n | ResponseFunctionCallArgumentsDoneEvent\n | ResponseOutputItemAddedEvent\n | ResponseOutputItemDoneEvent\n | ResponseTextDeltaEvent\n | ResponseTextDoneEvent\n | SessionCreatedEvent\n | SessionUpdatedEvent\n | TranscriptionSessionUpdatedEvent\n | RealtimeServerEvent.OutputAudioBufferStarted\n | RealtimeServerEvent.OutputAudioBufferStopped\n | RealtimeServerEvent.OutputAudioBufferCleared;\n\nexport namespace RealtimeServerEvent {\n /**\n * Returned when a conversation item is retrieved with\n * `conversation.item.retrieve`.\n */\n export interface ConversationItemRetrieved {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The item to add to the conversation.\n */\n item: RealtimeAPI.ConversationItem;\n\n /**\n * The event type, must be `conversation.item.retrieved`.\n */\n type: 'conversation.item.retrieved';\n }\n\n /**\n * **WebRTC Only:** Emitted when the server begins streaming audio to the client.\n * This event is emitted after an audio content part has been added\n * (`response.content_part.added`) to the response.\n * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n */\n export interface OutputAudioBufferStarted {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The unique ID of the response that produced the audio.\n */\n response_id: string;\n\n /**\n * The event type, must be `output_audio_buffer.started`.\n */\n type: 'output_audio_buffer.started';\n }\n\n /**\n * **WebRTC Only:** Emitted when the output audio buffer has been completely\n * drained on the server, and no more audio is forthcoming. This event is emitted\n * after the full response data has been sent to the client (`response.done`).\n * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n */\n export interface OutputAudioBufferStopped {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The unique ID of the response that produced the audio.\n */\n response_id: string;\n\n /**\n * The event type, must be `output_audio_buffer.stopped`.\n */\n type: 'output_audio_buffer.stopped';\n }\n\n /**\n * **WebRTC Only:** Emitted when the output audio buffer is cleared. This happens\n * either in VAD mode when the user has interrupted\n * (`input_audio_buffer.speech_started`), or when the client has emitted the\n * `output_audio_buffer.clear` event to manually cut off the current audio\n * response.\n * [Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n */\n export interface OutputAudioBufferCleared {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The unique ID of the response that produced the audio.\n */\n response_id: string;\n\n /**\n * The event type, must be `output_audio_buffer.cleared`.\n */\n type: 'output_audio_buffer.cleared';\n }\n}\n\n/**\n * Returned when the model-generated audio is updated.\n */\nexport interface ResponseAudioDeltaEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * Base64-encoded audio data delta.\n */\n delta: string;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.audio.delta`.\n */\n type: 'response.audio.delta';\n}\n\n/**\n * Returned when the model-generated audio is done. Also emitted when a Response is\n * interrupted, incomplete, or cancelled.\n */\nexport interface ResponseAudioDoneEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.audio.done`.\n */\n type: 'response.audio.done';\n}\n\n/**\n * Returned when the model-generated transcription of audio output is updated.\n */\nexport interface ResponseAudioTranscriptDeltaEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The transcript delta.\n */\n delta: string;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.audio_transcript.delta`.\n */\n type: 'response.audio_transcript.delta';\n}\n\n/**\n * Returned when the model-generated transcription of audio output is done\n * streaming. Also emitted when a Response is interrupted, incomplete, or\n * cancelled.\n */\nexport interface ResponseAudioTranscriptDoneEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The final transcript of the audio.\n */\n transcript: string;\n\n /**\n * The event type, must be `response.audio_transcript.done`.\n */\n type: 'response.audio_transcript.done';\n}\n\n/**\n * Send this event to cancel an in-progress response. The server will respond with\n * a `response.cancelled` event or an error if there is no response to cancel.\n */\nexport interface ResponseCancelEvent {\n /**\n * The event type, must be `response.cancel`.\n */\n type: 'response.cancel';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n\n /**\n * A specific response ID to cancel - if not provided, will cancel an in-progress\n * response in the default conversation.\n */\n response_id?: string;\n}\n\n/**\n * Returned when a new content part is added to an assistant message item during\n * response generation.\n */\nexport interface ResponseContentPartAddedEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item to which the content part was added.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The content part that was added.\n */\n part: ResponseContentPartAddedEvent.Part;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.content_part.added`.\n */\n type: 'response.content_part.added';\n}\n\nexport namespace ResponseContentPartAddedEvent {\n /**\n * The content part that was added.\n */\n export interface Part {\n /**\n * Base64-encoded audio data (if type is \"audio\").\n */\n audio?: string;\n\n /**\n * The text content (if type is \"text\").\n */\n text?: string;\n\n /**\n * The transcript of the audio (if type is \"audio\").\n */\n transcript?: string;\n\n /**\n * The content type (\"text\", \"audio\").\n */\n type?: 'text' | 'audio';\n }\n}\n\n/**\n * Returned when a content part is done streaming in an assistant message item.\n * Also emitted when a Response is interrupted, incomplete, or cancelled.\n */\nexport interface ResponseContentPartDoneEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The content part that is done.\n */\n part: ResponseContentPartDoneEvent.Part;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.content_part.done`.\n */\n type: 'response.content_part.done';\n}\n\nexport namespace ResponseContentPartDoneEvent {\n /**\n * The content part that is done.\n */\n export interface Part {\n /**\n * Base64-encoded audio data (if type is \"audio\").\n */\n audio?: string;\n\n /**\n * The text content (if type is \"text\").\n */\n text?: string;\n\n /**\n * The transcript of the audio (if type is \"audio\").\n */\n transcript?: string;\n\n /**\n * The content type (\"text\", \"audio\").\n */\n type?: 'text' | 'audio';\n }\n}\n\n/**\n * This event instructs the server to create a Response, which means triggering\n * model inference. When in Server VAD mode, the server will create Responses\n * automatically.\n *\n * A Response will include at least one Item, and may have two, in which case the\n * second will be a function call. These Items will be appended to the conversation\n * history.\n *\n * The server will respond with a `response.created` event, events for Items and\n * content created, and finally a `response.done` event to indicate the Response is\n * complete.\n *\n * The `response.create` event includes inference configuration like\n * `instructions`, and `temperature`. These fields will override the Session's\n * configuration for this Response only.\n */\nexport interface ResponseCreateEvent {\n /**\n * The event type, must be `response.create`.\n */\n type: 'response.create';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n\n /**\n * Create a new Realtime response with these parameters\n */\n response?: ResponseCreateEvent.Response;\n}\n\nexport namespace ResponseCreateEvent {\n /**\n * Create a new Realtime response with these parameters\n */\n export interface Response {\n /**\n * Controls which conversation the response is added to. Currently supports `auto`\n * and `none`, with `auto` as the default value. The `auto` value means that the\n * contents of the response will be added to the default conversation. Set this to\n * `none` to create an out-of-band response which will not add items to default\n * conversation.\n */\n conversation?: (string & {}) | 'auto' | 'none';\n\n /**\n * Input items to include in the prompt for the model. Using this field creates a\n * new context for this Response instead of using the default conversation. An\n * empty array `[]` will clear the context for this Response. Note that this can\n * include references to items from the default conversation.\n */\n input?: Array<RealtimeAPI.ConversationItemWithReference>;\n\n /**\n * The default system instructions (i.e. system message) prepended to model calls.\n * This field allows the client to guide the model on desired responses. The model\n * can be instructed on response content and format, (e.g. \"be extremely succinct\",\n * \"act friendly\", \"here are examples of good responses\") and on audio behavior\n * (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The\n * instructions are not guaranteed to be followed by the model, but they provide\n * guidance to the model on the desired behavior.\n *\n * Note that the server sets default instructions which will be used if this field\n * is not set and are visible in the `session.created` event at the start of the\n * session.\n */\n instructions?: string;\n\n /**\n * Maximum number of output tokens for a single assistant response, inclusive of\n * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or\n * `inf` for the maximum available tokens for a given model. Defaults to `inf`.\n */\n max_response_output_tokens?: number | 'inf';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n */\n output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n */\n temperature?: number;\n\n /**\n * How the model chooses tools. Options are `auto`, `none`, `required`, or specify\n * a function, like `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}`.\n */\n tool_choice?: string;\n\n /**\n * Tools (functions) available to the model.\n */\n tools?: Array<Response.Tool>;\n\n /**\n * The voice the model uses to respond. Voice cannot be changed during the session\n * once the model has responded with audio at least once. Current voice options are\n * `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`,\n * `shimmer`, and `verse`.\n */\n voice?:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n }\n\n export namespace Response {\n export interface Tool {\n /**\n * The description of the function, including guidance on when and how to call it,\n * and guidance about what to tell the user when calling (if anything).\n */\n description?: string;\n\n /**\n * The name of the function.\n */\n name?: string;\n\n /**\n * Parameters of the function in JSON Schema.\n */\n parameters?: unknown;\n\n /**\n * The type of the tool, i.e. `function`.\n */\n type?: 'function';\n }\n }\n}\n\n/**\n * Returned when a new Response is created. The first event of response creation,\n * where the response is in an initial state of `in_progress`.\n */\nexport interface ResponseCreatedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The response resource.\n */\n response: RealtimeResponse;\n\n /**\n * The event type, must be `response.created`.\n */\n type: 'response.created';\n}\n\n/**\n * Returned when a Response is done streaming. Always emitted, no matter the final\n * state. The Response object included in the `response.done` event will include\n * all output Items in the Response but will omit the raw audio data.\n */\nexport interface ResponseDoneEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The response resource.\n */\n response: RealtimeResponse;\n\n /**\n * The event type, must be `response.done`.\n */\n type: 'response.done';\n}\n\n/**\n * Returned when the model-generated function call arguments are updated.\n */\nexport interface ResponseFunctionCallArgumentsDeltaEvent {\n /**\n * The ID of the function call.\n */\n call_id: string;\n\n /**\n * The arguments delta as a JSON string.\n */\n delta: string;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the function call item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.function_call_arguments.delta`.\n */\n type: 'response.function_call_arguments.delta';\n}\n\n/**\n * Returned when the model-generated function call arguments are done streaming.\n * Also emitted when a Response is interrupted, incomplete, or cancelled.\n */\nexport interface ResponseFunctionCallArgumentsDoneEvent {\n /**\n * The final arguments as a JSON string.\n */\n arguments: string;\n\n /**\n * The ID of the function call.\n */\n call_id: string;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the function call item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.function_call_arguments.done`.\n */\n type: 'response.function_call_arguments.done';\n}\n\n/**\n * Returned when a new Item is created during Response generation.\n */\nexport interface ResponseOutputItemAddedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The item to add to the conversation.\n */\n item: ConversationItem;\n\n /**\n * The index of the output item in the Response.\n */\n output_index: number;\n\n /**\n * The ID of the Response to which the item belongs.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.output_item.added`.\n */\n type: 'response.output_item.added';\n}\n\n/**\n * Returned when an Item is done streaming. Also emitted when a Response is\n * interrupted, incomplete, or cancelled.\n */\nexport interface ResponseOutputItemDoneEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The item to add to the conversation.\n */\n item: ConversationItem;\n\n /**\n * The index of the output item in the Response.\n */\n output_index: number;\n\n /**\n * The ID of the Response to which the item belongs.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.output_item.done`.\n */\n type: 'response.output_item.done';\n}\n\n/**\n * Returned when the text value of a \"text\" content part is updated.\n */\nexport interface ResponseTextDeltaEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The text delta.\n */\n delta: string;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The event type, must be `response.text.delta`.\n */\n type: 'response.text.delta';\n}\n\n/**\n * Returned when the text value of a \"text\" content part is done streaming. Also\n * emitted when a Response is interrupted, incomplete, or cancelled.\n */\nexport interface ResponseTextDoneEvent {\n /**\n * The index of the content part in the item's content array.\n */\n content_index: number;\n\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response.\n */\n output_index: number;\n\n /**\n * The ID of the response.\n */\n response_id: string;\n\n /**\n * The final text content.\n */\n text: string;\n\n /**\n * The event type, must be `response.text.done`.\n */\n type: 'response.text.done';\n}\n\n/**\n * Returned when a Session is created. Emitted automatically when a new connection\n * is established as the first server event. This event will contain the default\n * Session configuration.\n */\nexport interface SessionCreatedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * Realtime session object configuration.\n */\n session: SessionsAPI.Session;\n\n /**\n * The event type, must be `session.created`.\n */\n type: 'session.created';\n}\n\n/**\n * Send this event to update the session’s default configuration. The client may\n * send this event at any time to update any field, except for `voice`. However,\n * note that once a session has been initialized with a particular `model`, it\n * can’t be changed to another model using `session.update`.\n *\n * When the server receives a `session.update`, it will respond with a\n * `session.updated` event showing the full, effective configuration. Only the\n * fields that are present are updated. To clear a field like `instructions`, pass\n * an empty string.\n */\nexport interface SessionUpdateEvent {\n /**\n * Realtime session object configuration.\n */\n session: SessionUpdateEvent.Session;\n\n /**\n * The event type, must be `session.update`.\n */\n type: 'session.update';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\nexport namespace SessionUpdateEvent {\n /**\n * Realtime session object configuration.\n */\n export interface Session {\n /**\n * Configuration options for the generated client secret.\n */\n client_secret?: Session.ClientSecret;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For\n * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel\n * (mono), and little-endian byte order.\n */\n input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n input_audio_noise_reduction?: Session.InputAudioNoiseReduction;\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through\n * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)\n * and should be treated as guidance of input audio content rather than precisely\n * what the model heard. The client can optionally set the language and prompt for\n * transcription, these offer additional guidance to the transcription service.\n */\n input_audio_transcription?: Session.InputAudioTranscription;\n\n /**\n * The default system instructions (i.e. system message) prepended to model calls.\n * This field allows the client to guide the model on desired responses. The model\n * can be instructed on response content and format, (e.g. \"be extremely succinct\",\n * \"act friendly\", \"here are examples of good responses\") and on audio behavior\n * (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The\n * instructions are not guaranteed to be followed by the model, but they provide\n * guidance to the model on the desired behavior.\n *\n * Note that the server sets default instructions which will be used if this field\n * is not set and are visible in the `session.created` event at the start of the\n * session.\n */\n instructions?: string;\n\n /**\n * Maximum number of output tokens for a single assistant response, inclusive of\n * tool calls. Provide an integer between 1 and 4096 to limit output tokens, or\n * `inf` for the maximum available tokens for a given model. Defaults to `inf`.\n */\n max_response_output_tokens?: number | 'inf';\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * The Realtime model used for this session.\n */\n model?:\n | 'gpt-4o-realtime-preview'\n | 'gpt-4o-realtime-preview-2024-10-01'\n | 'gpt-4o-realtime-preview-2024-12-17'\n | 'gpt-4o-mini-realtime-preview'\n | 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n /**\n * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n * For `pcm16`, output audio is sampled at a rate of 24kHz.\n */\n output_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a\n * temperature of 0.8 is highly recommended for best performance.\n */\n temperature?: number;\n\n /**\n * How the model chooses tools. Options are `auto`, `none`, `required`, or specify\n * a function.\n */\n tool_choice?: string;\n\n /**\n * Tools (functions) available to the model.\n */\n tools?: Array<Session.Tool>;\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n turn_detection?: Session.TurnDetection;\n\n /**\n * The voice the model uses to respond. Voice cannot be changed during the session\n * once the model has responded with audio at least once. Current voice options are\n * `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`,\n * `shimmer`, and `verse`.\n */\n voice?:\n | (string & {})\n | 'alloy'\n | 'ash'\n | 'ballad'\n | 'coral'\n | 'echo'\n | 'fable'\n | 'onyx'\n | 'nova'\n | 'sage'\n | 'shimmer'\n | 'verse';\n }\n\n export namespace Session {\n /**\n * Configuration options for the generated client secret.\n */\n export interface ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n expires_at?: ClientSecret.ExpiresAt;\n }\n\n export namespace ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n export interface ExpiresAt {\n /**\n * The anchor point for the ephemeral token expiration. Only `created_at` is\n * currently supported.\n */\n anchor?: 'created_at';\n\n /**\n * The number of seconds from the anchor point to the expiration. Select a value\n * between `10` and `7200`.\n */\n seconds?: number;\n }\n }\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n export interface InputAudioNoiseReduction {\n /**\n * Type of noise reduction. `near_field` is for close-talking microphones such as\n * headphones, `far_field` is for far-field microphones such as laptop or\n * conference room microphones.\n */\n type?: 'near_field' | 'far_field';\n }\n\n /**\n * Configuration for input audio transcription, defaults to off and can be set to\n * `null` to turn off once on. Input audio transcription is not native to the\n * model, since the model consumes audio directly. Transcription runs\n * asynchronously through\n * [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription)\n * and should be treated as guidance of input audio content rather than precisely\n * what the model heard. The client can optionally set the language and prompt for\n * transcription, these offer additional guidance to the transcription service.\n */\n export interface InputAudioTranscription {\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * The model to use for transcription, current options are `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, and `whisper-1`.\n */\n model?: string;\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. For `whisper-1`, the\n * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\n * For `gpt-4o-transcribe` models, the prompt is a free text string, for example\n * \"expect words related to technology\".\n */\n prompt?: string;\n }\n\n export interface Tool {\n /**\n * The description of the function, including guidance on when and how to call it,\n * and guidance about what to tell the user when calling (if anything).\n */\n description?: string;\n\n /**\n * The name of the function.\n */\n name?: string;\n\n /**\n * Parameters of the function in JSON Schema.\n */\n parameters?: unknown;\n\n /**\n * The type of the tool, i.e. `function`.\n */\n type?: 'function';\n }\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n export interface TurnDetection {\n /**\n * Whether or not to automatically generate a response when a VAD stop event\n * occurs.\n */\n create_response?: boolean;\n\n /**\n * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low`\n * will wait longer for the user to continue speaking, `high` will respond more\n * quickly. `auto` is the default and is equivalent to `medium`.\n */\n eagerness?: 'low' | 'medium' | 'high' | 'auto';\n\n /**\n * Whether or not to automatically interrupt any ongoing response with output to\n * the default conversation (i.e. `conversation` of `auto`) when a VAD start event\n * occurs.\n */\n interrupt_response?: boolean;\n\n /**\n * Used only for `server_vad` mode. Amount of audio to include before the VAD\n * detected speech (in milliseconds). Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Duration of silence to detect speech stop (in\n * milliseconds). Defaults to 500ms. With shorter values the model will respond\n * more quickly, but may jump in on short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this\n * defaults to 0.5. A higher threshold will require louder audio to activate the\n * model, and thus might perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection.\n */\n type?: 'server_vad' | 'semantic_vad';\n }\n }\n}\n\n/**\n * Returned when a session is updated with a `session.update` event, unless there\n * is an error.\n */\nexport interface SessionUpdatedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * Realtime session object configuration.\n */\n session: SessionsAPI.Session;\n\n /**\n * The event type, must be `session.updated`.\n */\n type: 'session.updated';\n}\n\n/**\n * Send this event to update a transcription session.\n */\nexport interface TranscriptionSessionUpdate {\n /**\n * Realtime transcription session object configuration.\n */\n session: TranscriptionSessionUpdate.Session;\n\n /**\n * The event type, must be `transcription_session.update`.\n */\n type: 'transcription_session.update';\n\n /**\n * Optional client-generated ID used to identify this event.\n */\n event_id?: string;\n}\n\nexport namespace TranscriptionSessionUpdate {\n /**\n * Realtime transcription session object configuration.\n */\n export interface Session {\n /**\n * Configuration options for the generated client secret.\n */\n client_secret?: Session.ClientSecret;\n\n /**\n * The set of items to include in the transcription. Current available items are:\n *\n * - `item.input_audio_transcription.logprobs`\n */\n include?: Array<string>;\n\n /**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For\n * `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel\n * (mono), and little-endian byte order.\n */\n input_audio_format?: 'pcm16' | 'g711_ulaw' | 'g711_alaw';\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n input_audio_noise_reduction?: Session.InputAudioNoiseReduction;\n\n /**\n * Configuration for input audio transcription. The client can optionally set the\n * language and prompt for transcription, these offer additional guidance to the\n * transcription service.\n */\n input_audio_transcription?: Session.InputAudioTranscription;\n\n /**\n * The set of modalities the model can respond with. To disable audio, set this to\n * [\"text\"].\n */\n modalities?: Array<'text' | 'audio'>;\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n turn_detection?: Session.TurnDetection;\n }\n\n export namespace Session {\n /**\n * Configuration options for the generated client secret.\n */\n export interface ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n expires_at?: ClientSecret.ExpiresAt;\n }\n\n export namespace ClientSecret {\n /**\n * Configuration for the ephemeral token expiration.\n */\n export interface ExpiresAt {\n /**\n * The anchor point for the ephemeral token expiration. Only `created_at` is\n * currently supported.\n */\n anchor?: 'created_at';\n\n /**\n * The number of seconds from the anchor point to the expiration. Select a value\n * between `10` and `7200`.\n */\n seconds?: number;\n }\n }\n\n /**\n * Configuration for input audio noise reduction. This can be set to `null` to turn\n * off. Noise reduction filters audio added to the input audio buffer before it is\n * sent to VAD and the model. Filtering the audio can improve VAD and turn\n * detection accuracy (reducing false positives) and model performance by improving\n * perception of the input audio.\n */\n export interface InputAudioNoiseReduction {\n /**\n * Type of noise reduction. `near_field` is for close-talking microphones such as\n * headphones, `far_field` is for far-field microphones such as laptop or\n * conference room microphones.\n */\n type?: 'near_field' | 'far_field';\n }\n\n /**\n * Configuration for input audio transcription. The client can optionally set the\n * language and prompt for transcription, these offer additional guidance to the\n * transcription service.\n */\n export interface InputAudioTranscription {\n /**\n * The language of the input audio. Supplying the input language in\n * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)\n * format will improve accuracy and latency.\n */\n language?: string;\n\n /**\n * The model to use for transcription, current options are `gpt-4o-transcribe`,\n * `gpt-4o-mini-transcribe`, and `whisper-1`.\n */\n model?: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe' | 'whisper-1';\n\n /**\n * An optional text to guide the model's style or continue a previous audio\n * segment. For `whisper-1`, the\n * [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\n * For `gpt-4o-transcribe` models, the prompt is a free text string, for example\n * \"expect words related to technology\".\n */\n prompt?: string;\n }\n\n /**\n * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be\n * set to `null` to turn off, in which case the client must manually trigger model\n * response. Server VAD means that the model will detect the start and end of\n * speech based on audio volume and respond at the end of user speech. Semantic VAD\n * is more advanced and uses a turn detection model (in conjuction with VAD) to\n * semantically estimate whether the user has finished speaking, then dynamically\n * sets a timeout based on this probability. For example, if user audio trails off\n * with \"uhhm\", the model will score a low probability of turn end and wait longer\n * for the user to continue speaking. This can be useful for more natural\n * conversations, but may have a higher latency.\n */\n export interface TurnDetection {\n /**\n * Whether or not to automatically generate a response when a VAD stop event\n * occurs. Not available for transcription sessions.\n */\n create_response?: boolean;\n\n /**\n * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low`\n * will wait longer for the user to continue speaking, `high` will respond more\n * quickly. `auto` is the default and is equivalent to `medium`.\n */\n eagerness?: 'low' | 'medium' | 'high' | 'auto';\n\n /**\n * Whether or not to automatically interrupt any ongoing response with output to\n * the default conversation (i.e. `conversation` of `auto`) when a VAD start event\n * occurs. Not available for transcription sessions.\n */\n interrupt_response?: boolean;\n\n /**\n * Used only for `server_vad` mode. Amount of audio to include before the VAD\n * detected speech (in milliseconds). Defaults to 300ms.\n */\n prefix_padding_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Duration of silence to detect speech stop (in\n * milliseconds). Defaults to 500ms. With shorter values the model will respond\n * more quickly, but may jump in on short pauses from the user.\n */\n silence_duration_ms?: number;\n\n /**\n * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this\n * defaults to 0.5. A higher threshold will require louder audio to activate the\n * model, and thus might perform better in noisy environments.\n */\n threshold?: number;\n\n /**\n * Type of turn detection.\n */\n type?: 'server_vad' | 'semantic_vad';\n }\n }\n}\n\n/**\n * Returned when a transcription session is updated with a\n * `transcription_session.update` event, unless there is an error.\n */\nexport interface TranscriptionSessionUpdatedEvent {\n /**\n * The unique ID of the server event.\n */\n event_id: string;\n\n /**\n * A new Realtime transcription session configuration.\n *\n * When a session is created on the server via REST API, the session object also\n * contains an ephemeral key. Default TTL for keys is 10 minutes. This property is\n * not present when a session is updated via the WebSocket API.\n */\n session: TranscriptionSessionsAPI.TranscriptionSession;\n\n /**\n * The event type, must be `transcription_session.updated`.\n */\n type: 'transcription_session.updated';\n}\n\nRealtime.Sessions = Sessions;\nRealtime.TranscriptionSessions = TranscriptionSessions;\n\nexport declare namespace Realtime {\n export {\n type ConversationCreatedEvent as ConversationCreatedEvent,\n type ConversationItem as ConversationItem,\n type ConversationItemContent as ConversationItemContent,\n type ConversationItemCreateEvent as ConversationItemCreateEvent,\n type ConversationItemCreatedEvent as ConversationItemCreatedEvent,\n type ConversationItemDeleteEvent as ConversationItemDeleteEvent,\n type ConversationItemDeletedEvent as ConversationItemDeletedEvent,\n type ConversationItemInputAudioTranscriptionCompletedEvent as ConversationItemInputAudioTranscriptionCompletedEvent,\n type ConversationItemInputAudioTranscriptionDeltaEvent as ConversationItemInputAudioTranscriptionDeltaEvent,\n type ConversationItemInputAudioTranscriptionFailedEvent as ConversationItemInputAudioTranscriptionFailedEvent,\n type ConversationItemRetrieveEvent as ConversationItemRetrieveEvent,\n type ConversationItemTruncateEvent as ConversationItemTruncateEvent,\n type ConversationItemTruncatedEvent as ConversationItemTruncatedEvent,\n type ConversationItemWithReference as ConversationItemWithReference,\n type ErrorEvent as ErrorEvent,\n type InputAudioBufferAppendEvent as InputAudioBufferAppendEvent,\n type InputAudioBufferClearEvent as InputAudioBufferClearEvent,\n type InputAudioBufferClearedEvent as InputAudioBufferClearedEvent,\n type InputAudioBufferCommitEvent as InputAudioBufferCommitEvent,\n type InputAudioBufferCommittedEvent as InputAudioBufferCommittedEvent,\n type InputAudioBufferSpeechStartedEvent as InputAudioBufferSpeechStartedEvent,\n type InputAudioBufferSpeechStoppedEvent as InputAudioBufferSpeechStoppedEvent,\n type RateLimitsUpdatedEvent as RateLimitsUpdatedEvent,\n type RealtimeClientEvent as RealtimeClientEvent,\n type RealtimeResponse as RealtimeResponse,\n type RealtimeResponseStatus as RealtimeResponseStatus,\n type RealtimeResponseUsage as RealtimeResponseUsage,\n type RealtimeServerEvent as RealtimeServerEvent,\n type ResponseAudioDeltaEvent as ResponseAudioDeltaEvent,\n type ResponseAudioDoneEvent as ResponseAudioDoneEvent,\n type ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent,\n type ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent,\n type ResponseCancelEvent as ResponseCancelEvent,\n type ResponseContentPartAddedEvent as ResponseContentPartAddedEvent,\n type ResponseContentPartDoneEvent as ResponseContentPartDoneEvent,\n type ResponseCreateEvent as ResponseCreateEvent,\n type ResponseCreatedEvent as ResponseCreatedEvent,\n type ResponseDoneEvent as ResponseDoneEvent,\n type ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent,\n type ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent,\n type ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent,\n type ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent,\n type ResponseTextDeltaEvent as ResponseTextDeltaEvent,\n type ResponseTextDoneEvent as ResponseTextDoneEvent,\n type SessionCreatedEvent as SessionCreatedEvent,\n type SessionUpdateEvent as SessionUpdateEvent,\n type SessionUpdatedEvent as SessionUpdatedEvent,\n type TranscriptionSessionUpdate as TranscriptionSessionUpdate,\n type TranscriptionSessionUpdatedEvent as TranscriptionSessionUpdatedEvent,\n };\n\n export {\n Sessions as Sessions,\n type SessionsAPISession as Session,\n type SessionCreateResponse as SessionCreateResponse,\n type SessionCreateParams as SessionCreateParams,\n };\n\n export {\n TranscriptionSessions as TranscriptionSessions,\n type TranscriptionSession as TranscriptionSession,\n type TranscriptionSessionCreateParams as TranscriptionSessionCreateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport * as Shared from '../../shared';\nimport * as AssistantsAPI from '../assistants';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\n\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Messages extends APIResource {\n /**\n * Create a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n create(\n threadId: string,\n body: MessageCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Message> {\n return this._client.post(`/threads/${threadId}/messages`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Retrieve a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(threadId: string, messageId: string, options?: Core.RequestOptions): Core.APIPromise<Message> {\n return this._client.get(`/threads/${threadId}/messages/${messageId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Modifies a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n update(\n threadId: string,\n messageId: string,\n body: MessageUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Message> {\n return this._client.post(`/threads/${threadId}/messages/${messageId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Returns a list of messages for a given thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n list(\n threadId: string,\n query?: MessageListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<MessagesPage, Message>;\n list(threadId: string, options?: Core.RequestOptions): Core.PagePromise<MessagesPage, Message>;\n list(\n threadId: string,\n query: MessageListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<MessagesPage, Message> {\n if (isRequestOptions(query)) {\n return this.list(threadId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Deletes a message.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n del(threadId: string, messageId: string, options?: Core.RequestOptions): Core.APIPromise<MessageDeleted> {\n return this._client.delete(`/threads/${threadId}/messages/${messageId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n\nexport class MessagesPage extends CursorPage<Message> {}\n\n/**\n * A citation within the message that points to a specific quote from a specific\n * File associated with the assistant or the message. Generated when the assistant\n * uses the \"file_search\" tool to search files.\n */\nexport type Annotation = FileCitationAnnotation | FilePathAnnotation;\n\n/**\n * A citation within the message that points to a specific quote from a specific\n * File associated with the assistant or the message. Generated when the assistant\n * uses the \"file_search\" tool to search files.\n */\nexport type AnnotationDelta = FileCitationDeltaAnnotation | FilePathDeltaAnnotation;\n\n/**\n * A citation within the message that points to a specific quote from a specific\n * File associated with the assistant or the message. Generated when the assistant\n * uses the \"file_search\" tool to search files.\n */\nexport interface FileCitationAnnotation {\n end_index: number;\n\n file_citation: FileCitationAnnotation.FileCitation;\n\n start_index: number;\n\n /**\n * The text in the message content that needs to be replaced.\n */\n text: string;\n\n /**\n * Always `file_citation`.\n */\n type: 'file_citation';\n}\n\nexport namespace FileCitationAnnotation {\n export interface FileCitation {\n /**\n * The ID of the specific File the citation is from.\n */\n file_id: string;\n }\n}\n\n/**\n * A citation within the message that points to a specific quote from a specific\n * File associated with the assistant or the message. Generated when the assistant\n * uses the \"file_search\" tool to search files.\n */\nexport interface FileCitationDeltaAnnotation {\n /**\n * The index of the annotation in the text content part.\n */\n index: number;\n\n /**\n * Always `file_citation`.\n */\n type: 'file_citation';\n\n end_index?: number;\n\n file_citation?: FileCitationDeltaAnnotation.FileCitation;\n\n start_index?: number;\n\n /**\n * The text in the message content that needs to be replaced.\n */\n text?: string;\n}\n\nexport namespace FileCitationDeltaAnnotation {\n export interface FileCitation {\n /**\n * The ID of the specific File the citation is from.\n */\n file_id?: string;\n\n /**\n * The specific quote in the file.\n */\n quote?: string;\n }\n}\n\n/**\n * A URL for the file that's generated when the assistant used the\n * `code_interpreter` tool to generate a file.\n */\nexport interface FilePathAnnotation {\n end_index: number;\n\n file_path: FilePathAnnotation.FilePath;\n\n start_index: number;\n\n /**\n * The text in the message content that needs to be replaced.\n */\n text: string;\n\n /**\n * Always `file_path`.\n */\n type: 'file_path';\n}\n\nexport namespace FilePathAnnotation {\n export interface FilePath {\n /**\n * The ID of the file that was generated.\n */\n file_id: string;\n }\n}\n\n/**\n * A URL for the file that's generated when the assistant used the\n * `code_interpreter` tool to generate a file.\n */\nexport interface FilePathDeltaAnnotation {\n /**\n * The index of the annotation in the text content part.\n */\n index: number;\n\n /**\n * Always `file_path`.\n */\n type: 'file_path';\n\n end_index?: number;\n\n file_path?: FilePathDeltaAnnotation.FilePath;\n\n start_index?: number;\n\n /**\n * The text in the message content that needs to be replaced.\n */\n text?: string;\n}\n\nexport namespace FilePathDeltaAnnotation {\n export interface FilePath {\n /**\n * The ID of the file that was generated.\n */\n file_id?: string;\n }\n}\n\nexport interface ImageFile {\n /**\n * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image\n * in the message content. Set `purpose=\"vision\"` when uploading the File if you\n * need to later display the file content.\n */\n file_id: string;\n\n /**\n * Specifies the detail level of the image if specified by the user. `low` uses\n * fewer tokens, you can opt in to high resolution using `high`.\n */\n detail?: 'auto' | 'low' | 'high';\n}\n\n/**\n * References an image [File](https://platform.openai.com/docs/api-reference/files)\n * in the content of a message.\n */\nexport interface ImageFileContentBlock {\n image_file: ImageFile;\n\n /**\n * Always `image_file`.\n */\n type: 'image_file';\n}\n\nexport interface ImageFileDelta {\n /**\n * Specifies the detail level of the image if specified by the user. `low` uses\n * fewer tokens, you can opt in to high resolution using `high`.\n */\n detail?: 'auto' | 'low' | 'high';\n\n /**\n * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image\n * in the message content. Set `purpose=\"vision\"` when uploading the File if you\n * need to later display the file content.\n */\n file_id?: string;\n}\n\n/**\n * References an image [File](https://platform.openai.com/docs/api-reference/files)\n * in the content of a message.\n */\nexport interface ImageFileDeltaBlock {\n /**\n * The index of the content part in the message.\n */\n index: number;\n\n /**\n * Always `image_file`.\n */\n type: 'image_file';\n\n image_file?: ImageFileDelta;\n}\n\nexport interface ImageURL {\n /**\n * The external URL of the image, must be a supported image types: jpeg, jpg, png,\n * gif, webp.\n */\n url: string;\n\n /**\n * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in\n * to high resolution using `high`. Default value is `auto`\n */\n detail?: 'auto' | 'low' | 'high';\n}\n\n/**\n * References an image URL in the content of a message.\n */\nexport interface ImageURLContentBlock {\n image_url: ImageURL;\n\n /**\n * The type of the content part.\n */\n type: 'image_url';\n}\n\nexport interface ImageURLDelta {\n /**\n * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in\n * to high resolution using `high`.\n */\n detail?: 'auto' | 'low' | 'high';\n\n /**\n * The URL of the image, must be a supported image types: jpeg, jpg, png, gif,\n * webp.\n */\n url?: string;\n}\n\n/**\n * References an image URL in the content of a message.\n */\nexport interface ImageURLDeltaBlock {\n /**\n * The index of the content part in the message.\n */\n index: number;\n\n /**\n * Always `image_url`.\n */\n type: 'image_url';\n\n image_url?: ImageURLDelta;\n}\n\n/**\n * Represents a message within a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\nexport interface Message {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * If applicable, the ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) that\n * authored this message.\n */\n assistant_id: string | null;\n\n /**\n * A list of files attached to the message, and the tools they were added to.\n */\n attachments: Array<Message.Attachment> | null;\n\n /**\n * The Unix timestamp (in seconds) for when the message was completed.\n */\n completed_at: number | null;\n\n /**\n * The content of the message in array of text and/or images.\n */\n content: Array<MessageContent>;\n\n /**\n * The Unix timestamp (in seconds) for when the message was created.\n */\n created_at: number;\n\n /**\n * The Unix timestamp (in seconds) for when the message was marked as incomplete.\n */\n incomplete_at: number | null;\n\n /**\n * On an incomplete message, details about why the message is incomplete.\n */\n incomplete_details: Message.IncompleteDetails | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The object type, which is always `thread.message`.\n */\n object: 'thread.message';\n\n /**\n * The entity that produced the message. One of `user` or `assistant`.\n */\n role: 'user' | 'assistant';\n\n /**\n * The ID of the [run](https://platform.openai.com/docs/api-reference/runs)\n * associated with the creation of this message. Value is `null` when messages are\n * created manually using the create message or create thread endpoints.\n */\n run_id: string | null;\n\n /**\n * The status of the message, which can be either `in_progress`, `incomplete`, or\n * `completed`.\n */\n status: 'in_progress' | 'incomplete' | 'completed';\n\n /**\n * The [thread](https://platform.openai.com/docs/api-reference/threads) ID that\n * this message belongs to.\n */\n thread_id: string;\n}\n\nexport namespace Message {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | Attachment.AssistantToolsFileSearchTypeOnly>;\n }\n\n export namespace Attachment {\n export interface AssistantToolsFileSearchTypeOnly {\n /**\n * The type of tool being defined: `file_search`\n */\n type: 'file_search';\n }\n }\n\n /**\n * On an incomplete message, details about why the message is incomplete.\n */\n export interface IncompleteDetails {\n /**\n * The reason the message is incomplete.\n */\n reason: 'content_filter' | 'max_tokens' | 'run_cancelled' | 'run_expired' | 'run_failed';\n }\n}\n\n/**\n * References an image [File](https://platform.openai.com/docs/api-reference/files)\n * in the content of a message.\n */\nexport type MessageContent =\n | ImageFileContentBlock\n | ImageURLContentBlock\n | TextContentBlock\n | RefusalContentBlock;\n\n/**\n * References an image [File](https://platform.openai.com/docs/api-reference/files)\n * in the content of a message.\n */\nexport type MessageContentDelta =\n | ImageFileDeltaBlock\n | TextDeltaBlock\n | RefusalDeltaBlock\n | ImageURLDeltaBlock;\n\n/**\n * References an image [File](https://platform.openai.com/docs/api-reference/files)\n * in the content of a message.\n */\nexport type MessageContentPartParam = ImageFileContentBlock | ImageURLContentBlock | TextContentBlockParam;\n\nexport interface MessageDeleted {\n id: string;\n\n deleted: boolean;\n\n object: 'thread.message.deleted';\n}\n\n/**\n * The delta containing the fields that have changed on the Message.\n */\nexport interface MessageDelta {\n /**\n * The content of the message in array of text and/or images.\n */\n content?: Array<MessageContentDelta>;\n\n /**\n * The entity that produced the message. One of `user` or `assistant`.\n */\n role?: 'user' | 'assistant';\n}\n\n/**\n * Represents a message delta i.e. any changed fields on a message during\n * streaming.\n */\nexport interface MessageDeltaEvent {\n /**\n * The identifier of the message, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The delta containing the fields that have changed on the Message.\n */\n delta: MessageDelta;\n\n /**\n * The object type, which is always `thread.message.delta`.\n */\n object: 'thread.message.delta';\n}\n\n/**\n * The refusal content generated by the assistant.\n */\nexport interface RefusalContentBlock {\n refusal: string;\n\n /**\n * Always `refusal`.\n */\n type: 'refusal';\n}\n\n/**\n * The refusal content that is part of a message.\n */\nexport interface RefusalDeltaBlock {\n /**\n * The index of the refusal part in the message.\n */\n index: number;\n\n /**\n * Always `refusal`.\n */\n type: 'refusal';\n\n refusal?: string;\n}\n\nexport interface Text {\n annotations: Array<Annotation>;\n\n /**\n * The data that makes up the text.\n */\n value: string;\n}\n\n/**\n * The text content that is part of a message.\n */\nexport interface TextContentBlock {\n text: Text;\n\n /**\n * Always `text`.\n */\n type: 'text';\n}\n\n/**\n * The text content that is part of a message.\n */\nexport interface TextContentBlockParam {\n /**\n * Text content to be sent to the model\n */\n text: string;\n\n /**\n * Always `text`.\n */\n type: 'text';\n}\n\nexport interface TextDelta {\n annotations?: Array<AnnotationDelta>;\n\n /**\n * The data that makes up the text.\n */\n value?: string;\n}\n\n/**\n * The text content that is part of a message.\n */\nexport interface TextDeltaBlock {\n /**\n * The index of the content part in the message.\n */\n index: number;\n\n /**\n * Always `text`.\n */\n type: 'text';\n\n text?: TextDelta;\n}\n\nexport interface MessageCreateParams {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<MessageCreateParams.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n}\n\nexport namespace MessageCreateParams {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | Attachment.FileSearch>;\n }\n\n export namespace Attachment {\n export interface FileSearch {\n /**\n * The type of tool being defined: `file_search`\n */\n type: 'file_search';\n }\n }\n}\n\nexport interface MessageUpdateParams {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n}\n\nexport interface MessageListParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n\n /**\n * Filter messages by the run ID that generated them.\n */\n run_id?: string;\n}\n\nMessages.MessagesPage = MessagesPage;\n\nexport declare namespace Messages {\n export {\n type Annotation as Annotation,\n type AnnotationDelta as AnnotationDelta,\n type FileCitationAnnotation as FileCitationAnnotation,\n type FileCitationDeltaAnnotation as FileCitationDeltaAnnotation,\n type FilePathAnnotation as FilePathAnnotation,\n type FilePathDeltaAnnotation as FilePathDeltaAnnotation,\n type ImageFile as ImageFile,\n type ImageFileContentBlock as ImageFileContentBlock,\n type ImageFileDelta as ImageFileDelta,\n type ImageFileDeltaBlock as ImageFileDeltaBlock,\n type ImageURL as ImageURL,\n type ImageURLContentBlock as ImageURLContentBlock,\n type ImageURLDelta as ImageURLDelta,\n type ImageURLDeltaBlock as ImageURLDeltaBlock,\n type Message as Message,\n type MessageContent as MessageContent,\n type MessageContentDelta as MessageContentDelta,\n type MessageContentPartParam as MessageContentPartParam,\n type MessageDeleted as MessageDeleted,\n type MessageDelta as MessageDelta,\n type MessageDeltaEvent as MessageDeltaEvent,\n type RefusalContentBlock as RefusalContentBlock,\n type RefusalDeltaBlock as RefusalDeltaBlock,\n type Text as Text,\n type TextContentBlock as TextContentBlock,\n type TextContentBlockParam as TextContentBlockParam,\n type TextDelta as TextDelta,\n type TextDeltaBlock as TextDeltaBlock,\n MessagesPage as MessagesPage,\n type MessageCreateParams as MessageCreateParams,\n type MessageUpdateParams as MessageUpdateParams,\n type MessageListParams as MessageListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../../resource';\nimport { isRequestOptions } from '../../../../core';\nimport * as Core from '../../../../core';\nimport * as StepsAPI from './steps';\nimport * as Shared from '../../../shared';\nimport { CursorPage, type CursorPageParams } from '../../../../pagination';\n\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Steps extends APIResource {\n /**\n * Retrieves a run step.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(\n threadId: string,\n runId: string,\n stepId: string,\n query?: StepRetrieveParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<RunStep>;\n retrieve(\n threadId: string,\n runId: string,\n stepId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<RunStep>;\n retrieve(\n threadId: string,\n runId: string,\n stepId: string,\n query: StepRetrieveParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<RunStep> {\n if (isRequestOptions(query)) {\n return this.retrieve(threadId, runId, stepId, {}, query);\n }\n return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Returns a list of run steps belonging to a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n list(\n threadId: string,\n runId: string,\n query?: StepListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunStepsPage, RunStep>;\n list(\n threadId: string,\n runId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunStepsPage, RunStep>;\n list(\n threadId: string,\n runId: string,\n query: StepListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunStepsPage, RunStep> {\n if (isRequestOptions(query)) {\n return this.list(threadId, runId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n\nexport class RunStepsPage extends CursorPage<RunStep> {}\n\n/**\n * Text output from the Code Interpreter tool call as part of a run step.\n */\nexport interface CodeInterpreterLogs {\n /**\n * The index of the output in the outputs array.\n */\n index: number;\n\n /**\n * Always `logs`.\n */\n type: 'logs';\n\n /**\n * The text output from the Code Interpreter tool call.\n */\n logs?: string;\n}\n\nexport interface CodeInterpreterOutputImage {\n /**\n * The index of the output in the outputs array.\n */\n index: number;\n\n /**\n * Always `image`.\n */\n type: 'image';\n\n image?: CodeInterpreterOutputImage.Image;\n}\n\nexport namespace CodeInterpreterOutputImage {\n export interface Image {\n /**\n * The [file](https://platform.openai.com/docs/api-reference/files) ID of the\n * image.\n */\n file_id?: string;\n }\n}\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n */\nexport interface CodeInterpreterToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The Code Interpreter tool call definition.\n */\n code_interpreter: CodeInterpreterToolCall.CodeInterpreter;\n\n /**\n * The type of tool call. This is always going to be `code_interpreter` for this\n * type of tool call.\n */\n type: 'code_interpreter';\n}\n\nexport namespace CodeInterpreterToolCall {\n /**\n * The Code Interpreter tool call definition.\n */\n export interface CodeInterpreter {\n /**\n * The input to the Code Interpreter tool call.\n */\n input: string;\n\n /**\n * The outputs from the Code Interpreter tool call. Code Interpreter can output one\n * or more items, including text (`logs`) or images (`image`). Each of these are\n * represented by a different object type.\n */\n outputs: Array<CodeInterpreter.Logs | CodeInterpreter.Image>;\n }\n\n export namespace CodeInterpreter {\n /**\n * Text output from the Code Interpreter tool call as part of a run step.\n */\n export interface Logs {\n /**\n * The text output from the Code Interpreter tool call.\n */\n logs: string;\n\n /**\n * Always `logs`.\n */\n type: 'logs';\n }\n\n export interface Image {\n image: Image.Image;\n\n /**\n * Always `image`.\n */\n type: 'image';\n }\n\n export namespace Image {\n export interface Image {\n /**\n * The [file](https://platform.openai.com/docs/api-reference/files) ID of the\n * image.\n */\n file_id: string;\n }\n }\n }\n}\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n */\nexport interface CodeInterpreterToolCallDelta {\n /**\n * The index of the tool call in the tool calls array.\n */\n index: number;\n\n /**\n * The type of tool call. This is always going to be `code_interpreter` for this\n * type of tool call.\n */\n type: 'code_interpreter';\n\n /**\n * The ID of the tool call.\n */\n id?: string;\n\n /**\n * The Code Interpreter tool call definition.\n */\n code_interpreter?: CodeInterpreterToolCallDelta.CodeInterpreter;\n}\n\nexport namespace CodeInterpreterToolCallDelta {\n /**\n * The Code Interpreter tool call definition.\n */\n export interface CodeInterpreter {\n /**\n * The input to the Code Interpreter tool call.\n */\n input?: string;\n\n /**\n * The outputs from the Code Interpreter tool call. Code Interpreter can output one\n * or more items, including text (`logs`) or images (`image`). Each of these are\n * represented by a different object type.\n */\n outputs?: Array<StepsAPI.CodeInterpreterLogs | StepsAPI.CodeInterpreterOutputImage>;\n }\n}\n\nexport interface FileSearchToolCall {\n /**\n * The ID of the tool call object.\n */\n id: string;\n\n /**\n * For now, this is always going to be an empty object.\n */\n file_search: FileSearchToolCall.FileSearch;\n\n /**\n * The type of tool call. This is always going to be `file_search` for this type of\n * tool call.\n */\n type: 'file_search';\n}\n\nexport namespace FileSearchToolCall {\n /**\n * For now, this is always going to be an empty object.\n */\n export interface FileSearch {\n /**\n * The ranking options for the file search.\n */\n ranking_options?: FileSearch.RankingOptions;\n\n /**\n * The results of the file search.\n */\n results?: Array<FileSearch.Result>;\n }\n\n export namespace FileSearch {\n /**\n * The ranking options for the file search.\n */\n export interface RankingOptions {\n /**\n * The ranker used for the file search.\n */\n ranker: 'default_2024_08_21';\n\n /**\n * The score threshold for the file search. All values must be a floating point\n * number between 0 and 1.\n */\n score_threshold: number;\n }\n\n /**\n * A result instance of the file search.\n */\n export interface Result {\n /**\n * The ID of the file that result was found in.\n */\n file_id: string;\n\n /**\n * The name of the file that result was found in.\n */\n file_name: string;\n\n /**\n * The score of the result. All values must be a floating point number between 0\n * and 1.\n */\n score: number;\n\n /**\n * The content of the result that was found. The content is only included if\n * requested via the include query parameter.\n */\n content?: Array<Result.Content>;\n }\n\n export namespace Result {\n export interface Content {\n /**\n * The text content of the file.\n */\n text?: string;\n\n /**\n * The type of the content.\n */\n type?: 'text';\n }\n }\n }\n}\n\nexport interface FileSearchToolCallDelta {\n /**\n * For now, this is always going to be an empty object.\n */\n file_search: unknown;\n\n /**\n * The index of the tool call in the tool calls array.\n */\n index: number;\n\n /**\n * The type of tool call. This is always going to be `file_search` for this type of\n * tool call.\n */\n type: 'file_search';\n\n /**\n * The ID of the tool call object.\n */\n id?: string;\n}\n\nexport interface FunctionToolCall {\n /**\n * The ID of the tool call object.\n */\n id: string;\n\n /**\n * The definition of the function that was called.\n */\n function: FunctionToolCall.Function;\n\n /**\n * The type of tool call. This is always going to be `function` for this type of\n * tool call.\n */\n type: 'function';\n}\n\nexport namespace FunctionToolCall {\n /**\n * The definition of the function that was called.\n */\n export interface Function {\n /**\n * The arguments passed to the function.\n */\n arguments: string;\n\n /**\n * The name of the function.\n */\n name: string;\n\n /**\n * The output of the function. This will be `null` if the outputs have not been\n * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs)\n * yet.\n */\n output: string | null;\n }\n}\n\nexport interface FunctionToolCallDelta {\n /**\n * The index of the tool call in the tool calls array.\n */\n index: number;\n\n /**\n * The type of tool call. This is always going to be `function` for this type of\n * tool call.\n */\n type: 'function';\n\n /**\n * The ID of the tool call object.\n */\n id?: string;\n\n /**\n * The definition of the function that was called.\n */\n function?: FunctionToolCallDelta.Function;\n}\n\nexport namespace FunctionToolCallDelta {\n /**\n * The definition of the function that was called.\n */\n export interface Function {\n /**\n * The arguments passed to the function.\n */\n arguments?: string;\n\n /**\n * The name of the function.\n */\n name?: string;\n\n /**\n * The output of the function. This will be `null` if the outputs have not been\n * [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs)\n * yet.\n */\n output?: string | null;\n }\n}\n\n/**\n * Details of the message creation by the run step.\n */\nexport interface MessageCreationStepDetails {\n message_creation: MessageCreationStepDetails.MessageCreation;\n\n /**\n * Always `message_creation`.\n */\n type: 'message_creation';\n}\n\nexport namespace MessageCreationStepDetails {\n export interface MessageCreation {\n /**\n * The ID of the message that was created by this run step.\n */\n message_id: string;\n }\n}\n\n/**\n * Represents a step in execution of a run.\n */\nexport interface RunStep {\n /**\n * The identifier of the run step, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants)\n * associated with the run step.\n */\n assistant_id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the run step was cancelled.\n */\n cancelled_at: number | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run step completed.\n */\n completed_at: number | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run step was created.\n */\n created_at: number;\n\n /**\n * The Unix timestamp (in seconds) for when the run step expired. A step is\n * considered expired if the parent run is expired.\n */\n expired_at: number | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run step failed.\n */\n failed_at: number | null;\n\n /**\n * The last error associated with this run step. Will be `null` if there are no\n * errors.\n */\n last_error: RunStep.LastError | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The object type, which is always `thread.run.step`.\n */\n object: 'thread.run.step';\n\n /**\n * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that\n * this run step is a part of.\n */\n run_id: string;\n\n /**\n * The status of the run step, which can be either `in_progress`, `cancelled`,\n * `failed`, `completed`, or `expired`.\n */\n status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired';\n\n /**\n * The details of the run step.\n */\n step_details: MessageCreationStepDetails | ToolCallsStepDetails;\n\n /**\n * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads)\n * that was run.\n */\n thread_id: string;\n\n /**\n * The type of run step, which can be either `message_creation` or `tool_calls`.\n */\n type: 'message_creation' | 'tool_calls';\n\n /**\n * Usage statistics related to the run step. This value will be `null` while the\n * run step's status is `in_progress`.\n */\n usage: RunStep.Usage | null;\n}\n\nexport namespace RunStep {\n /**\n * The last error associated with this run step. Will be `null` if there are no\n * errors.\n */\n export interface LastError {\n /**\n * One of `server_error` or `rate_limit_exceeded`.\n */\n code: 'server_error' | 'rate_limit_exceeded';\n\n /**\n * A human-readable description of the error.\n */\n message: string;\n }\n\n /**\n * Usage statistics related to the run step. This value will be `null` while the\n * run step's status is `in_progress`.\n */\n export interface Usage {\n /**\n * Number of completion tokens used over the course of the run step.\n */\n completion_tokens: number;\n\n /**\n * Number of prompt tokens used over the course of the run step.\n */\n prompt_tokens: number;\n\n /**\n * Total number of tokens used (prompt + completion).\n */\n total_tokens: number;\n }\n}\n\n/**\n * The delta containing the fields that have changed on the run step.\n */\nexport interface RunStepDelta {\n /**\n * The details of the run step.\n */\n step_details?: RunStepDeltaMessageDelta | ToolCallDeltaObject;\n}\n\n/**\n * Represents a run step delta i.e. any changed fields on a run step during\n * streaming.\n */\nexport interface RunStepDeltaEvent {\n /**\n * The identifier of the run step, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The delta containing the fields that have changed on the run step.\n */\n delta: RunStepDelta;\n\n /**\n * The object type, which is always `thread.run.step.delta`.\n */\n object: 'thread.run.step.delta';\n}\n\n/**\n * Details of the message creation by the run step.\n */\nexport interface RunStepDeltaMessageDelta {\n /**\n * Always `message_creation`.\n */\n type: 'message_creation';\n\n message_creation?: RunStepDeltaMessageDelta.MessageCreation;\n}\n\nexport namespace RunStepDeltaMessageDelta {\n export interface MessageCreation {\n /**\n * The ID of the message that was created by this run step.\n */\n message_id?: string;\n }\n}\n\nexport type RunStepInclude = 'step_details.tool_calls[*].file_search.results[*].content';\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n */\nexport type ToolCall = CodeInterpreterToolCall | FileSearchToolCall | FunctionToolCall;\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n */\nexport type ToolCallDelta = CodeInterpreterToolCallDelta | FileSearchToolCallDelta | FunctionToolCallDelta;\n\n/**\n * Details of the tool call.\n */\nexport interface ToolCallDeltaObject {\n /**\n * Always `tool_calls`.\n */\n type: 'tool_calls';\n\n /**\n * An array of tool calls the run step was involved in. These can be associated\n * with one of three types of tools: `code_interpreter`, `file_search`, or\n * `function`.\n */\n tool_calls?: Array<ToolCallDelta>;\n}\n\n/**\n * Details of the tool call.\n */\nexport interface ToolCallsStepDetails {\n /**\n * An array of tool calls the run step was involved in. These can be associated\n * with one of three types of tools: `code_interpreter`, `file_search`, or\n * `function`.\n */\n tool_calls: Array<ToolCall>;\n\n /**\n * Always `tool_calls`.\n */\n type: 'tool_calls';\n}\n\nexport interface StepRetrieveParams {\n /**\n * A list of additional fields to include in the response. Currently the only\n * supported value is `step_details.tool_calls[*].file_search.results[*].content`\n * to fetch the file search result content.\n *\n * See the\n * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)\n * for more information.\n */\n include?: Array<RunStepInclude>;\n}\n\nexport interface StepListParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * A list of additional fields to include in the response. Currently the only\n * supported value is `step_details.tool_calls[*].file_search.results[*].content`\n * to fetch the file search result content.\n *\n * See the\n * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)\n * for more information.\n */\n include?: Array<RunStepInclude>;\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nSteps.RunStepsPage = RunStepsPage;\n\nexport declare namespace Steps {\n export {\n type CodeInterpreterLogs as CodeInterpreterLogs,\n type CodeInterpreterOutputImage as CodeInterpreterOutputImage,\n type CodeInterpreterToolCall as CodeInterpreterToolCall,\n type CodeInterpreterToolCallDelta as CodeInterpreterToolCallDelta,\n type FileSearchToolCall as FileSearchToolCall,\n type FileSearchToolCallDelta as FileSearchToolCallDelta,\n type FunctionToolCall as FunctionToolCall,\n type FunctionToolCallDelta as FunctionToolCallDelta,\n type MessageCreationStepDetails as MessageCreationStepDetails,\n type RunStep as RunStep,\n type RunStepDelta as RunStepDelta,\n type RunStepDeltaEvent as RunStepDeltaEvent,\n type RunStepDeltaMessageDelta as RunStepDeltaMessageDelta,\n type RunStepInclude as RunStepInclude,\n type ToolCall as ToolCall,\n type ToolCallDelta as ToolCallDelta,\n type ToolCallDeltaObject as ToolCallDeltaObject,\n type ToolCallsStepDetails as ToolCallsStepDetails,\n RunStepsPage as RunStepsPage,\n type StepRetrieveParams as StepRetrieveParams,\n type StepListParams as StepListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../../resource';\nimport { isRequestOptions } from '../../../../core';\nimport { APIPromise } from '../../../../core';\nimport * as Core from '../../../../core';\nimport { AssistantStream, RunCreateParamsBaseStream } from '../../../../lib/AssistantStream';\nimport { sleep } from '../../../../core';\nimport { RunSubmitToolOutputsParamsStream } from '../../../../lib/AssistantStream';\nimport * as RunsAPI from './runs';\nimport * as Shared from '../../../shared';\nimport * as AssistantsAPI from '../../assistants';\nimport * as MessagesAPI from '../messages';\nimport * as ThreadsAPI from '../threads';\nimport * as StepsAPI from './steps';\nimport {\n CodeInterpreterLogs,\n CodeInterpreterOutputImage,\n CodeInterpreterToolCall,\n CodeInterpreterToolCallDelta,\n FileSearchToolCall,\n FileSearchToolCallDelta,\n FunctionToolCall,\n FunctionToolCallDelta,\n MessageCreationStepDetails,\n RunStep,\n RunStepDelta,\n RunStepDeltaEvent,\n RunStepDeltaMessageDelta,\n RunStepInclude,\n RunStepsPage,\n StepListParams,\n StepRetrieveParams,\n Steps,\n ToolCall,\n ToolCallDelta,\n ToolCallDeltaObject,\n ToolCallsStepDetails,\n} from './steps';\nimport { CursorPage, type CursorPageParams } from '../../../../pagination';\nimport { Stream } from '../../../../streaming';\n\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Runs extends APIResource {\n steps: StepsAPI.Steps = new StepsAPI.Steps(this._client);\n\n /**\n * Create a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n create(\n threadId: string,\n params: RunCreateParamsNonStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Run>;\n create(\n threadId: string,\n params: RunCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>>;\n create(\n threadId: string,\n params: RunCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<AssistantsAPI.AssistantStreamEvent> | Run>;\n create(\n threadId: string,\n params: RunCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Run> | APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>> {\n const { include, ...body } = params;\n return this._client.post(`/threads/${threadId}/runs`, {\n query: { include },\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: params.stream ?? false,\n }) as APIPromise<Run> | APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>>;\n }\n\n /**\n * Retrieves a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise<Run> {\n return this._client.get(`/threads/${threadId}/runs/${runId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Modifies a run.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n update(\n threadId: string,\n runId: string,\n body: RunUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Run> {\n return this._client.post(`/threads/${threadId}/runs/${runId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Returns a list of runs belonging to a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n list(\n threadId: string,\n query?: RunListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunsPage, Run>;\n list(threadId: string, options?: Core.RequestOptions): Core.PagePromise<RunsPage, Run>;\n list(\n threadId: string,\n query: RunListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunsPage, Run> {\n if (isRequestOptions(query)) {\n return this.list(threadId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Cancels a run that is `in_progress`.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n cancel(threadId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise<Run> {\n return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * A helper to create a run an poll for a terminal state. More information on Run\n * lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndPoll(\n threadId: string,\n body: RunCreateParamsNonStreaming,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<Run> {\n const run = await this.create(threadId, body, options);\n return await this.poll(threadId, run.id, options);\n }\n\n /**\n * Create a Run stream\n *\n * @deprecated use `stream` instead\n */\n createAndStream(\n threadId: string,\n body: RunCreateParamsBaseStream,\n options?: Core.RequestOptions,\n ): AssistantStream {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n\n /**\n * A helper to poll a run status until it reaches a terminal state. More\n * information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async poll(\n threadId: string,\n runId: string,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<Run> {\n const headers: { [key: string]: string } = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n\n while (true) {\n const { data: run, response } = await this.retrieve(threadId, runId, {\n ...options,\n headers: { ...options?.headers, ...headers },\n }).withResponse();\n\n switch (run.status) {\n //If we are in any sort of intermediate state we poll\n case 'queued':\n case 'in_progress':\n case 'cancelling':\n let sleepInterval = 5000;\n\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n } else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n //We return the run in any terminal state.\n case 'requires_action':\n case 'incomplete':\n case 'cancelled':\n case 'completed':\n case 'failed':\n case 'expired':\n return run;\n }\n }\n }\n\n /**\n * Create a Run stream\n */\n stream(threadId: string, body: RunCreateParamsBaseStream, options?: Core.RequestOptions): AssistantStream {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n\n /**\n * When a run has the `status: \"requires_action\"` and `required_action.type` is\n * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the\n * tool calls once they're all completed. All outputs must be submitted in a single\n * request.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n submitToolOutputs(\n threadId: string,\n runId: string,\n body: RunSubmitToolOutputsParamsNonStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Run>;\n submitToolOutputs(\n threadId: string,\n runId: string,\n body: RunSubmitToolOutputsParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>>;\n submitToolOutputs(\n threadId: string,\n runId: string,\n body: RunSubmitToolOutputsParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<AssistantsAPI.AssistantStreamEvent> | Run>;\n submitToolOutputs(\n threadId: string,\n runId: string,\n body: RunSubmitToolOutputsParams,\n options?: Core.RequestOptions,\n ): APIPromise<Run> | APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>> {\n return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: body.stream ?? false,\n }) as APIPromise<Run> | APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>>;\n }\n\n /**\n * A helper to submit a tool output to a run and poll for a terminal run state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async submitToolOutputsAndPoll(\n threadId: string,\n runId: string,\n body: RunSubmitToolOutputsParamsNonStreaming,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<Run> {\n const run = await this.submitToolOutputs(threadId, runId, body, options);\n return await this.poll(threadId, run.id, options);\n }\n\n /**\n * Submit the tool outputs from a previous run and stream the run to a terminal\n * state. More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n submitToolOutputsStream(\n threadId: string,\n runId: string,\n body: RunSubmitToolOutputsParamsStream,\n options?: Core.RequestOptions,\n ): AssistantStream {\n return AssistantStream.createToolAssistantStream(\n threadId,\n runId,\n this._client.beta.threads.runs,\n body,\n options,\n );\n }\n}\n\nexport class RunsPage extends CursorPage<Run> {}\n\n/**\n * Tool call objects\n */\nexport interface RequiredActionFunctionToolCall {\n /**\n * The ID of the tool call. This ID must be referenced when you submit the tool\n * outputs in using the\n * [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs)\n * endpoint.\n */\n id: string;\n\n /**\n * The function definition.\n */\n function: RequiredActionFunctionToolCall.Function;\n\n /**\n * The type of tool call the output is required for. For now, this is always\n * `function`.\n */\n type: 'function';\n}\n\nexport namespace RequiredActionFunctionToolCall {\n /**\n * The function definition.\n */\n export interface Function {\n /**\n * The arguments that the model expects you to pass to the function.\n */\n arguments: string;\n\n /**\n * The name of the function.\n */\n name: string;\n }\n}\n\n/**\n * Represents an execution run on a\n * [thread](https://platform.openai.com/docs/api-reference/threads).\n */\nexport interface Run {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for\n * execution of this run.\n */\n assistant_id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the run was cancelled.\n */\n cancelled_at: number | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run was completed.\n */\n completed_at: number | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run was created.\n */\n created_at: number;\n\n /**\n * The Unix timestamp (in seconds) for when the run will expire.\n */\n expires_at: number | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run failed.\n */\n failed_at: number | null;\n\n /**\n * Details on why the run is incomplete. Will be `null` if the run is not\n * incomplete.\n */\n incomplete_details: Run.IncompleteDetails | null;\n\n /**\n * The instructions that the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for\n * this run.\n */\n instructions: string;\n\n /**\n * The last error associated with this run. Will be `null` if there are no errors.\n */\n last_error: Run.LastError | null;\n\n /**\n * The maximum number of completion tokens specified to have been used over the\n * course of the run.\n */\n max_completion_tokens: number | null;\n\n /**\n * The maximum number of prompt tokens specified to have been used over the course\n * of the run.\n */\n max_prompt_tokens: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The model that the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for\n * this run.\n */\n model: string;\n\n /**\n * The object type, which is always `thread.run`.\n */\n object: 'thread.run';\n\n /**\n * Whether to enable\n * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling)\n * during tool use.\n */\n parallel_tool_calls: boolean;\n\n /**\n * Details on the action required to continue the run. Will be `null` if no action\n * is required.\n */\n required_action: Run.RequiredAction | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * The Unix timestamp (in seconds) for when the run was started.\n */\n started_at: number | null;\n\n /**\n * The status of the run, which can be either `queued`, `in_progress`,\n * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`,\n * `incomplete`, or `expired`.\n */\n status: RunStatus;\n\n /**\n * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads)\n * that was executed on as a part of this run.\n */\n thread_id: string;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice: ThreadsAPI.AssistantToolChoiceOption | null;\n\n /**\n * The list of tools that the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) used for\n * this run.\n */\n tools: Array<AssistantsAPI.AssistantTool>;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy: Run.TruncationStrategy | null;\n\n /**\n * Usage statistics related to the run. This value will be `null` if the run is not\n * in a terminal state (i.e. `in_progress`, `queued`, etc.).\n */\n usage: Run.Usage | null;\n\n /**\n * The sampling temperature used for this run. If not set, defaults to 1.\n */\n temperature?: number | null;\n\n /**\n * The nucleus sampling value used for this run. If not set, defaults to 1.\n */\n top_p?: number | null;\n}\n\nexport namespace Run {\n /**\n * Details on why the run is incomplete. Will be `null` if the run is not\n * incomplete.\n */\n export interface IncompleteDetails {\n /**\n * The reason why the run is incomplete. This will point to which specific token\n * limit was reached over the course of the run.\n */\n reason?: 'max_completion_tokens' | 'max_prompt_tokens';\n }\n\n /**\n * The last error associated with this run. Will be `null` if there are no errors.\n */\n export interface LastError {\n /**\n * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.\n */\n code: 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt';\n\n /**\n * A human-readable description of the error.\n */\n message: string;\n }\n\n /**\n * Details on the action required to continue the run. Will be `null` if no action\n * is required.\n */\n export interface RequiredAction {\n /**\n * Details on the tool outputs needed for this run to continue.\n */\n submit_tool_outputs: RequiredAction.SubmitToolOutputs;\n\n /**\n * For now, this is always `submit_tool_outputs`.\n */\n type: 'submit_tool_outputs';\n }\n\n export namespace RequiredAction {\n /**\n * Details on the tool outputs needed for this run to continue.\n */\n export interface SubmitToolOutputs {\n /**\n * A list of the relevant tool calls.\n */\n tool_calls: Array<RunsAPI.RequiredActionFunctionToolCall>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n\n /**\n * Usage statistics related to the run. This value will be `null` if the run is not\n * in a terminal state (i.e. `in_progress`, `queued`, etc.).\n */\n export interface Usage {\n /**\n * Number of completion tokens used over the course of the run.\n */\n completion_tokens: number;\n\n /**\n * Number of prompt tokens used over the course of the run.\n */\n prompt_tokens: number;\n\n /**\n * Total number of tokens used (prompt + completion).\n */\n total_tokens: number;\n }\n}\n\n/**\n * The status of the run, which can be either `queued`, `in_progress`,\n * `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`,\n * `incomplete`, or `expired`.\n */\nexport type RunStatus =\n | 'queued'\n | 'in_progress'\n | 'requires_action'\n | 'cancelling'\n | 'cancelled'\n | 'failed'\n | 'completed'\n | 'incomplete'\n | 'expired';\n\nexport type RunCreateParams = RunCreateParamsNonStreaming | RunCreateParamsStreaming;\n\nexport interface RunCreateParamsBase {\n /**\n * Body param: The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Query param: A list of additional fields to include in the response. Currently\n * the only supported value is\n * `step_details.tool_calls[*].file_search.results[*].content` to fetch the file\n * search result content.\n *\n * See the\n * [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)\n * for more information.\n */\n include?: Array<StepsAPI.RunStepInclude>;\n\n /**\n * Body param: Appends additional instructions at the end of the instructions for\n * the run. This is useful for modifying the behavior on a per-run basis without\n * overriding other instructions.\n */\n additional_instructions?: string | null;\n\n /**\n * Body param: Adds additional messages to the thread before creating the run.\n */\n additional_messages?: Array<RunCreateParams.AdditionalMessage> | null;\n\n /**\n * Body param: Overrides the\n * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant)\n * of the assistant. This is useful for modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * Body param: The maximum number of completion tokens that may be used over the\n * course of the run. The run will make a best effort to use only the number of\n * completion tokens specified, across multiple turns of the run. If the run\n * exceeds the number of completion tokens specified, the run will end with status\n * `incomplete`. See `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * Body param: The maximum number of prompt tokens that may be used over the course\n * of the run. The run will make a best effort to use only the number of prompt\n * tokens specified, across multiple turns of the run. If the run exceeds the\n * number of prompt tokens specified, the run will end with status `incomplete`.\n * See `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Body param: Set of 16 key-value pairs that can be attached to an object. This\n * can be useful for storing additional information about the object in a\n * structured format, and querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * Body param: The ID of the\n * [Model](https://platform.openai.com/docs/api-reference/models) to be used to\n * execute this run. If a value is provided here, it will override the model\n * associated with the assistant. If not, the model associated with the assistant\n * will be used.\n */\n model?: (string & {}) | Shared.ChatModel | null;\n\n /**\n * Body param: Whether to enable\n * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling)\n * during tool use.\n */\n parallel_tool_calls?: boolean;\n\n /**\n * Body param: **o-series models only**\n *\n * Constrains effort on reasoning for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently\n * supported values are `low`, `medium`, and `high`. Reducing reasoning effort can\n * result in faster responses and fewer tokens used on reasoning in a response.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Body param: Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * Body param: If `true`, returns a stream of events that happen during the Run as\n * server-sent events, terminating when the Run enters a terminal state with a\n * `data: [DONE]` message.\n */\n stream?: boolean | null;\n\n /**\n * Body param: What sampling temperature to use, between 0 and 2. Higher values\n * like 0.8 will make the output more random, while lower values like 0.2 will make\n * it more focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * Body param: Controls which (if any) tool is called by the model. `none` means\n * the model will not call any tools and instead generates a message. `auto` is the\n * default value and means the model can pick between generating a message or\n * calling one or more tools. `required` means the model must call one or more\n * tools before responding to the user. Specifying a particular tool like\n * `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null;\n\n /**\n * Body param: Override the tools the assistant can use for this run. This is\n * useful for modifying the behavior on a per-run basis.\n */\n tools?: Array<AssistantsAPI.AssistantTool> | null;\n\n /**\n * Body param: An alternative to sampling with temperature, called nucleus\n * sampling, where the model considers the results of the tokens with top_p\n * probability mass. So 0.1 means only the tokens comprising the top 10%\n * probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Body param: Controls for how a thread will be truncated prior to the run. Use\n * this to control the intial context window of the run.\n */\n truncation_strategy?: RunCreateParams.TruncationStrategy | null;\n}\n\nexport namespace RunCreateParams {\n export interface AdditionalMessage {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<AdditionalMessage.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n export namespace AdditionalMessage {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | Attachment.FileSearch>;\n }\n\n export namespace Attachment {\n export interface FileSearch {\n /**\n * The type of tool being defined: `file_search`\n */\n type: 'file_search';\n }\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n\n export type RunCreateParamsNonStreaming = RunsAPI.RunCreateParamsNonStreaming;\n export type RunCreateParamsStreaming = RunsAPI.RunCreateParamsStreaming;\n}\n\nexport interface RunCreateParamsNonStreaming extends RunCreateParamsBase {\n /**\n * Body param: If `true`, returns a stream of events that happen during the Run as\n * server-sent events, terminating when the Run enters a terminal state with a\n * `data: [DONE]` message.\n */\n stream?: false | null;\n}\n\nexport interface RunCreateParamsStreaming extends RunCreateParamsBase {\n /**\n * Body param: If `true`, returns a stream of events that happen during the Run as\n * server-sent events, terminating when the Run enters a terminal state with a\n * `data: [DONE]` message.\n */\n stream: true;\n}\n\nexport interface RunUpdateParams {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n}\n\nexport interface RunListParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nexport interface RunCreateAndPollParams {\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Appends additional instructions at the end of the instructions for the run. This\n * is useful for modifying the behavior on a per-run basis without overriding other\n * instructions.\n */\n additional_instructions?: string | null;\n\n /**\n * Adds additional messages to the thread before creating the run.\n */\n additional_messages?: Array<RunCreateAndPollParams.AdditionalMessage> | null;\n\n /**\n * Overrides the\n * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant)\n * of the assistant. This is useful for modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * The maximum number of completion tokens that may be used over the course of the\n * run. The run will make a best effort to use only the number of completion tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * completion tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * The maximum number of prompt tokens that may be used over the course of the run.\n * The run will make a best effort to use only the number of prompt tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * prompt tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to\n * be used to execute this run. If a value is provided here, it will override the\n * model associated with the assistant. If not, the model associated with the\n * assistant will be used.\n */\n model?:\n | (string & {})\n | 'gpt-4o'\n | 'gpt-4o-2024-05-13'\n | 'gpt-4-turbo'\n | 'gpt-4-turbo-2024-04-09'\n | 'gpt-4-0125-preview'\n | 'gpt-4-turbo-preview'\n | 'gpt-4-1106-preview'\n | 'gpt-4-vision-preview'\n | 'gpt-4'\n | 'gpt-4-0314'\n | 'gpt-4-0613'\n | 'gpt-4-32k'\n | 'gpt-4-32k-0314'\n | 'gpt-4-32k-0613'\n | 'gpt-3.5-turbo'\n | 'gpt-3.5-turbo-16k'\n | 'gpt-3.5-turbo-0613'\n | 'gpt-3.5-turbo-1106'\n | 'gpt-3.5-turbo-0125'\n | 'gpt-3.5-turbo-16k-0613'\n | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models/gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which guarantees the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null;\n\n /**\n * Override the tools the assistant can use for this run. This is useful for\n * modifying the behavior on a per-run basis.\n */\n tools?: Array<AssistantsAPI.AssistantTool> | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy?: RunCreateAndPollParams.TruncationStrategy | null;\n}\n\nexport namespace RunCreateAndPollParams {\n export interface AdditionalMessage {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<AdditionalMessage.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n }\n\n export namespace AdditionalMessage {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n}\n\nexport interface RunCreateAndStreamParams {\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Appends additional instructions at the end of the instructions for the run. This\n * is useful for modifying the behavior on a per-run basis without overriding other\n * instructions.\n */\n additional_instructions?: string | null;\n\n /**\n * Adds additional messages to the thread before creating the run.\n */\n additional_messages?: Array<RunCreateAndStreamParams.AdditionalMessage> | null;\n\n /**\n * Overrides the\n * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant)\n * of the assistant. This is useful for modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * The maximum number of completion tokens that may be used over the course of the\n * run. The run will make a best effort to use only the number of completion tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * completion tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * The maximum number of prompt tokens that may be used over the course of the run.\n * The run will make a best effort to use only the number of prompt tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * prompt tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to\n * be used to execute this run. If a value is provided here, it will override the\n * model associated with the assistant. If not, the model associated with the\n * assistant will be used.\n */\n model?:\n | (string & {})\n | 'gpt-4o'\n | 'gpt-4o-2024-05-13'\n | 'gpt-4-turbo'\n | 'gpt-4-turbo-2024-04-09'\n | 'gpt-4-0125-preview'\n | 'gpt-4-turbo-preview'\n | 'gpt-4-1106-preview'\n | 'gpt-4-vision-preview'\n | 'gpt-4'\n | 'gpt-4-0314'\n | 'gpt-4-0613'\n | 'gpt-4-32k'\n | 'gpt-4-32k-0314'\n | 'gpt-4-32k-0613'\n | 'gpt-3.5-turbo'\n | 'gpt-3.5-turbo-16k'\n | 'gpt-3.5-turbo-0613'\n | 'gpt-3.5-turbo-1106'\n | 'gpt-3.5-turbo-0125'\n | 'gpt-3.5-turbo-16k-0613'\n | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models/gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which guarantees the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null;\n\n /**\n * Override the tools the assistant can use for this run. This is useful for\n * modifying the behavior on a per-run basis.\n */\n tools?: Array<AssistantsAPI.AssistantTool> | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy?: RunCreateAndStreamParams.TruncationStrategy | null;\n}\n\nexport namespace RunCreateAndStreamParams {\n export interface AdditionalMessage {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<AdditionalMessage.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n }\n\n export namespace AdditionalMessage {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n}\n\nexport interface RunStreamParams {\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Appends additional instructions at the end of the instructions for the run. This\n * is useful for modifying the behavior on a per-run basis without overriding other\n * instructions.\n */\n additional_instructions?: string | null;\n\n /**\n * Adds additional messages to the thread before creating the run.\n */\n additional_messages?: Array<RunStreamParams.AdditionalMessage> | null;\n\n /**\n * Overrides the\n * [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant)\n * of the assistant. This is useful for modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * The maximum number of completion tokens that may be used over the course of the\n * run. The run will make a best effort to use only the number of completion tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * completion tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * The maximum number of prompt tokens that may be used over the course of the run.\n * The run will make a best effort to use only the number of prompt tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * prompt tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to\n * be used to execute this run. If a value is provided here, it will override the\n * model associated with the assistant. If not, the model associated with the\n * assistant will be used.\n */\n model?:\n | (string & {})\n | 'gpt-4o'\n | 'gpt-4o-2024-05-13'\n | 'gpt-4-turbo'\n | 'gpt-4-turbo-2024-04-09'\n | 'gpt-4-0125-preview'\n | 'gpt-4-turbo-preview'\n | 'gpt-4-1106-preview'\n | 'gpt-4-vision-preview'\n | 'gpt-4'\n | 'gpt-4-0314'\n | 'gpt-4-0613'\n | 'gpt-4-32k'\n | 'gpt-4-32k-0314'\n | 'gpt-4-32k-0613'\n | 'gpt-3.5-turbo'\n | 'gpt-3.5-turbo-16k'\n | 'gpt-3.5-turbo-0613'\n | 'gpt-3.5-turbo-1106'\n | 'gpt-3.5-turbo-0125'\n | 'gpt-3.5-turbo-16k-0613'\n | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models/gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which guarantees the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: ThreadsAPI.AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: ThreadsAPI.AssistantToolChoiceOption | null;\n\n /**\n * Override the tools the assistant can use for this run. This is useful for\n * modifying the behavior on a per-run basis.\n */\n tools?: Array<AssistantsAPI.AssistantTool> | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy?: RunStreamParams.TruncationStrategy | null;\n}\n\nexport namespace RunStreamParams {\n export interface AdditionalMessage {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<AdditionalMessage.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n }\n\n export namespace AdditionalMessage {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n}\n\nexport type RunSubmitToolOutputsParams =\n | RunSubmitToolOutputsParamsNonStreaming\n | RunSubmitToolOutputsParamsStreaming;\n\nexport interface RunSubmitToolOutputsParamsBase {\n /**\n * A list of tools for which the outputs are being submitted.\n */\n tool_outputs: Array<RunSubmitToolOutputsParams.ToolOutput>;\n\n /**\n * If `true`, returns a stream of events that happen during the Run as server-sent\n * events, terminating when the Run enters a terminal state with a `data: [DONE]`\n * message.\n */\n stream?: boolean | null;\n}\n\nexport namespace RunSubmitToolOutputsParams {\n export interface ToolOutput {\n /**\n * The output of the tool call to be submitted to continue the run.\n */\n output?: string;\n\n /**\n * The ID of the tool call in the `required_action` object within the run object\n * the output is being submitted for.\n */\n tool_call_id?: string;\n }\n\n export type RunSubmitToolOutputsParamsNonStreaming = RunsAPI.RunSubmitToolOutputsParamsNonStreaming;\n export type RunSubmitToolOutputsParamsStreaming = RunsAPI.RunSubmitToolOutputsParamsStreaming;\n}\n\nexport interface RunSubmitToolOutputsParamsNonStreaming extends RunSubmitToolOutputsParamsBase {\n /**\n * If `true`, returns a stream of events that happen during the Run as server-sent\n * events, terminating when the Run enters a terminal state with a `data: [DONE]`\n * message.\n */\n stream?: false | null;\n}\n\nexport interface RunSubmitToolOutputsParamsStreaming extends RunSubmitToolOutputsParamsBase {\n /**\n * If `true`, returns a stream of events that happen during the Run as server-sent\n * events, terminating when the Run enters a terminal state with a `data: [DONE]`\n * message.\n */\n stream: true;\n}\n\nexport interface RunSubmitToolOutputsAndPollParams {\n /**\n * A list of tools for which the outputs are being submitted.\n */\n tool_outputs: Array<RunSubmitToolOutputsAndPollParams.ToolOutput>;\n}\n\nexport namespace RunSubmitToolOutputsAndPollParams {\n export interface ToolOutput {\n /**\n * The output of the tool call to be submitted to continue the run.\n */\n output?: string;\n\n /**\n * The ID of the tool call in the `required_action` object within the run object\n * the output is being submitted for.\n */\n tool_call_id?: string;\n }\n}\n\nexport interface RunSubmitToolOutputsStreamParams {\n /**\n * A list of tools for which the outputs are being submitted.\n */\n tool_outputs: Array<RunSubmitToolOutputsStreamParams.ToolOutput>;\n}\n\nexport namespace RunSubmitToolOutputsStreamParams {\n export interface ToolOutput {\n /**\n * The output of the tool call to be submitted to continue the run.\n */\n output?: string;\n\n /**\n * The ID of the tool call in the `required_action` object within the run object\n * the output is being submitted for.\n */\n tool_call_id?: string;\n }\n}\n\nRuns.RunsPage = RunsPage;\nRuns.Steps = Steps;\nRuns.RunStepsPage = RunStepsPage;\n\nexport declare namespace Runs {\n export {\n type RequiredActionFunctionToolCall as RequiredActionFunctionToolCall,\n type Run as Run,\n type RunStatus as RunStatus,\n RunsPage as RunsPage,\n type RunCreateParams as RunCreateParams,\n type RunCreateParamsNonStreaming as RunCreateParamsNonStreaming,\n type RunCreateParamsStreaming as RunCreateParamsStreaming,\n type RunUpdateParams as RunUpdateParams,\n type RunListParams as RunListParams,\n type RunCreateAndPollParams,\n type RunCreateAndStreamParams,\n type RunStreamParams,\n type RunSubmitToolOutputsParams as RunSubmitToolOutputsParams,\n type RunSubmitToolOutputsParamsNonStreaming as RunSubmitToolOutputsParamsNonStreaming,\n type RunSubmitToolOutputsParamsStreaming as RunSubmitToolOutputsParamsStreaming,\n type RunSubmitToolOutputsAndPollParams,\n type RunSubmitToolOutputsStreamParams,\n };\n\n export {\n Steps as Steps,\n type CodeInterpreterLogs as CodeInterpreterLogs,\n type CodeInterpreterOutputImage as CodeInterpreterOutputImage,\n type CodeInterpreterToolCall as CodeInterpreterToolCall,\n type CodeInterpreterToolCallDelta as CodeInterpreterToolCallDelta,\n type FileSearchToolCall as FileSearchToolCall,\n type FileSearchToolCallDelta as FileSearchToolCallDelta,\n type FunctionToolCall as FunctionToolCall,\n type FunctionToolCallDelta as FunctionToolCallDelta,\n type MessageCreationStepDetails as MessageCreationStepDetails,\n type RunStep as RunStep,\n type RunStepDelta as RunStepDelta,\n type RunStepDeltaEvent as RunStepDeltaEvent,\n type RunStepDeltaMessageDelta as RunStepDeltaMessageDelta,\n type RunStepInclude as RunStepInclude,\n type ToolCall as ToolCall,\n type ToolCallDelta as ToolCallDelta,\n type ToolCallDeltaObject as ToolCallDeltaObject,\n type ToolCallsStepDetails as ToolCallsStepDetails,\n RunStepsPage as RunStepsPage,\n type StepRetrieveParams as StepRetrieveParams,\n type StepListParams as StepListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport { AssistantStream, ThreadCreateAndRunParamsBaseStream } from '../../../lib/AssistantStream';\nimport { APIPromise } from '../../../core';\nimport * as Core from '../../../core';\nimport * as ThreadsAPI from './threads';\nimport * as Shared from '../../shared';\nimport * as AssistantsAPI from '../assistants';\nimport * as MessagesAPI from './messages';\nimport {\n Annotation,\n AnnotationDelta,\n FileCitationAnnotation,\n FileCitationDeltaAnnotation,\n FilePathAnnotation,\n FilePathDeltaAnnotation,\n ImageFile,\n ImageFileContentBlock,\n ImageFileDelta,\n ImageFileDeltaBlock,\n ImageURL,\n ImageURLContentBlock,\n ImageURLDelta,\n ImageURLDeltaBlock,\n Message as MessagesAPIMessage,\n MessageContent,\n MessageContentDelta,\n MessageContentPartParam,\n MessageCreateParams,\n MessageDeleted,\n MessageDelta,\n MessageDeltaEvent,\n MessageListParams,\n MessageUpdateParams,\n Messages,\n MessagesPage,\n RefusalContentBlock,\n RefusalDeltaBlock,\n Text,\n TextContentBlock,\n TextContentBlockParam,\n TextDelta,\n TextDeltaBlock,\n} from './messages';\nimport * as RunsAPI from './runs/runs';\nimport {\n RequiredActionFunctionToolCall,\n Run,\n RunCreateAndPollParams,\n RunCreateAndStreamParams,\n RunCreateParams,\n RunCreateParamsNonStreaming,\n RunCreateParamsStreaming,\n RunListParams,\n RunStatus,\n RunStreamParams,\n RunSubmitToolOutputsAndPollParams,\n RunSubmitToolOutputsParams,\n RunSubmitToolOutputsParamsNonStreaming,\n RunSubmitToolOutputsParamsStreaming,\n RunSubmitToolOutputsStreamParams,\n RunUpdateParams,\n Runs,\n RunsPage,\n} from './runs/runs';\nimport { Stream } from '../../../streaming';\n\n/**\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\nexport class Threads extends APIResource {\n runs: RunsAPI.Runs = new RunsAPI.Runs(this._client);\n messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client);\n\n /**\n * Create a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n create(body?: ThreadCreateParams, options?: Core.RequestOptions): Core.APIPromise<Thread>;\n create(options?: Core.RequestOptions): Core.APIPromise<Thread>;\n create(\n body: ThreadCreateParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<Thread> {\n if (isRequestOptions(body)) {\n return this.create({}, body);\n }\n return this._client.post('/threads', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Retrieves a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n retrieve(threadId: string, options?: Core.RequestOptions): Core.APIPromise<Thread> {\n return this._client.get(`/threads/${threadId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Modifies a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n update(threadId: string, body: ThreadUpdateParams, options?: Core.RequestOptions): Core.APIPromise<Thread> {\n return this._client.post(`/threads/${threadId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Delete a thread.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n del(threadId: string, options?: Core.RequestOptions): Core.APIPromise<ThreadDeleted> {\n return this._client.delete(`/threads/${threadId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Create a thread and run it in one request.\n *\n * @deprecated The Assistants API is deprecated in favor of the Responses API\n */\n createAndRun(\n body: ThreadCreateAndRunParamsNonStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<RunsAPI.Run>;\n createAndRun(\n body: ThreadCreateAndRunParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>>;\n createAndRun(\n body: ThreadCreateAndRunParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<AssistantsAPI.AssistantStreamEvent> | RunsAPI.Run>;\n createAndRun(\n body: ThreadCreateAndRunParams,\n options?: Core.RequestOptions,\n ): APIPromise<RunsAPI.Run> | APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>> {\n return this._client.post('/threads/runs', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: body.stream ?? false,\n }) as APIPromise<RunsAPI.Run> | APIPromise<Stream<AssistantsAPI.AssistantStreamEvent>>;\n }\n\n /**\n * A helper to create a thread, start a run and then poll for a terminal state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndRunPoll(\n body: ThreadCreateAndRunParamsNonStreaming,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<Threads.Run> {\n const run = await this.createAndRun(body, options);\n return await this.runs.poll(run.thread_id, run.id, options);\n }\n\n /**\n * Create a thread and stream the run back\n */\n createAndRunStream(\n body: ThreadCreateAndRunParamsBaseStream,\n options?: Core.RequestOptions,\n ): AssistantStream {\n return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);\n }\n}\n\n/**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\nexport type AssistantResponseFormatOption =\n | 'auto'\n | Shared.ResponseFormatText\n | Shared.ResponseFormatJSONObject\n | Shared.ResponseFormatJSONSchema;\n\n/**\n * Specifies a tool the model should use. Use to force the model to call a specific\n * tool.\n */\nexport interface AssistantToolChoice {\n /**\n * The type of the tool. If type is `function`, the function name must be set\n */\n type: 'function' | 'code_interpreter' | 'file_search';\n\n function?: AssistantToolChoiceFunction;\n}\n\nexport interface AssistantToolChoiceFunction {\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\n/**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\nexport type AssistantToolChoiceOption = 'none' | 'auto' | 'required' | AssistantToolChoice;\n\n/**\n * Represents a thread that contains\n * [messages](https://platform.openai.com/docs/api-reference/messages).\n */\nexport interface Thread {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the thread was created.\n */\n created_at: number;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The object type, which is always `thread`.\n */\n object: 'thread';\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n tool_resources: Thread.ToolResources | null;\n}\n\nexport namespace Thread {\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this thread. There can be a maximum of 1 vector store attached to\n * the thread.\n */\n vector_store_ids?: Array<string>;\n }\n }\n}\n\nexport interface ThreadDeleted {\n id: string;\n\n deleted: boolean;\n\n object: 'thread.deleted';\n}\n\nexport interface ThreadCreateParams {\n /**\n * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to\n * start the thread with.\n */\n messages?: Array<ThreadCreateParams.Message>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n tool_resources?: ThreadCreateParams.ToolResources | null;\n}\n\nexport namespace ThreadCreateParams {\n export interface Message {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<Message.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n export namespace Message {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | Attachment.FileSearch>;\n }\n\n export namespace Attachment {\n export interface FileSearch {\n /**\n * The type of tool being defined: `file_search`\n */\n type: 'file_search';\n }\n }\n }\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this thread. There can be a maximum of 1 vector store attached to\n * the thread.\n */\n vector_store_ids?: Array<string>;\n\n /**\n * A helper to create a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * with file_ids and attach it to this thread. There can be a maximum of 1 vector\n * store attached to the thread.\n */\n vector_stores?: Array<FileSearch.VectorStore>;\n }\n\n export namespace FileSearch {\n export interface VectorStore {\n /**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy.\n */\n chunking_strategy?: VectorStore.Auto | VectorStore.Static;\n\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to\n * add to the vector store. There can be a maximum of 10000 files in a vector\n * store.\n */\n file_ids?: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n export namespace VectorStore {\n /**\n * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of\n * `800` and `chunk_overlap_tokens` of `400`.\n */\n export interface Auto {\n /**\n * Always `auto`.\n */\n type: 'auto';\n }\n\n export interface Static {\n static: Static.Static;\n\n /**\n * Always `static`.\n */\n type: 'static';\n }\n\n export namespace Static {\n export interface Static {\n /**\n * The number of tokens that overlap between chunks. The default value is `400`.\n *\n * Note that the overlap must not exceed half of `max_chunk_size_tokens`.\n */\n chunk_overlap_tokens: number;\n\n /**\n * The maximum number of tokens in each chunk. The default value is `800`. The\n * minimum value is `100` and the maximum value is `4096`.\n */\n max_chunk_size_tokens: number;\n }\n }\n }\n }\n }\n}\n\nexport interface ThreadUpdateParams {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n tool_resources?: ThreadUpdateParams.ToolResources | null;\n}\n\nexport namespace ThreadUpdateParams {\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this thread. There can be a maximum of 1 vector store attached to\n * the thread.\n */\n vector_store_ids?: Array<string>;\n }\n }\n}\n\nexport type ThreadCreateAndRunParams =\n | ThreadCreateAndRunParamsNonStreaming\n | ThreadCreateAndRunParamsStreaming;\n\nexport interface ThreadCreateAndRunParamsBase {\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Override the default system message of the assistant. This is useful for\n * modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * The maximum number of completion tokens that may be used over the course of the\n * run. The run will make a best effort to use only the number of completion tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * completion tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * The maximum number of prompt tokens that may be used over the course of the run.\n * The run will make a best effort to use only the number of prompt tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * prompt tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to\n * be used to execute this run. If a value is provided here, it will override the\n * model associated with the assistant. If not, the model associated with the\n * assistant will be used.\n */\n model?: (string & {}) | Shared.ChatModel | null;\n\n /**\n * Whether to enable\n * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling)\n * during tool use.\n */\n parallel_tool_calls?: boolean;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured\n * Outputs which ensures the model will match your supplied JSON schema. Learn more\n * in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: AssistantResponseFormatOption | null;\n\n /**\n * If `true`, returns a stream of events that happen during the Run as server-sent\n * events, terminating when the Run enters a terminal state with a `data: [DONE]`\n * message.\n */\n stream?: boolean | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * Options to create a new thread. If no thread is provided when running a request,\n * an empty thread will be created.\n */\n thread?: ThreadCreateAndRunParams.Thread;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: AssistantToolChoiceOption | null;\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n tool_resources?: ThreadCreateAndRunParams.ToolResources | null;\n\n /**\n * Override the tools the assistant can use for this run. This is useful for\n * modifying the behavior on a per-run basis.\n */\n tools?: Array<AssistantsAPI.AssistantTool> | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy?: ThreadCreateAndRunParams.TruncationStrategy | null;\n}\n\nexport namespace ThreadCreateAndRunParams {\n /**\n * Options to create a new thread. If no thread is provided when running a request,\n * an empty thread will be created.\n */\n export interface Thread {\n /**\n * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to\n * start the thread with.\n */\n messages?: Array<Thread.Message>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n tool_resources?: Thread.ToolResources | null;\n }\n\n export namespace Thread {\n export interface Message {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<Message.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n export namespace Message {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | Attachment.FileSearch>;\n }\n\n export namespace Attachment {\n export interface FileSearch {\n /**\n * The type of tool being defined: `file_search`\n */\n type: 'file_search';\n }\n }\n }\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this thread. There can be a maximum of 1 vector store attached to\n * the thread.\n */\n vector_store_ids?: Array<string>;\n\n /**\n * A helper to create a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * with file_ids and attach it to this thread. There can be a maximum of 1 vector\n * store attached to the thread.\n */\n vector_stores?: Array<FileSearch.VectorStore>;\n }\n\n export namespace FileSearch {\n export interface VectorStore {\n /**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy.\n */\n chunking_strategy?: VectorStore.Auto | VectorStore.Static;\n\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to\n * add to the vector store. There can be a maximum of 10000 files in a vector\n * store.\n */\n file_ids?: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n export namespace VectorStore {\n /**\n * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of\n * `800` and `chunk_overlap_tokens` of `400`.\n */\n export interface Auto {\n /**\n * Always `auto`.\n */\n type: 'auto';\n }\n\n export interface Static {\n static: Static.Static;\n\n /**\n * Always `static`.\n */\n type: 'static';\n }\n\n export namespace Static {\n export interface Static {\n /**\n * The number of tokens that overlap between chunks. The default value is `400`.\n *\n * Note that the overlap must not exceed half of `max_chunk_size_tokens`.\n */\n chunk_overlap_tokens: number;\n\n /**\n * The maximum number of tokens in each chunk. The default value is `800`. The\n * minimum value is `100` and the maximum value is `4096`.\n */\n max_chunk_size_tokens: number;\n }\n }\n }\n }\n }\n }\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n\n export type ThreadCreateAndRunParamsNonStreaming = ThreadsAPI.ThreadCreateAndRunParamsNonStreaming;\n export type ThreadCreateAndRunParamsStreaming = ThreadsAPI.ThreadCreateAndRunParamsStreaming;\n}\n\nexport interface ThreadCreateAndRunParamsNonStreaming extends ThreadCreateAndRunParamsBase {\n /**\n * If `true`, returns a stream of events that happen during the Run as server-sent\n * events, terminating when the Run enters a terminal state with a `data: [DONE]`\n * message.\n */\n stream?: false | null;\n}\n\nexport interface ThreadCreateAndRunParamsStreaming extends ThreadCreateAndRunParamsBase {\n /**\n * If `true`, returns a stream of events that happen during the Run as server-sent\n * events, terminating when the Run enters a terminal state with a `data: [DONE]`\n * message.\n */\n stream: true;\n}\n\nexport interface ThreadCreateAndRunPollParams {\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Override the default system message of the assistant. This is useful for\n * modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * The maximum number of completion tokens that may be used over the course of the\n * run. The run will make a best effort to use only the number of completion tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * completion tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * The maximum number of prompt tokens that may be used over the course of the run.\n * The run will make a best effort to use only the number of prompt tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * prompt tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to\n * be used to execute this run. If a value is provided here, it will override the\n * model associated with the assistant. If not, the model associated with the\n * assistant will be used.\n */\n model?:\n | (string & {})\n | 'gpt-4o'\n | 'gpt-4o-2024-05-13'\n | 'gpt-4-turbo'\n | 'gpt-4-turbo-2024-04-09'\n | 'gpt-4-0125-preview'\n | 'gpt-4-turbo-preview'\n | 'gpt-4-1106-preview'\n | 'gpt-4-vision-preview'\n | 'gpt-4'\n | 'gpt-4-0314'\n | 'gpt-4-0613'\n | 'gpt-4-32k'\n | 'gpt-4-32k-0314'\n | 'gpt-4-32k-0613'\n | 'gpt-3.5-turbo'\n | 'gpt-3.5-turbo-16k'\n | 'gpt-3.5-turbo-0613'\n | 'gpt-3.5-turbo-1106'\n | 'gpt-3.5-turbo-0125'\n | 'gpt-3.5-turbo-16k-0613'\n | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models/gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which guarantees the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * If no thread is provided, an empty thread will be created.\n */\n thread?: ThreadCreateAndRunPollParams.Thread;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: AssistantToolChoiceOption | null;\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n tool_resources?: ThreadCreateAndRunPollParams.ToolResources | null;\n\n /**\n * Override the tools the assistant can use for this run. This is useful for\n * modifying the behavior on a per-run basis.\n */\n tools?: Array<\n AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool | AssistantsAPI.FunctionTool\n > | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy?: ThreadCreateAndRunPollParams.TruncationStrategy | null;\n}\n\nexport namespace ThreadCreateAndRunPollParams {\n /**\n * If no thread is provided, an empty thread will be created.\n */\n export interface Thread {\n /**\n * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to\n * start the thread with.\n */\n messages?: Array<Thread.Message>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n tool_resources?: Thread.ToolResources | null;\n }\n\n export namespace Thread {\n export interface Message {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<Message.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n }\n\n export namespace Message {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool>;\n }\n }\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this thread. There can be a maximum of 1 vector store attached to\n * the thread.\n */\n vector_store_ids?: Array<string>;\n\n /**\n * A helper to create a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * with file_ids and attach it to this thread. There can be a maximum of 1 vector\n * store attached to the thread.\n */\n vector_stores?: Array<FileSearch.VectorStore>;\n }\n\n export namespace FileSearch {\n export interface VectorStore {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to\n * add to the vector store. There can be a maximum of 10000 files in a vector\n * store.\n */\n file_ids?: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to a vector store. This can be\n * useful for storing additional information about the vector store in a structured\n * format. Keys can be a maximum of 64 characters long and values can be a maxium\n * of 512 characters long.\n */\n metadata?: unknown;\n }\n }\n }\n }\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n}\n\nexport interface ThreadCreateAndRunStreamParams {\n /**\n * The ID of the\n * [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to\n * execute this run.\n */\n assistant_id: string;\n\n /**\n * Override the default system message of the assistant. This is useful for\n * modifying the behavior on a per-run basis.\n */\n instructions?: string | null;\n\n /**\n * The maximum number of completion tokens that may be used over the course of the\n * run. The run will make a best effort to use only the number of completion tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * completion tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_completion_tokens?: number | null;\n\n /**\n * The maximum number of prompt tokens that may be used over the course of the run.\n * The run will make a best effort to use only the number of prompt tokens\n * specified, across multiple turns of the run. If the run exceeds the number of\n * prompt tokens specified, the run will end with status `incomplete`. See\n * `incomplete_details` for more info.\n */\n max_prompt_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to\n * be used to execute this run. If a value is provided here, it will override the\n * model associated with the assistant. If not, the model associated with the\n * assistant will be used.\n */\n model?:\n | (string & {})\n | 'gpt-4o'\n | 'gpt-4o-2024-05-13'\n | 'gpt-4-turbo'\n | 'gpt-4-turbo-2024-04-09'\n | 'gpt-4-0125-preview'\n | 'gpt-4-turbo-preview'\n | 'gpt-4-1106-preview'\n | 'gpt-4-vision-preview'\n | 'gpt-4'\n | 'gpt-4-0314'\n | 'gpt-4-0613'\n | 'gpt-4-32k'\n | 'gpt-4-32k-0314'\n | 'gpt-4-32k-0613'\n | 'gpt-3.5-turbo'\n | 'gpt-3.5-turbo-16k'\n | 'gpt-3.5-turbo-0613'\n | 'gpt-3.5-turbo-1106'\n | 'gpt-3.5-turbo-0125'\n | 'gpt-3.5-turbo-16k-0613'\n | null;\n\n /**\n * Specifies the format that the model must output. Compatible with\n * [GPT-4o](https://platform.openai.com/docs/models/gpt-4o),\n * [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4),\n * and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which guarantees the\n * message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to\n * produce JSON yourself via a system or user message. Without this, the model may\n * generate an unending stream of whitespace until the generation reaches the token\n * limit, resulting in a long-running and seemingly \"stuck\" request. Also note that\n * the message content may be partially cut off if `finish_reason=\"length\"`, which\n * indicates the generation exceeded `max_tokens` or the conversation exceeded the\n * max context length.\n */\n response_format?: AssistantResponseFormatOption | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n */\n temperature?: number | null;\n\n /**\n * If no thread is provided, an empty thread will be created.\n */\n thread?: ThreadCreateAndRunStreamParams.Thread;\n\n /**\n * Controls which (if any) tool is called by the model. `none` means the model will\n * not call any tools and instead generates a message. `auto` is the default value\n * and means the model can pick between generating a message or calling one or more\n * tools. `required` means the model must call one or more tools before responding\n * to the user. Specifying a particular tool like `{\"type\": \"file_search\"}` or\n * `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to\n * call that tool.\n */\n tool_choice?: AssistantToolChoiceOption | null;\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n tool_resources?: ThreadCreateAndRunStreamParams.ToolResources | null;\n\n /**\n * Override the tools the assistant can use for this run. This is useful for\n * modifying the behavior on a per-run basis.\n */\n tools?: Array<\n AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool | AssistantsAPI.FunctionTool\n > | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or temperature but not both.\n */\n top_p?: number | null;\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n truncation_strategy?: ThreadCreateAndRunStreamParams.TruncationStrategy | null;\n}\n\nexport namespace ThreadCreateAndRunStreamParams {\n /**\n * If no thread is provided, an empty thread will be created.\n */\n export interface Thread {\n /**\n * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to\n * start the thread with.\n */\n messages?: Array<Thread.Message>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n tool_resources?: Thread.ToolResources | null;\n }\n\n export namespace Thread {\n export interface Message {\n /**\n * The text contents of the message.\n */\n content: string | Array<MessagesAPI.MessageContentPartParam>;\n\n /**\n * The role of the entity that is creating the message. Allowed values include:\n *\n * - `user`: Indicates the message is sent by an actual user and should be used in\n * most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this\n * value to insert messages from the assistant into the conversation.\n */\n role: 'user' | 'assistant';\n\n /**\n * A list of files attached to the message, and the tools they should be added to.\n */\n attachments?: Array<Message.Attachment> | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format. Keys\n * can be a maximum of 64 characters long and values can be a maxium of 512\n * characters long.\n */\n metadata?: unknown | null;\n }\n\n export namespace Message {\n export interface Attachment {\n /**\n * The ID of the file to attach to the message.\n */\n file_id?: string;\n\n /**\n * The tools to add this file to.\n */\n tools?: Array<AssistantsAPI.CodeInterpreterTool | AssistantsAPI.FileSearchTool>;\n }\n }\n\n /**\n * A set of resources that are made available to the assistant's tools in this\n * thread. The resources are specific to the type of tool. For example, the\n * `code_interpreter` tool requires a list of file IDs, while the `file_search`\n * tool requires a list of vector store IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this thread. There can be a maximum of 1 vector store attached to\n * the thread.\n */\n vector_store_ids?: Array<string>;\n\n /**\n * A helper to create a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * with file_ids and attach it to this thread. There can be a maximum of 1 vector\n * store attached to the thread.\n */\n vector_stores?: Array<FileSearch.VectorStore>;\n }\n\n export namespace FileSearch {\n export interface VectorStore {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to\n * add to the vector store. There can be a maximum of 10000 files in a vector\n * store.\n */\n file_ids?: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to a vector store. This can be\n * useful for storing additional information about the vector store in a structured\n * format. Keys can be a maximum of 64 characters long and values can be a maxium\n * of 512 characters long.\n */\n metadata?: unknown;\n }\n }\n }\n }\n\n /**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\n export interface ToolResources {\n code_interpreter?: ToolResources.CodeInterpreter;\n\n file_search?: ToolResources.FileSearch;\n }\n\n export namespace ToolResources {\n export interface CodeInterpreter {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n }\n\n export interface FileSearch {\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n }\n }\n\n /**\n * Controls for how a thread will be truncated prior to the run. Use this to\n * control the intial context window of the run.\n */\n export interface TruncationStrategy {\n /**\n * The truncation strategy to use for the thread. The default is `auto`. If set to\n * `last_messages`, the thread will be truncated to the n most recent messages in\n * the thread. When set to `auto`, messages in the middle of the thread will be\n * dropped to fit the context length of the model, `max_prompt_tokens`.\n */\n type: 'auto' | 'last_messages';\n\n /**\n * The number of most recent messages from the thread when constructing the context\n * for the run.\n */\n last_messages?: number | null;\n }\n}\n\nThreads.Runs = Runs;\nThreads.RunsPage = RunsPage;\nThreads.Messages = Messages;\nThreads.MessagesPage = MessagesPage;\n\nexport declare namespace Threads {\n export {\n type AssistantResponseFormatOption as AssistantResponseFormatOption,\n type AssistantToolChoice as AssistantToolChoice,\n type AssistantToolChoiceFunction as AssistantToolChoiceFunction,\n type AssistantToolChoiceOption as AssistantToolChoiceOption,\n type Thread as Thread,\n type ThreadDeleted as ThreadDeleted,\n type ThreadCreateParams as ThreadCreateParams,\n type ThreadUpdateParams as ThreadUpdateParams,\n type ThreadCreateAndRunParams as ThreadCreateAndRunParams,\n type ThreadCreateAndRunParamsNonStreaming as ThreadCreateAndRunParamsNonStreaming,\n type ThreadCreateAndRunParamsStreaming as ThreadCreateAndRunParamsStreaming,\n type ThreadCreateAndRunPollParams,\n type ThreadCreateAndRunStreamParams,\n };\n\n export {\n Runs as Runs,\n type RequiredActionFunctionToolCall as RequiredActionFunctionToolCall,\n type Run as Run,\n type RunStatus as RunStatus,\n RunsPage as RunsPage,\n type RunCreateParams as RunCreateParams,\n type RunCreateParamsNonStreaming as RunCreateParamsNonStreaming,\n type RunCreateParamsStreaming as RunCreateParamsStreaming,\n type RunUpdateParams as RunUpdateParams,\n type RunListParams as RunListParams,\n type RunCreateAndPollParams,\n type RunCreateAndStreamParams,\n type RunStreamParams,\n type RunSubmitToolOutputsParams as RunSubmitToolOutputsParams,\n type RunSubmitToolOutputsParamsNonStreaming as RunSubmitToolOutputsParamsNonStreaming,\n type RunSubmitToolOutputsParamsStreaming as RunSubmitToolOutputsParamsStreaming,\n type RunSubmitToolOutputsAndPollParams,\n type RunSubmitToolOutputsStreamParams,\n };\n\n export {\n Messages as Messages,\n type Annotation as Annotation,\n type AnnotationDelta as AnnotationDelta,\n type FileCitationAnnotation as FileCitationAnnotation,\n type FileCitationDeltaAnnotation as FileCitationDeltaAnnotation,\n type FilePathAnnotation as FilePathAnnotation,\n type FilePathDeltaAnnotation as FilePathDeltaAnnotation,\n type ImageFile as ImageFile,\n type ImageFileContentBlock as ImageFileContentBlock,\n type ImageFileDelta as ImageFileDelta,\n type ImageFileDeltaBlock as ImageFileDeltaBlock,\n type ImageURL as ImageURL,\n type ImageURLContentBlock as ImageURLContentBlock,\n type ImageURLDelta as ImageURLDelta,\n type ImageURLDeltaBlock as ImageURLDeltaBlock,\n type MessagesAPIMessage as Message,\n type MessageContent as MessageContent,\n type MessageContentDelta as MessageContentDelta,\n type MessageContentPartParam as MessageContentPartParam,\n type MessageDeleted as MessageDeleted,\n type MessageDelta as MessageDelta,\n type MessageDeltaEvent as MessageDeltaEvent,\n type RefusalContentBlock as RefusalContentBlock,\n type RefusalDeltaBlock as RefusalDeltaBlock,\n type Text as Text,\n type TextContentBlock as TextContentBlock,\n type TextContentBlockParam as TextContentBlockParam,\n type TextDelta as TextDelta,\n type TextDeltaBlock as TextDeltaBlock,\n MessagesPage as MessagesPage,\n type MessageCreateParams as MessageCreateParams,\n type MessageUpdateParams as MessageUpdateParams,\n type MessageListParams as MessageListParams,\n };\n\n export { AssistantStream };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as AssistantsAPI from './assistants';\nimport * as ChatAPI from './chat/chat';\nimport {\n Assistant,\n AssistantCreateParams,\n AssistantDeleted,\n AssistantListParams,\n AssistantStreamEvent,\n AssistantTool,\n AssistantUpdateParams,\n Assistants,\n AssistantsPage,\n CodeInterpreterTool,\n FileSearchTool,\n FunctionTool,\n MessageStreamEvent,\n RunStepStreamEvent,\n RunStreamEvent,\n ThreadStreamEvent,\n} from './assistants';\nimport * as RealtimeAPI from './realtime/realtime';\nimport {\n ConversationCreatedEvent,\n ConversationItem,\n ConversationItemContent,\n ConversationItemCreateEvent,\n ConversationItemCreatedEvent,\n ConversationItemDeleteEvent,\n ConversationItemDeletedEvent,\n ConversationItemInputAudioTranscriptionCompletedEvent,\n ConversationItemInputAudioTranscriptionDeltaEvent,\n ConversationItemInputAudioTranscriptionFailedEvent,\n ConversationItemRetrieveEvent,\n ConversationItemTruncateEvent,\n ConversationItemTruncatedEvent,\n ConversationItemWithReference,\n ErrorEvent,\n InputAudioBufferAppendEvent,\n InputAudioBufferClearEvent,\n InputAudioBufferClearedEvent,\n InputAudioBufferCommitEvent,\n InputAudioBufferCommittedEvent,\n InputAudioBufferSpeechStartedEvent,\n InputAudioBufferSpeechStoppedEvent,\n RateLimitsUpdatedEvent,\n Realtime,\n RealtimeClientEvent,\n RealtimeResponse,\n RealtimeResponseStatus,\n RealtimeResponseUsage,\n RealtimeServerEvent,\n ResponseAudioDeltaEvent,\n ResponseAudioDoneEvent,\n ResponseAudioTranscriptDeltaEvent,\n ResponseAudioTranscriptDoneEvent,\n ResponseCancelEvent,\n ResponseContentPartAddedEvent,\n ResponseContentPartDoneEvent,\n ResponseCreateEvent,\n ResponseCreatedEvent,\n ResponseDoneEvent,\n ResponseFunctionCallArgumentsDeltaEvent,\n ResponseFunctionCallArgumentsDoneEvent,\n ResponseOutputItemAddedEvent,\n ResponseOutputItemDoneEvent,\n ResponseTextDeltaEvent,\n ResponseTextDoneEvent,\n SessionCreatedEvent,\n SessionUpdateEvent,\n SessionUpdatedEvent,\n TranscriptionSessionUpdate,\n TranscriptionSessionUpdatedEvent,\n} from './realtime/realtime';\nimport * as ThreadsAPI from './threads/threads';\nimport {\n AssistantResponseFormatOption,\n AssistantToolChoice,\n AssistantToolChoiceFunction,\n AssistantToolChoiceOption,\n Thread,\n ThreadCreateAndRunParams,\n ThreadCreateAndRunParamsNonStreaming,\n ThreadCreateAndRunParamsStreaming,\n ThreadCreateAndRunPollParams,\n ThreadCreateAndRunStreamParams,\n ThreadCreateParams,\n ThreadDeleted,\n ThreadUpdateParams,\n Threads,\n} from './threads/threads';\nimport { Chat } from './chat/chat';\n\nexport class Beta extends APIResource {\n realtime: RealtimeAPI.Realtime = new RealtimeAPI.Realtime(this._client);\n chat: ChatAPI.Chat = new ChatAPI.Chat(this._client);\n assistants: AssistantsAPI.Assistants = new AssistantsAPI.Assistants(this._client);\n threads: ThreadsAPI.Threads = new ThreadsAPI.Threads(this._client);\n}\n\nBeta.Realtime = Realtime;\nBeta.Assistants = Assistants;\nBeta.AssistantsPage = AssistantsPage;\nBeta.Threads = Threads;\n\nexport declare namespace Beta {\n export {\n Realtime as Realtime,\n type ConversationCreatedEvent as ConversationCreatedEvent,\n type ConversationItem as ConversationItem,\n type ConversationItemContent as ConversationItemContent,\n type ConversationItemCreateEvent as ConversationItemCreateEvent,\n type ConversationItemCreatedEvent as ConversationItemCreatedEvent,\n type ConversationItemDeleteEvent as ConversationItemDeleteEvent,\n type ConversationItemDeletedEvent as ConversationItemDeletedEvent,\n type ConversationItemInputAudioTranscriptionCompletedEvent as ConversationItemInputAudioTranscriptionCompletedEvent,\n type ConversationItemInputAudioTranscriptionDeltaEvent as ConversationItemInputAudioTranscriptionDeltaEvent,\n type ConversationItemInputAudioTranscriptionFailedEvent as ConversationItemInputAudioTranscriptionFailedEvent,\n type ConversationItemRetrieveEvent as ConversationItemRetrieveEvent,\n type ConversationItemTruncateEvent as ConversationItemTruncateEvent,\n type ConversationItemTruncatedEvent as ConversationItemTruncatedEvent,\n type ConversationItemWithReference as ConversationItemWithReference,\n type ErrorEvent as ErrorEvent,\n type InputAudioBufferAppendEvent as InputAudioBufferAppendEvent,\n type InputAudioBufferClearEvent as InputAudioBufferClearEvent,\n type InputAudioBufferClearedEvent as InputAudioBufferClearedEvent,\n type InputAudioBufferCommitEvent as InputAudioBufferCommitEvent,\n type InputAudioBufferCommittedEvent as InputAudioBufferCommittedEvent,\n type InputAudioBufferSpeechStartedEvent as InputAudioBufferSpeechStartedEvent,\n type InputAudioBufferSpeechStoppedEvent as InputAudioBufferSpeechStoppedEvent,\n type RateLimitsUpdatedEvent as RateLimitsUpdatedEvent,\n type RealtimeClientEvent as RealtimeClientEvent,\n type RealtimeResponse as RealtimeResponse,\n type RealtimeResponseStatus as RealtimeResponseStatus,\n type RealtimeResponseUsage as RealtimeResponseUsage,\n type RealtimeServerEvent as RealtimeServerEvent,\n type ResponseAudioDeltaEvent as ResponseAudioDeltaEvent,\n type ResponseAudioDoneEvent as ResponseAudioDoneEvent,\n type ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent,\n type ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent,\n type ResponseCancelEvent as ResponseCancelEvent,\n type ResponseContentPartAddedEvent as ResponseContentPartAddedEvent,\n type ResponseContentPartDoneEvent as ResponseContentPartDoneEvent,\n type ResponseCreateEvent as ResponseCreateEvent,\n type ResponseCreatedEvent as ResponseCreatedEvent,\n type ResponseDoneEvent as ResponseDoneEvent,\n type ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent,\n type ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent,\n type ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent,\n type ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent,\n type ResponseTextDeltaEvent as ResponseTextDeltaEvent,\n type ResponseTextDoneEvent as ResponseTextDoneEvent,\n type SessionCreatedEvent as SessionCreatedEvent,\n type SessionUpdateEvent as SessionUpdateEvent,\n type SessionUpdatedEvent as SessionUpdatedEvent,\n type TranscriptionSessionUpdate as TranscriptionSessionUpdate,\n type TranscriptionSessionUpdatedEvent as TranscriptionSessionUpdatedEvent,\n };\n\n export { Chat };\n\n export {\n Assistants as Assistants,\n type Assistant as Assistant,\n type AssistantDeleted as AssistantDeleted,\n type AssistantStreamEvent as AssistantStreamEvent,\n type AssistantTool as AssistantTool,\n type CodeInterpreterTool as CodeInterpreterTool,\n type FileSearchTool as FileSearchTool,\n type FunctionTool as FunctionTool,\n type MessageStreamEvent as MessageStreamEvent,\n type RunStepStreamEvent as RunStepStreamEvent,\n type RunStreamEvent as RunStreamEvent,\n type ThreadStreamEvent as ThreadStreamEvent,\n AssistantsPage as AssistantsPage,\n type AssistantCreateParams as AssistantCreateParams,\n type AssistantUpdateParams as AssistantUpdateParams,\n type AssistantListParams as AssistantListParams,\n };\n\n export {\n Threads as Threads,\n type AssistantResponseFormatOption as AssistantResponseFormatOption,\n type AssistantToolChoice as AssistantToolChoice,\n type AssistantToolChoiceFunction as AssistantToolChoiceFunction,\n type AssistantToolChoiceOption as AssistantToolChoiceOption,\n type Thread as Thread,\n type ThreadDeleted as ThreadDeleted,\n type ThreadCreateParams as ThreadCreateParams,\n type ThreadUpdateParams as ThreadUpdateParams,\n type ThreadCreateAndRunParams as ThreadCreateAndRunParams,\n type ThreadCreateAndRunParamsNonStreaming as ThreadCreateAndRunParamsNonStreaming,\n type ThreadCreateAndRunParamsStreaming as ThreadCreateAndRunParamsStreaming,\n type ThreadCreateAndRunPollParams,\n type ThreadCreateAndRunStreamParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport { APIPromise } from '../core';\nimport * as Core from '../core';\nimport * as CompletionsAPI from './completions';\nimport * as CompletionsCompletionsAPI from './chat/completions/completions';\nimport { Stream } from '../streaming';\n\nexport class Completions extends APIResource {\n /**\n * Creates a completion for the provided prompt and parameters.\n *\n * @example\n * ```ts\n * const completion = await client.completions.create({\n * model: 'string',\n * prompt: 'This is a test.',\n * });\n * ```\n */\n create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;\n create(\n body: CompletionCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<Completion>>;\n create(\n body: CompletionCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<Completion> | Completion>;\n create(\n body: CompletionCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Completion> | APIPromise<Stream<Completion>> {\n return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }) as\n | APIPromise<Completion>\n | APIPromise<Stream<Completion>>;\n }\n}\n\n/**\n * Represents a completion response from the API. Note: both the streamed and\n * non-streamed response objects share the same shape (unlike the chat endpoint).\n */\nexport interface Completion {\n /**\n * A unique identifier for the completion.\n */\n id: string;\n\n /**\n * The list of completion choices the model generated for the input prompt.\n */\n choices: Array<CompletionChoice>;\n\n /**\n * The Unix timestamp (in seconds) of when the completion was created.\n */\n created: number;\n\n /**\n * The model used for completion.\n */\n model: string;\n\n /**\n * The object type, which is always \"text_completion\"\n */\n object: 'text_completion';\n\n /**\n * This fingerprint represents the backend configuration that the model runs with.\n *\n * Can be used in conjunction with the `seed` request parameter to understand when\n * backend changes have been made that might impact determinism.\n */\n system_fingerprint?: string;\n\n /**\n * Usage statistics for the completion request.\n */\n usage?: CompletionUsage;\n}\n\nexport interface CompletionChoice {\n /**\n * The reason the model stopped generating tokens. This will be `stop` if the model\n * hit a natural stop point or a provided stop sequence, `length` if the maximum\n * number of tokens specified in the request was reached, or `content_filter` if\n * content was omitted due to a flag from our content filters.\n */\n finish_reason: 'stop' | 'length' | 'content_filter';\n\n index: number;\n\n logprobs: CompletionChoice.Logprobs | null;\n\n text: string;\n}\n\nexport namespace CompletionChoice {\n export interface Logprobs {\n text_offset?: Array<number>;\n\n token_logprobs?: Array<number>;\n\n tokens?: Array<string>;\n\n top_logprobs?: Array<Record<string, number>>;\n }\n}\n\n/**\n * Usage statistics for the completion request.\n */\nexport interface CompletionUsage {\n /**\n * Number of tokens in the generated completion.\n */\n completion_tokens: number;\n\n /**\n * Number of tokens in the prompt.\n */\n prompt_tokens: number;\n\n /**\n * Total number of tokens used in the request (prompt + completion).\n */\n total_tokens: number;\n\n /**\n * Breakdown of tokens used in a completion.\n */\n completion_tokens_details?: CompletionUsage.CompletionTokensDetails;\n\n /**\n * Breakdown of tokens used in the prompt.\n */\n prompt_tokens_details?: CompletionUsage.PromptTokensDetails;\n}\n\nexport namespace CompletionUsage {\n /**\n * Breakdown of tokens used in a completion.\n */\n export interface CompletionTokensDetails {\n /**\n * When using Predicted Outputs, the number of tokens in the prediction that\n * appeared in the completion.\n */\n accepted_prediction_tokens?: number;\n\n /**\n * Audio input tokens generated by the model.\n */\n audio_tokens?: number;\n\n /**\n * Tokens generated by the model for reasoning.\n */\n reasoning_tokens?: number;\n\n /**\n * When using Predicted Outputs, the number of tokens in the prediction that did\n * not appear in the completion. However, like reasoning tokens, these tokens are\n * still counted in the total completion tokens for purposes of billing, output,\n * and context window limits.\n */\n rejected_prediction_tokens?: number;\n }\n\n /**\n * Breakdown of tokens used in the prompt.\n */\n export interface PromptTokensDetails {\n /**\n * Audio input tokens present in the prompt.\n */\n audio_tokens?: number;\n\n /**\n * Cached tokens present in the prompt.\n */\n cached_tokens?: number;\n }\n}\n\nexport type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming;\n\nexport interface CompletionCreateParamsBase {\n /**\n * ID of the model to use. You can use the\n * [List models](https://platform.openai.com/docs/api-reference/models/list) API to\n * see all of your available models, or see our\n * [Model overview](https://platform.openai.com/docs/models) for descriptions of\n * them.\n */\n model: (string & {}) | 'gpt-3.5-turbo-instruct' | 'davinci-002' | 'babbage-002';\n\n /**\n * The prompt(s) to generate completions for, encoded as a string, array of\n * strings, array of tokens, or array of token arrays.\n *\n * Note that <|endoftext|> is the document separator that the model sees during\n * training, so if a prompt is not specified the model will generate as if from the\n * beginning of a new document.\n */\n prompt: string | Array<string> | Array<number> | Array<Array<number>> | null;\n\n /**\n * Generates `best_of` completions server-side and returns the \"best\" (the one with\n * the highest log probability per token). Results cannot be streamed.\n *\n * When used with `n`, `best_of` controls the number of candidate completions and\n * `n` specifies how many to return – `best_of` must be greater than `n`.\n *\n * **Note:** Because this parameter generates many completions, it can quickly\n * consume your token quota. Use carefully and ensure that you have reasonable\n * settings for `max_tokens` and `stop`.\n */\n best_of?: number | null;\n\n /**\n * Echo back the prompt in addition to the completion\n */\n echo?: boolean | null;\n\n /**\n * Number between -2.0 and 2.0. Positive values penalize new tokens based on their\n * existing frequency in the text so far, decreasing the model's likelihood to\n * repeat the same line verbatim.\n *\n * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n */\n frequency_penalty?: number | null;\n\n /**\n * Modify the likelihood of specified tokens appearing in the completion.\n *\n * Accepts a JSON object that maps tokens (specified by their token ID in the GPT\n * tokenizer) to an associated bias value from -100 to 100. You can use this\n * [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.\n * Mathematically, the bias is added to the logits generated by the model prior to\n * sampling. The exact effect will vary per model, but values between -1 and 1\n * should decrease or increase likelihood of selection; values like -100 or 100\n * should result in a ban or exclusive selection of the relevant token.\n *\n * As an example, you can pass `{\"50256\": -100}` to prevent the <|endoftext|> token\n * from being generated.\n */\n logit_bias?: Record<string, number> | null;\n\n /**\n * Include the log probabilities on the `logprobs` most likely output tokens, as\n * well the chosen tokens. For example, if `logprobs` is 5, the API will return a\n * list of the 5 most likely tokens. The API will always return the `logprob` of\n * the sampled token, so there may be up to `logprobs+1` elements in the response.\n *\n * The maximum value for `logprobs` is 5.\n */\n logprobs?: number | null;\n\n /**\n * The maximum number of [tokens](/tokenizer) that can be generated in the\n * completion.\n *\n * The token count of your prompt plus `max_tokens` cannot exceed the model's\n * context length.\n * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)\n * for counting tokens.\n */\n max_tokens?: number | null;\n\n /**\n * How many completions to generate for each prompt.\n *\n * **Note:** Because this parameter generates many completions, it can quickly\n * consume your token quota. Use carefully and ensure that you have reasonable\n * settings for `max_tokens` and `stop`.\n */\n n?: number | null;\n\n /**\n * Number between -2.0 and 2.0. Positive values penalize new tokens based on\n * whether they appear in the text so far, increasing the model's likelihood to\n * talk about new topics.\n *\n * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n */\n presence_penalty?: number | null;\n\n /**\n * If specified, our system will make a best effort to sample deterministically,\n * such that repeated requests with the same `seed` and parameters should return\n * the same result.\n *\n * Determinism is not guaranteed, and you should refer to the `system_fingerprint`\n * response parameter to monitor changes in the backend.\n */\n seed?: number | null;\n\n /**\n * Not supported with latest reasoning models `o3` and `o4-mini`.\n *\n * Up to 4 sequences where the API will stop generating further tokens. The\n * returned text will not contain the stop sequence.\n */\n stop?: string | null | Array<string>;\n\n /**\n * Whether to stream back partial progress. If set, tokens will be sent as\n * data-only\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)\n * as they become available, with the stream terminated by a `data: [DONE]`\n * message.\n * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n */\n stream?: boolean | null;\n\n /**\n * Options for streaming response. Only set this when you set `stream: true`.\n */\n stream_options?: CompletionsCompletionsAPI.ChatCompletionStreamOptions | null;\n\n /**\n * The suffix that comes after a completion of inserted text.\n *\n * This parameter is only supported for `gpt-3.5-turbo-instruct`.\n */\n suffix?: string | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic.\n *\n * We generally recommend altering this or `top_p` but not both.\n */\n temperature?: number | null;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or `temperature` but not both.\n */\n top_p?: number | null;\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor\n * and detect abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport namespace CompletionCreateParams {\n export type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming;\n export type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming;\n}\n\nexport interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {\n /**\n * Whether to stream back partial progress. If set, tokens will be sent as\n * data-only\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)\n * as they become available, with the stream terminated by a `data: [DONE]`\n * message.\n * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n */\n stream?: false | null;\n}\n\nexport interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {\n /**\n * Whether to stream back partial progress. If set, tokens will be sent as\n * data-only\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)\n * as they become available, with the stream terminated by a `data: [DONE]`\n * message.\n * [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n */\n stream: true;\n}\n\nexport declare namespace Completions {\n export {\n type Completion as Completion,\n type CompletionChoice as CompletionChoice,\n type CompletionUsage as CompletionUsage,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as Core from '../../../core';\nimport { type Response } from '../../../_shims/index';\n\nexport class Content extends APIResource {\n /**\n * Retrieve Container File Content\n */\n retrieve(containerId: string, fileId: string, options?: Core.RequestOptions): Core.APIPromise<Response> {\n return this._client.get(`/containers/${containerId}/files/${fileId}/content`, {\n ...options,\n headers: { Accept: 'application/binary', ...options?.headers },\n __binaryResponse: true,\n });\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport * as ContentAPI from './content';\nimport { Content } from './content';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\n\nexport class Files extends APIResource {\n content: ContentAPI.Content = new ContentAPI.Content(this._client);\n\n /**\n * Create a Container File\n *\n * You can send either a multipart/form-data request with the raw file content, or\n * a JSON request with a file ID.\n */\n create(\n containerId: string,\n body: FileCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<FileCreateResponse> {\n return this._client.post(\n `/containers/${containerId}/files`,\n Core.multipartFormRequestOptions({ body, ...options }),\n );\n }\n\n /**\n * Retrieve Container File\n */\n retrieve(\n containerId: string,\n fileId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<FileRetrieveResponse> {\n return this._client.get(`/containers/${containerId}/files/${fileId}`, options);\n }\n\n /**\n * List Container files\n */\n list(\n containerId: string,\n query?: FileListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FileListResponsesPage, FileListResponse>;\n list(\n containerId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FileListResponsesPage, FileListResponse>;\n list(\n containerId: string,\n query: FileListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<FileListResponsesPage, FileListResponse> {\n if (isRequestOptions(query)) {\n return this.list(containerId, {}, query);\n }\n return this._client.getAPIList(`/containers/${containerId}/files`, FileListResponsesPage, {\n query,\n ...options,\n });\n }\n\n /**\n * Delete Container File\n */\n del(containerId: string, fileId: string, options?: Core.RequestOptions): Core.APIPromise<void> {\n return this._client.delete(`/containers/${containerId}/files/${fileId}`, {\n ...options,\n headers: { Accept: '*/*', ...options?.headers },\n });\n }\n}\n\nexport class FileListResponsesPage extends CursorPage<FileListResponse> {}\n\nexport interface FileCreateResponse {\n /**\n * Unique identifier for the file.\n */\n id: string;\n\n /**\n * Size of the file in bytes.\n */\n bytes: number;\n\n /**\n * The container this file belongs to.\n */\n container_id: string;\n\n /**\n * Unix timestamp (in seconds) when the file was created.\n */\n created_at: number;\n\n /**\n * The type of this object (`container.file`).\n */\n object: 'container.file';\n\n /**\n * Path of the file in the container.\n */\n path: string;\n\n /**\n * Source of the file (e.g., `user`, `assistant`).\n */\n source: string;\n}\n\nexport interface FileRetrieveResponse {\n /**\n * Unique identifier for the file.\n */\n id: string;\n\n /**\n * Size of the file in bytes.\n */\n bytes: number;\n\n /**\n * The container this file belongs to.\n */\n container_id: string;\n\n /**\n * Unix timestamp (in seconds) when the file was created.\n */\n created_at: number;\n\n /**\n * The type of this object (`container.file`).\n */\n object: 'container.file';\n\n /**\n * Path of the file in the container.\n */\n path: string;\n\n /**\n * Source of the file (e.g., `user`, `assistant`).\n */\n source: string;\n}\n\nexport interface FileListResponse {\n /**\n * Unique identifier for the file.\n */\n id: string;\n\n /**\n * Size of the file in bytes.\n */\n bytes: number;\n\n /**\n * The container this file belongs to.\n */\n container_id: string;\n\n /**\n * Unix timestamp (in seconds) when the file was created.\n */\n created_at: number;\n\n /**\n * The type of this object (`container.file`).\n */\n object: 'container.file';\n\n /**\n * Path of the file in the container.\n */\n path: string;\n\n /**\n * Source of the file (e.g., `user`, `assistant`).\n */\n source: string;\n}\n\nexport interface FileCreateParams {\n /**\n * The File object (not file name) to be uploaded.\n */\n file?: Core.Uploadable;\n\n /**\n * Name of the file to create.\n */\n file_id?: string;\n}\n\nexport interface FileListParams extends CursorPageParams {\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nFiles.FileListResponsesPage = FileListResponsesPage;\nFiles.Content = Content;\n\nexport declare namespace Files {\n export {\n type FileCreateResponse as FileCreateResponse,\n type FileRetrieveResponse as FileRetrieveResponse,\n type FileListResponse as FileListResponse,\n FileListResponsesPage as FileListResponsesPage,\n type FileCreateParams as FileCreateParams,\n type FileListParams as FileListParams,\n };\n\n export { Content as Content };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { isRequestOptions } from '../../core';\nimport * as Core from '../../core';\nimport * as FilesAPI from './files/files';\nimport {\n FileCreateParams,\n FileCreateResponse,\n FileListParams,\n FileListResponse,\n FileListResponsesPage,\n FileRetrieveResponse,\n Files,\n} from './files/files';\nimport { CursorPage, type CursorPageParams } from '../../pagination';\n\nexport class Containers extends APIResource {\n files: FilesAPI.Files = new FilesAPI.Files(this._client);\n\n /**\n * Create Container\n */\n create(\n body: ContainerCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<ContainerCreateResponse> {\n return this._client.post('/containers', { body, ...options });\n }\n\n /**\n * Retrieve Container\n */\n retrieve(containerId: string, options?: Core.RequestOptions): Core.APIPromise<ContainerRetrieveResponse> {\n return this._client.get(`/containers/${containerId}`, options);\n }\n\n /**\n * List Containers\n */\n list(\n query?: ContainerListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<ContainerListResponsesPage, ContainerListResponse>;\n list(options?: Core.RequestOptions): Core.PagePromise<ContainerListResponsesPage, ContainerListResponse>;\n list(\n query: ContainerListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<ContainerListResponsesPage, ContainerListResponse> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/containers', ContainerListResponsesPage, { query, ...options });\n }\n\n /**\n * Delete Container\n */\n del(containerId: string, options?: Core.RequestOptions): Core.APIPromise<void> {\n return this._client.delete(`/containers/${containerId}`, {\n ...options,\n headers: { Accept: '*/*', ...options?.headers },\n });\n }\n}\n\nexport class ContainerListResponsesPage extends CursorPage<ContainerListResponse> {}\n\nexport interface ContainerCreateResponse {\n /**\n * Unique identifier for the container.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the container was created.\n */\n created_at: number;\n\n /**\n * Name of the container.\n */\n name: string;\n\n /**\n * The type of this object.\n */\n object: string;\n\n /**\n * Status of the container (e.g., active, deleted).\n */\n status: string;\n\n /**\n * The container will expire after this time period. The anchor is the reference\n * point for the expiration. The minutes is the number of minutes after the anchor\n * before the container expires.\n */\n expires_after?: ContainerCreateResponse.ExpiresAfter;\n}\n\nexport namespace ContainerCreateResponse {\n /**\n * The container will expire after this time period. The anchor is the reference\n * point for the expiration. The minutes is the number of minutes after the anchor\n * before the container expires.\n */\n export interface ExpiresAfter {\n /**\n * The reference point for the expiration.\n */\n anchor?: 'last_active_at';\n\n /**\n * The number of minutes after the anchor before the container expires.\n */\n minutes?: number;\n }\n}\n\nexport interface ContainerRetrieveResponse {\n /**\n * Unique identifier for the container.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the container was created.\n */\n created_at: number;\n\n /**\n * Name of the container.\n */\n name: string;\n\n /**\n * The type of this object.\n */\n object: string;\n\n /**\n * Status of the container (e.g., active, deleted).\n */\n status: string;\n\n /**\n * The container will expire after this time period. The anchor is the reference\n * point for the expiration. The minutes is the number of minutes after the anchor\n * before the container expires.\n */\n expires_after?: ContainerRetrieveResponse.ExpiresAfter;\n}\n\nexport namespace ContainerRetrieveResponse {\n /**\n * The container will expire after this time period. The anchor is the reference\n * point for the expiration. The minutes is the number of minutes after the anchor\n * before the container expires.\n */\n export interface ExpiresAfter {\n /**\n * The reference point for the expiration.\n */\n anchor?: 'last_active_at';\n\n /**\n * The number of minutes after the anchor before the container expires.\n */\n minutes?: number;\n }\n}\n\nexport interface ContainerListResponse {\n /**\n * Unique identifier for the container.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the container was created.\n */\n created_at: number;\n\n /**\n * Name of the container.\n */\n name: string;\n\n /**\n * The type of this object.\n */\n object: string;\n\n /**\n * Status of the container (e.g., active, deleted).\n */\n status: string;\n\n /**\n * The container will expire after this time period. The anchor is the reference\n * point for the expiration. The minutes is the number of minutes after the anchor\n * before the container expires.\n */\n expires_after?: ContainerListResponse.ExpiresAfter;\n}\n\nexport namespace ContainerListResponse {\n /**\n * The container will expire after this time period. The anchor is the reference\n * point for the expiration. The minutes is the number of minutes after the anchor\n * before the container expires.\n */\n export interface ExpiresAfter {\n /**\n * The reference point for the expiration.\n */\n anchor?: 'last_active_at';\n\n /**\n * The number of minutes after the anchor before the container expires.\n */\n minutes?: number;\n }\n}\n\nexport interface ContainerCreateParams {\n /**\n * Name of the container to create.\n */\n name: string;\n\n /**\n * Container expiration time in seconds relative to the 'anchor' time.\n */\n expires_after?: ContainerCreateParams.ExpiresAfter;\n\n /**\n * IDs of files to copy to the container.\n */\n file_ids?: Array<string>;\n}\n\nexport namespace ContainerCreateParams {\n /**\n * Container expiration time in seconds relative to the 'anchor' time.\n */\n export interface ExpiresAfter {\n /**\n * Time anchor for the expiration time. Currently only 'last_active_at' is\n * supported.\n */\n anchor: 'last_active_at';\n\n minutes: number;\n }\n}\n\nexport interface ContainerListParams extends CursorPageParams {\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nContainers.ContainerListResponsesPage = ContainerListResponsesPage;\nContainers.Files = Files;\nContainers.FileListResponsesPage = FileListResponsesPage;\n\nexport declare namespace Containers {\n export {\n type ContainerCreateResponse as ContainerCreateResponse,\n type ContainerRetrieveResponse as ContainerRetrieveResponse,\n type ContainerListResponse as ContainerListResponse,\n ContainerListResponsesPage as ContainerListResponsesPage,\n type ContainerCreateParams as ContainerCreateParams,\n type ContainerListParams as ContainerListParams,\n };\n\n export {\n Files as Files,\n type FileCreateResponse as FileCreateResponse,\n type FileRetrieveResponse as FileRetrieveResponse,\n type FileListResponse as FileListResponse,\n FileListResponsesPage as FileListResponsesPage,\n type FileCreateParams as FileCreateParams,\n type FileListParams as FileListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport * as Core from '../core';\n\nexport class Embeddings extends APIResource {\n /**\n * Creates an embedding vector representing the input text.\n *\n * @example\n * ```ts\n * const createEmbeddingResponse =\n * await client.embeddings.create({\n * input: 'The quick brown fox jumped over the lazy dog',\n * model: 'text-embedding-3-small',\n * });\n * ```\n */\n create(\n body: EmbeddingCreateParams,\n options?: Core.RequestOptions<EmbeddingCreateParams>,\n ): Core.APIPromise<CreateEmbeddingResponse> {\n const hasUserProvidedEncodingFormat = !!body.encoding_format;\n // No encoding_format specified, defaulting to base64 for performance reasons\n // See https://github.com/openai/openai-node/pull/1312\n let encoding_format: EmbeddingCreateParams['encoding_format'] =\n hasUserProvidedEncodingFormat ? body.encoding_format : 'base64';\n\n if (hasUserProvidedEncodingFormat) {\n Core.debug('Request', 'User defined encoding_format:', body.encoding_format);\n }\n\n const response: Core.APIPromise<CreateEmbeddingResponse> = this._client.post('/embeddings', {\n body: {\n ...body,\n encoding_format: encoding_format as EmbeddingCreateParams['encoding_format'],\n },\n ...options,\n });\n\n // if the user specified an encoding_format, return the response as-is\n if (hasUserProvidedEncodingFormat) {\n return response;\n }\n\n // in this stage, we are sure the user did not specify an encoding_format\n // and we defaulted to base64 for performance reasons\n // we are sure then that the response is base64 encoded, let's decode it\n // the returned result will be a float32 array since this is OpenAI API's default encoding\n Core.debug('response', 'Decoding base64 embeddings to float32 array');\n\n return (response as Core.APIPromise<CreateEmbeddingResponse>)._thenUnwrap((response) => {\n if (response && response.data) {\n response.data.forEach((embeddingBase64Obj) => {\n const embeddingBase64Str = embeddingBase64Obj.embedding as unknown as string;\n embeddingBase64Obj.embedding = Core.toFloat32Array(embeddingBase64Str);\n });\n }\n\n return response;\n });\n }\n}\n\nexport interface CreateEmbeddingResponse {\n /**\n * The list of embeddings generated by the model.\n */\n data: Array<Embedding>;\n\n /**\n * The name of the model used to generate the embedding.\n */\n model: string;\n\n /**\n * The object type, which is always \"list\".\n */\n object: 'list';\n\n /**\n * The usage information for the request.\n */\n usage: CreateEmbeddingResponse.Usage;\n}\n\nexport namespace CreateEmbeddingResponse {\n /**\n * The usage information for the request.\n */\n export interface Usage {\n /**\n * The number of tokens used by the prompt.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used by the request.\n */\n total_tokens: number;\n }\n}\n\n/**\n * Represents an embedding vector returned by embedding endpoint.\n */\nexport interface Embedding {\n /**\n * The embedding vector, which is a list of floats. The length of vector depends on\n * the model as listed in the\n * [embedding guide](https://platform.openai.com/docs/guides/embeddings).\n */\n embedding: Array<number>;\n\n /**\n * The index of the embedding in the list of embeddings.\n */\n index: number;\n\n /**\n * The object type, which is always \"embedding\".\n */\n object: 'embedding';\n}\n\nexport type EmbeddingModel = 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large';\n\nexport interface EmbeddingCreateParams {\n /**\n * Input text to embed, encoded as a string or array of tokens. To embed multiple\n * inputs in a single request, pass an array of strings or array of token arrays.\n * The input must not exceed the max input tokens for the model (8192 tokens for\n * all embedding models), cannot be an empty string, and any array must be 2048\n * dimensions or less.\n * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)\n * for counting tokens. In addition to the per-input token limit, all embedding\n * models enforce a maximum of 300,000 tokens summed across all inputs in a single\n * request.\n */\n input: string | Array<string> | Array<number> | Array<Array<number>>;\n\n /**\n * ID of the model to use. You can use the\n * [List models](https://platform.openai.com/docs/api-reference/models/list) API to\n * see all of your available models, or see our\n * [Model overview](https://platform.openai.com/docs/models) for descriptions of\n * them.\n */\n model: (string & {}) | EmbeddingModel;\n\n /**\n * The number of dimensions the resulting output embeddings should have. Only\n * supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n /**\n * The format to return the embeddings in. Can be either `float` or\n * [`base64`](https://pypi.org/project/pybase64/).\n */\n encoding_format?: 'float' | 'base64';\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor\n * and detect abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport declare namespace Embeddings {\n export {\n type CreateEmbeddingResponse as CreateEmbeddingResponse,\n type Embedding as Embedding,\n type EmbeddingModel as EmbeddingModel,\n type EmbeddingCreateParams as EmbeddingCreateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport * as RunsAPI from './runs';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\n\nexport class OutputItems extends APIResource {\n /**\n * Get an evaluation run output item by ID.\n */\n retrieve(\n evalId: string,\n runId: string,\n outputItemId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<OutputItemRetrieveResponse> {\n return this._client.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`, options);\n }\n\n /**\n * Get a list of output items for an evaluation run.\n */\n list(\n evalId: string,\n runId: string,\n query?: OutputItemListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<OutputItemListResponsesPage, OutputItemListResponse>;\n list(\n evalId: string,\n runId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<OutputItemListResponsesPage, OutputItemListResponse>;\n list(\n evalId: string,\n runId: string,\n query: OutputItemListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<OutputItemListResponsesPage, OutputItemListResponse> {\n if (isRequestOptions(query)) {\n return this.list(evalId, runId, {}, query);\n }\n return this._client.getAPIList(\n `/evals/${evalId}/runs/${runId}/output_items`,\n OutputItemListResponsesPage,\n { query, ...options },\n );\n }\n}\n\nexport class OutputItemListResponsesPage extends CursorPage<OutputItemListResponse> {}\n\n/**\n * A schema representing an evaluation run output item.\n */\nexport interface OutputItemRetrieveResponse {\n /**\n * Unique identifier for the evaluation run output item.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the evaluation run was created.\n */\n created_at: number;\n\n /**\n * Details of the input data source item.\n */\n datasource_item: Record<string, unknown>;\n\n /**\n * The identifier for the data source item.\n */\n datasource_item_id: number;\n\n /**\n * The identifier of the evaluation group.\n */\n eval_id: string;\n\n /**\n * The type of the object. Always \"eval.run.output_item\".\n */\n object: 'eval.run.output_item';\n\n /**\n * A list of results from the evaluation run.\n */\n results: Array<Record<string, unknown>>;\n\n /**\n * The identifier of the evaluation run associated with this output item.\n */\n run_id: string;\n\n /**\n * A sample containing the input and output of the evaluation run.\n */\n sample: OutputItemRetrieveResponse.Sample;\n\n /**\n * The status of the evaluation run.\n */\n status: string;\n}\n\nexport namespace OutputItemRetrieveResponse {\n /**\n * A sample containing the input and output of the evaluation run.\n */\n export interface Sample {\n /**\n * An object representing an error response from the Eval API.\n */\n error: RunsAPI.EvalAPIError;\n\n /**\n * The reason why the sample generation was finished.\n */\n finish_reason: string;\n\n /**\n * An array of input messages.\n */\n input: Array<Sample.Input>;\n\n /**\n * The maximum number of tokens allowed for completion.\n */\n max_completion_tokens: number;\n\n /**\n * The model used for generating the sample.\n */\n model: string;\n\n /**\n * An array of output messages.\n */\n output: Array<Sample.Output>;\n\n /**\n * The seed used for generating the sample.\n */\n seed: number;\n\n /**\n * The sampling temperature used.\n */\n temperature: number;\n\n /**\n * The top_p value used for sampling.\n */\n top_p: number;\n\n /**\n * Token usage details for the sample.\n */\n usage: Sample.Usage;\n }\n\n export namespace Sample {\n /**\n * An input message.\n */\n export interface Input {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message sender (e.g., system, user, developer).\n */\n role: string;\n }\n\n export interface Output {\n /**\n * The content of the message.\n */\n content?: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role?: string;\n }\n\n /**\n * Token usage details for the sample.\n */\n export interface Usage {\n /**\n * The number of tokens retrieved from cache.\n */\n cached_tokens: number;\n\n /**\n * The number of completion tokens generated.\n */\n completion_tokens: number;\n\n /**\n * The number of prompt tokens used.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n }\n }\n}\n\n/**\n * A schema representing an evaluation run output item.\n */\nexport interface OutputItemListResponse {\n /**\n * Unique identifier for the evaluation run output item.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the evaluation run was created.\n */\n created_at: number;\n\n /**\n * Details of the input data source item.\n */\n datasource_item: Record<string, unknown>;\n\n /**\n * The identifier for the data source item.\n */\n datasource_item_id: number;\n\n /**\n * The identifier of the evaluation group.\n */\n eval_id: string;\n\n /**\n * The type of the object. Always \"eval.run.output_item\".\n */\n object: 'eval.run.output_item';\n\n /**\n * A list of results from the evaluation run.\n */\n results: Array<Record<string, unknown>>;\n\n /**\n * The identifier of the evaluation run associated with this output item.\n */\n run_id: string;\n\n /**\n * A sample containing the input and output of the evaluation run.\n */\n sample: OutputItemListResponse.Sample;\n\n /**\n * The status of the evaluation run.\n */\n status: string;\n}\n\nexport namespace OutputItemListResponse {\n /**\n * A sample containing the input and output of the evaluation run.\n */\n export interface Sample {\n /**\n * An object representing an error response from the Eval API.\n */\n error: RunsAPI.EvalAPIError;\n\n /**\n * The reason why the sample generation was finished.\n */\n finish_reason: string;\n\n /**\n * An array of input messages.\n */\n input: Array<Sample.Input>;\n\n /**\n * The maximum number of tokens allowed for completion.\n */\n max_completion_tokens: number;\n\n /**\n * The model used for generating the sample.\n */\n model: string;\n\n /**\n * An array of output messages.\n */\n output: Array<Sample.Output>;\n\n /**\n * The seed used for generating the sample.\n */\n seed: number;\n\n /**\n * The sampling temperature used.\n */\n temperature: number;\n\n /**\n * The top_p value used for sampling.\n */\n top_p: number;\n\n /**\n * Token usage details for the sample.\n */\n usage: Sample.Usage;\n }\n\n export namespace Sample {\n /**\n * An input message.\n */\n export interface Input {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message sender (e.g., system, user, developer).\n */\n role: string;\n }\n\n export interface Output {\n /**\n * The content of the message.\n */\n content?: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role?: string;\n }\n\n /**\n * Token usage details for the sample.\n */\n export interface Usage {\n /**\n * The number of tokens retrieved from cache.\n */\n cached_tokens: number;\n\n /**\n * The number of completion tokens generated.\n */\n completion_tokens: number;\n\n /**\n * The number of prompt tokens used.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n }\n }\n}\n\nexport interface OutputItemListParams extends CursorPageParams {\n /**\n * Sort order for output items by timestamp. Use `asc` for ascending order or\n * `desc` for descending order. Defaults to `asc`.\n */\n order?: 'asc' | 'desc';\n\n /**\n * Filter output items by status. Use `failed` to filter by failed output items or\n * `pass` to filter by passed output items.\n */\n status?: 'fail' | 'pass';\n}\n\nOutputItems.OutputItemListResponsesPage = OutputItemListResponsesPage;\n\nexport declare namespace OutputItems {\n export {\n type OutputItemRetrieveResponse as OutputItemRetrieveResponse,\n type OutputItemListResponse as OutputItemListResponse,\n OutputItemListResponsesPage as OutputItemListResponsesPage,\n type OutputItemListParams as OutputItemListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport * as Shared from '../../shared';\nimport * as ResponsesAPI from '../../responses/responses';\nimport * as OutputItemsAPI from './output-items';\nimport {\n OutputItemListParams,\n OutputItemListResponse,\n OutputItemListResponsesPage,\n OutputItemRetrieveResponse,\n OutputItems,\n} from './output-items';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\n\nexport class Runs extends APIResource {\n outputItems: OutputItemsAPI.OutputItems = new OutputItemsAPI.OutputItems(this._client);\n\n /**\n * Kicks off a new run for a given evaluation, specifying the data source, and what\n * model configuration to use to test. The datasource will be validated against the\n * schema specified in the config of the evaluation.\n */\n create(\n evalId: string,\n body: RunCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<RunCreateResponse> {\n return this._client.post(`/evals/${evalId}/runs`, { body, ...options });\n }\n\n /**\n * Get an evaluation run by ID.\n */\n retrieve(\n evalId: string,\n runId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<RunRetrieveResponse> {\n return this._client.get(`/evals/${evalId}/runs/${runId}`, options);\n }\n\n /**\n * Get a list of runs for an evaluation.\n */\n list(\n evalId: string,\n query?: RunListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunListResponsesPage, RunListResponse>;\n list(\n evalId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunListResponsesPage, RunListResponse>;\n list(\n evalId: string,\n query: RunListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<RunListResponsesPage, RunListResponse> {\n if (isRequestOptions(query)) {\n return this.list(evalId, {}, query);\n }\n return this._client.getAPIList(`/evals/${evalId}/runs`, RunListResponsesPage, { query, ...options });\n }\n\n /**\n * Delete an eval run.\n */\n del(evalId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise<RunDeleteResponse> {\n return this._client.delete(`/evals/${evalId}/runs/${runId}`, options);\n }\n\n /**\n * Cancel an ongoing evaluation run.\n */\n cancel(evalId: string, runId: string, options?: Core.RequestOptions): Core.APIPromise<RunCancelResponse> {\n return this._client.post(`/evals/${evalId}/runs/${runId}`, options);\n }\n}\n\nexport class RunListResponsesPage extends CursorPage<RunListResponse> {}\n\n/**\n * A CompletionsRunDataSource object describing a model sampling configuration.\n */\nexport interface CreateEvalCompletionsRunDataSource {\n /**\n * Determines what populates the `item` namespace in this run's data source.\n */\n source:\n | CreateEvalCompletionsRunDataSource.FileContent\n | CreateEvalCompletionsRunDataSource.FileID\n | CreateEvalCompletionsRunDataSource.StoredCompletions;\n\n /**\n * The type of run data source. Always `completions`.\n */\n type: 'completions';\n\n /**\n * Used when sampling from a model. Dictates the structure of the messages passed\n * into the model. Can either be a reference to a prebuilt trajectory (ie,\n * `item.input_trajectory`), or a template with variable references to the `item`\n * namespace.\n */\n input_messages?:\n | CreateEvalCompletionsRunDataSource.Template\n | CreateEvalCompletionsRunDataSource.ItemReference;\n\n /**\n * The name of the model to use for generating completions (e.g. \"o3-mini\").\n */\n model?: string;\n\n sampling_params?: CreateEvalCompletionsRunDataSource.SamplingParams;\n}\n\nexport namespace CreateEvalCompletionsRunDataSource {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n\n /**\n * A StoredCompletionsRunDataSource configuration describing a set of filters\n */\n export interface StoredCompletions {\n /**\n * The type of source. Always `stored_completions`.\n */\n type: 'stored_completions';\n\n /**\n * An optional Unix timestamp to filter items created after this time.\n */\n created_after?: number | null;\n\n /**\n * An optional Unix timestamp to filter items created before this time.\n */\n created_before?: number | null;\n\n /**\n * An optional maximum number of items to return.\n */\n limit?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * An optional model to filter by (e.g., 'gpt-4o').\n */\n model?: string | null;\n }\n\n export interface Template {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n template: Array<ResponsesAPI.EasyInputMessage | Template.Message>;\n\n /**\n * The type of input messages. Always `template`.\n */\n type: 'template';\n }\n\n export namespace Template {\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface Message {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | Message.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace Message {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n export interface ItemReference {\n /**\n * A reference to a variable in the `item` namespace. Ie, \"item.input_trajectory\"\n */\n item_reference: string;\n\n /**\n * The type of input messages. Always `item_reference`.\n */\n type: 'item_reference';\n }\n\n export interface SamplingParams {\n /**\n * The maximum number of tokens in the generated output.\n */\n max_completion_tokens?: number;\n\n /**\n * A seed value to initialize the randomness, during sampling.\n */\n seed?: number;\n\n /**\n * A higher temperature increases randomness in the outputs.\n */\n temperature?: number;\n\n /**\n * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n */\n top_p?: number;\n }\n}\n\n/**\n * A JsonlRunDataSource object with that specifies a JSONL file that matches the\n * eval\n */\nexport interface CreateEvalJSONLRunDataSource {\n /**\n * Determines what populates the `item` namespace in the data source.\n */\n source: CreateEvalJSONLRunDataSource.FileContent | CreateEvalJSONLRunDataSource.FileID;\n\n /**\n * The type of data source. Always `jsonl`.\n */\n type: 'jsonl';\n}\n\nexport namespace CreateEvalJSONLRunDataSource {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n}\n\n/**\n * An object representing an error response from the Eval API.\n */\nexport interface EvalAPIError {\n /**\n * The error code.\n */\n code: string;\n\n /**\n * The error message.\n */\n message: string;\n}\n\n/**\n * A schema representing an evaluation run.\n */\nexport interface RunCreateResponse {\n /**\n * Unique identifier for the evaluation run.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the evaluation run was created.\n */\n created_at: number;\n\n /**\n * Information about the run's data source.\n */\n data_source:\n | CreateEvalJSONLRunDataSource\n | CreateEvalCompletionsRunDataSource\n | RunCreateResponse.Responses;\n\n /**\n * An object representing an error response from the Eval API.\n */\n error: EvalAPIError;\n\n /**\n * The identifier of the associated evaluation.\n */\n eval_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The model that is evaluated, if applicable.\n */\n model: string;\n\n /**\n * The name of the evaluation run.\n */\n name: string;\n\n /**\n * The type of the object. Always \"eval.run\".\n */\n object: 'eval.run';\n\n /**\n * Usage statistics for each model during the evaluation run.\n */\n per_model_usage: Array<RunCreateResponse.PerModelUsage>;\n\n /**\n * Results per testing criteria applied during the evaluation run.\n */\n per_testing_criteria_results: Array<RunCreateResponse.PerTestingCriteriaResult>;\n\n /**\n * The URL to the rendered evaluation run report on the UI dashboard.\n */\n report_url: string;\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n result_counts: RunCreateResponse.ResultCounts;\n\n /**\n * The status of the evaluation run.\n */\n status: string;\n}\n\nexport namespace RunCreateResponse {\n /**\n * A ResponsesRunDataSource object describing a model sampling configuration.\n */\n export interface Responses {\n /**\n * Determines what populates the `item` namespace in this run's data source.\n */\n source: Responses.FileContent | Responses.FileID | Responses.Responses;\n\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Used when sampling from a model. Dictates the structure of the messages passed\n * into the model. Can either be a reference to a prebuilt trajectory (ie,\n * `item.input_trajectory`), or a template with variable references to the `item`\n * namespace.\n */\n input_messages?: Responses.Template | Responses.ItemReference;\n\n /**\n * The name of the model to use for generating completions (e.g. \"o3-mini\").\n */\n model?: string;\n\n sampling_params?: Responses.SamplingParams;\n }\n\n export namespace Responses {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n\n /**\n * A EvalResponsesSource object describing a run data source configuration.\n */\n export interface Responses {\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Only include items created after this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_after?: number | null;\n\n /**\n * Only include items created before this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_before?: number | null;\n\n /**\n * Optional string to search the 'instructions' field. This is a query parameter\n * used to select responses.\n */\n instructions_search?: string | null;\n\n /**\n * Metadata filter for the responses. This is a query parameter used to select\n * responses.\n */\n metadata?: unknown | null;\n\n /**\n * The name of the model to find responses for. This is a query parameter used to\n * select responses.\n */\n model?: string | null;\n\n /**\n * Optional reasoning effort parameter. This is a query parameter used to select\n * responses.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Sampling temperature. This is a query parameter used to select responses.\n */\n temperature?: number | null;\n\n /**\n * List of tool names. This is a query parameter used to select responses.\n */\n tools?: Array<string> | null;\n\n /**\n * Nucleus sampling parameter. This is a query parameter used to select responses.\n */\n top_p?: number | null;\n\n /**\n * List of user identifiers. This is a query parameter used to select responses.\n */\n users?: Array<string> | null;\n }\n\n export interface Template {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n template: Array<Template.ChatMessage | Template.EvalItem>;\n\n /**\n * The type of input messages. Always `template`.\n */\n type: 'template';\n }\n\n export namespace Template {\n export interface ChatMessage {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role: string;\n }\n\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface EvalItem {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | EvalItem.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace EvalItem {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n export interface ItemReference {\n /**\n * A reference to a variable in the `item` namespace. Ie, \"item.name\"\n */\n item_reference: string;\n\n /**\n * The type of input messages. Always `item_reference`.\n */\n type: 'item_reference';\n }\n\n export interface SamplingParams {\n /**\n * The maximum number of tokens in the generated output.\n */\n max_completion_tokens?: number;\n\n /**\n * A seed value to initialize the randomness, during sampling.\n */\n seed?: number;\n\n /**\n * A higher temperature increases randomness in the outputs.\n */\n temperature?: number;\n\n /**\n * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n */\n top_p?: number;\n }\n }\n\n export interface PerModelUsage {\n /**\n * The number of tokens retrieved from cache.\n */\n cached_tokens: number;\n\n /**\n * The number of completion tokens generated.\n */\n completion_tokens: number;\n\n /**\n * The number of invocations.\n */\n invocation_count: number;\n\n /**\n * The name of the model.\n */\n model_name: string;\n\n /**\n * The number of prompt tokens used.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n }\n\n export interface PerTestingCriteriaResult {\n /**\n * Number of tests failed for this criteria.\n */\n failed: number;\n\n /**\n * Number of tests passed for this criteria.\n */\n passed: number;\n\n /**\n * A description of the testing criteria.\n */\n testing_criteria: string;\n }\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n export interface ResultCounts {\n /**\n * Number of output items that resulted in an error.\n */\n errored: number;\n\n /**\n * Number of output items that failed to pass the evaluation.\n */\n failed: number;\n\n /**\n * Number of output items that passed the evaluation.\n */\n passed: number;\n\n /**\n * Total number of executed output items.\n */\n total: number;\n }\n}\n\n/**\n * A schema representing an evaluation run.\n */\nexport interface RunRetrieveResponse {\n /**\n * Unique identifier for the evaluation run.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the evaluation run was created.\n */\n created_at: number;\n\n /**\n * Information about the run's data source.\n */\n data_source:\n | CreateEvalJSONLRunDataSource\n | CreateEvalCompletionsRunDataSource\n | RunRetrieveResponse.Responses;\n\n /**\n * An object representing an error response from the Eval API.\n */\n error: EvalAPIError;\n\n /**\n * The identifier of the associated evaluation.\n */\n eval_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The model that is evaluated, if applicable.\n */\n model: string;\n\n /**\n * The name of the evaluation run.\n */\n name: string;\n\n /**\n * The type of the object. Always \"eval.run\".\n */\n object: 'eval.run';\n\n /**\n * Usage statistics for each model during the evaluation run.\n */\n per_model_usage: Array<RunRetrieveResponse.PerModelUsage>;\n\n /**\n * Results per testing criteria applied during the evaluation run.\n */\n per_testing_criteria_results: Array<RunRetrieveResponse.PerTestingCriteriaResult>;\n\n /**\n * The URL to the rendered evaluation run report on the UI dashboard.\n */\n report_url: string;\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n result_counts: RunRetrieveResponse.ResultCounts;\n\n /**\n * The status of the evaluation run.\n */\n status: string;\n}\n\nexport namespace RunRetrieveResponse {\n /**\n * A ResponsesRunDataSource object describing a model sampling configuration.\n */\n export interface Responses {\n /**\n * Determines what populates the `item` namespace in this run's data source.\n */\n source: Responses.FileContent | Responses.FileID | Responses.Responses;\n\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Used when sampling from a model. Dictates the structure of the messages passed\n * into the model. Can either be a reference to a prebuilt trajectory (ie,\n * `item.input_trajectory`), or a template with variable references to the `item`\n * namespace.\n */\n input_messages?: Responses.Template | Responses.ItemReference;\n\n /**\n * The name of the model to use for generating completions (e.g. \"o3-mini\").\n */\n model?: string;\n\n sampling_params?: Responses.SamplingParams;\n }\n\n export namespace Responses {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n\n /**\n * A EvalResponsesSource object describing a run data source configuration.\n */\n export interface Responses {\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Only include items created after this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_after?: number | null;\n\n /**\n * Only include items created before this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_before?: number | null;\n\n /**\n * Optional string to search the 'instructions' field. This is a query parameter\n * used to select responses.\n */\n instructions_search?: string | null;\n\n /**\n * Metadata filter for the responses. This is a query parameter used to select\n * responses.\n */\n metadata?: unknown | null;\n\n /**\n * The name of the model to find responses for. This is a query parameter used to\n * select responses.\n */\n model?: string | null;\n\n /**\n * Optional reasoning effort parameter. This is a query parameter used to select\n * responses.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Sampling temperature. This is a query parameter used to select responses.\n */\n temperature?: number | null;\n\n /**\n * List of tool names. This is a query parameter used to select responses.\n */\n tools?: Array<string> | null;\n\n /**\n * Nucleus sampling parameter. This is a query parameter used to select responses.\n */\n top_p?: number | null;\n\n /**\n * List of user identifiers. This is a query parameter used to select responses.\n */\n users?: Array<string> | null;\n }\n\n export interface Template {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n template: Array<Template.ChatMessage | Template.EvalItem>;\n\n /**\n * The type of input messages. Always `template`.\n */\n type: 'template';\n }\n\n export namespace Template {\n export interface ChatMessage {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role: string;\n }\n\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface EvalItem {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | EvalItem.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace EvalItem {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n export interface ItemReference {\n /**\n * A reference to a variable in the `item` namespace. Ie, \"item.name\"\n */\n item_reference: string;\n\n /**\n * The type of input messages. Always `item_reference`.\n */\n type: 'item_reference';\n }\n\n export interface SamplingParams {\n /**\n * The maximum number of tokens in the generated output.\n */\n max_completion_tokens?: number;\n\n /**\n * A seed value to initialize the randomness, during sampling.\n */\n seed?: number;\n\n /**\n * A higher temperature increases randomness in the outputs.\n */\n temperature?: number;\n\n /**\n * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n */\n top_p?: number;\n }\n }\n\n export interface PerModelUsage {\n /**\n * The number of tokens retrieved from cache.\n */\n cached_tokens: number;\n\n /**\n * The number of completion tokens generated.\n */\n completion_tokens: number;\n\n /**\n * The number of invocations.\n */\n invocation_count: number;\n\n /**\n * The name of the model.\n */\n model_name: string;\n\n /**\n * The number of prompt tokens used.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n }\n\n export interface PerTestingCriteriaResult {\n /**\n * Number of tests failed for this criteria.\n */\n failed: number;\n\n /**\n * Number of tests passed for this criteria.\n */\n passed: number;\n\n /**\n * A description of the testing criteria.\n */\n testing_criteria: string;\n }\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n export interface ResultCounts {\n /**\n * Number of output items that resulted in an error.\n */\n errored: number;\n\n /**\n * Number of output items that failed to pass the evaluation.\n */\n failed: number;\n\n /**\n * Number of output items that passed the evaluation.\n */\n passed: number;\n\n /**\n * Total number of executed output items.\n */\n total: number;\n }\n}\n\n/**\n * A schema representing an evaluation run.\n */\nexport interface RunListResponse {\n /**\n * Unique identifier for the evaluation run.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the evaluation run was created.\n */\n created_at: number;\n\n /**\n * Information about the run's data source.\n */\n data_source: CreateEvalJSONLRunDataSource | CreateEvalCompletionsRunDataSource | RunListResponse.Responses;\n\n /**\n * An object representing an error response from the Eval API.\n */\n error: EvalAPIError;\n\n /**\n * The identifier of the associated evaluation.\n */\n eval_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The model that is evaluated, if applicable.\n */\n model: string;\n\n /**\n * The name of the evaluation run.\n */\n name: string;\n\n /**\n * The type of the object. Always \"eval.run\".\n */\n object: 'eval.run';\n\n /**\n * Usage statistics for each model during the evaluation run.\n */\n per_model_usage: Array<RunListResponse.PerModelUsage>;\n\n /**\n * Results per testing criteria applied during the evaluation run.\n */\n per_testing_criteria_results: Array<RunListResponse.PerTestingCriteriaResult>;\n\n /**\n * The URL to the rendered evaluation run report on the UI dashboard.\n */\n report_url: string;\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n result_counts: RunListResponse.ResultCounts;\n\n /**\n * The status of the evaluation run.\n */\n status: string;\n}\n\nexport namespace RunListResponse {\n /**\n * A ResponsesRunDataSource object describing a model sampling configuration.\n */\n export interface Responses {\n /**\n * Determines what populates the `item` namespace in this run's data source.\n */\n source: Responses.FileContent | Responses.FileID | Responses.Responses;\n\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Used when sampling from a model. Dictates the structure of the messages passed\n * into the model. Can either be a reference to a prebuilt trajectory (ie,\n * `item.input_trajectory`), or a template with variable references to the `item`\n * namespace.\n */\n input_messages?: Responses.Template | Responses.ItemReference;\n\n /**\n * The name of the model to use for generating completions (e.g. \"o3-mini\").\n */\n model?: string;\n\n sampling_params?: Responses.SamplingParams;\n }\n\n export namespace Responses {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n\n /**\n * A EvalResponsesSource object describing a run data source configuration.\n */\n export interface Responses {\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Only include items created after this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_after?: number | null;\n\n /**\n * Only include items created before this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_before?: number | null;\n\n /**\n * Optional string to search the 'instructions' field. This is a query parameter\n * used to select responses.\n */\n instructions_search?: string | null;\n\n /**\n * Metadata filter for the responses. This is a query parameter used to select\n * responses.\n */\n metadata?: unknown | null;\n\n /**\n * The name of the model to find responses for. This is a query parameter used to\n * select responses.\n */\n model?: string | null;\n\n /**\n * Optional reasoning effort parameter. This is a query parameter used to select\n * responses.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Sampling temperature. This is a query parameter used to select responses.\n */\n temperature?: number | null;\n\n /**\n * List of tool names. This is a query parameter used to select responses.\n */\n tools?: Array<string> | null;\n\n /**\n * Nucleus sampling parameter. This is a query parameter used to select responses.\n */\n top_p?: number | null;\n\n /**\n * List of user identifiers. This is a query parameter used to select responses.\n */\n users?: Array<string> | null;\n }\n\n export interface Template {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n template: Array<Template.ChatMessage | Template.EvalItem>;\n\n /**\n * The type of input messages. Always `template`.\n */\n type: 'template';\n }\n\n export namespace Template {\n export interface ChatMessage {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role: string;\n }\n\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface EvalItem {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | EvalItem.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace EvalItem {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n export interface ItemReference {\n /**\n * A reference to a variable in the `item` namespace. Ie, \"item.name\"\n */\n item_reference: string;\n\n /**\n * The type of input messages. Always `item_reference`.\n */\n type: 'item_reference';\n }\n\n export interface SamplingParams {\n /**\n * The maximum number of tokens in the generated output.\n */\n max_completion_tokens?: number;\n\n /**\n * A seed value to initialize the randomness, during sampling.\n */\n seed?: number;\n\n /**\n * A higher temperature increases randomness in the outputs.\n */\n temperature?: number;\n\n /**\n * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n */\n top_p?: number;\n }\n }\n\n export interface PerModelUsage {\n /**\n * The number of tokens retrieved from cache.\n */\n cached_tokens: number;\n\n /**\n * The number of completion tokens generated.\n */\n completion_tokens: number;\n\n /**\n * The number of invocations.\n */\n invocation_count: number;\n\n /**\n * The name of the model.\n */\n model_name: string;\n\n /**\n * The number of prompt tokens used.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n }\n\n export interface PerTestingCriteriaResult {\n /**\n * Number of tests failed for this criteria.\n */\n failed: number;\n\n /**\n * Number of tests passed for this criteria.\n */\n passed: number;\n\n /**\n * A description of the testing criteria.\n */\n testing_criteria: string;\n }\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n export interface ResultCounts {\n /**\n * Number of output items that resulted in an error.\n */\n errored: number;\n\n /**\n * Number of output items that failed to pass the evaluation.\n */\n failed: number;\n\n /**\n * Number of output items that passed the evaluation.\n */\n passed: number;\n\n /**\n * Total number of executed output items.\n */\n total: number;\n }\n}\n\nexport interface RunDeleteResponse {\n deleted?: boolean;\n\n object?: string;\n\n run_id?: string;\n}\n\n/**\n * A schema representing an evaluation run.\n */\nexport interface RunCancelResponse {\n /**\n * Unique identifier for the evaluation run.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) when the evaluation run was created.\n */\n created_at: number;\n\n /**\n * Information about the run's data source.\n */\n data_source:\n | CreateEvalJSONLRunDataSource\n | CreateEvalCompletionsRunDataSource\n | RunCancelResponse.Responses;\n\n /**\n * An object representing an error response from the Eval API.\n */\n error: EvalAPIError;\n\n /**\n * The identifier of the associated evaluation.\n */\n eval_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The model that is evaluated, if applicable.\n */\n model: string;\n\n /**\n * The name of the evaluation run.\n */\n name: string;\n\n /**\n * The type of the object. Always \"eval.run\".\n */\n object: 'eval.run';\n\n /**\n * Usage statistics for each model during the evaluation run.\n */\n per_model_usage: Array<RunCancelResponse.PerModelUsage>;\n\n /**\n * Results per testing criteria applied during the evaluation run.\n */\n per_testing_criteria_results: Array<RunCancelResponse.PerTestingCriteriaResult>;\n\n /**\n * The URL to the rendered evaluation run report on the UI dashboard.\n */\n report_url: string;\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n result_counts: RunCancelResponse.ResultCounts;\n\n /**\n * The status of the evaluation run.\n */\n status: string;\n}\n\nexport namespace RunCancelResponse {\n /**\n * A ResponsesRunDataSource object describing a model sampling configuration.\n */\n export interface Responses {\n /**\n * Determines what populates the `item` namespace in this run's data source.\n */\n source: Responses.FileContent | Responses.FileID | Responses.Responses;\n\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Used when sampling from a model. Dictates the structure of the messages passed\n * into the model. Can either be a reference to a prebuilt trajectory (ie,\n * `item.input_trajectory`), or a template with variable references to the `item`\n * namespace.\n */\n input_messages?: Responses.Template | Responses.ItemReference;\n\n /**\n * The name of the model to use for generating completions (e.g. \"o3-mini\").\n */\n model?: string;\n\n sampling_params?: Responses.SamplingParams;\n }\n\n export namespace Responses {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n\n /**\n * A EvalResponsesSource object describing a run data source configuration.\n */\n export interface Responses {\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Only include items created after this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_after?: number | null;\n\n /**\n * Only include items created before this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_before?: number | null;\n\n /**\n * Optional string to search the 'instructions' field. This is a query parameter\n * used to select responses.\n */\n instructions_search?: string | null;\n\n /**\n * Metadata filter for the responses. This is a query parameter used to select\n * responses.\n */\n metadata?: unknown | null;\n\n /**\n * The name of the model to find responses for. This is a query parameter used to\n * select responses.\n */\n model?: string | null;\n\n /**\n * Optional reasoning effort parameter. This is a query parameter used to select\n * responses.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Sampling temperature. This is a query parameter used to select responses.\n */\n temperature?: number | null;\n\n /**\n * List of tool names. This is a query parameter used to select responses.\n */\n tools?: Array<string> | null;\n\n /**\n * Nucleus sampling parameter. This is a query parameter used to select responses.\n */\n top_p?: number | null;\n\n /**\n * List of user identifiers. This is a query parameter used to select responses.\n */\n users?: Array<string> | null;\n }\n\n export interface Template {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n template: Array<Template.ChatMessage | Template.EvalItem>;\n\n /**\n * The type of input messages. Always `template`.\n */\n type: 'template';\n }\n\n export namespace Template {\n export interface ChatMessage {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role: string;\n }\n\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface EvalItem {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | EvalItem.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace EvalItem {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n export interface ItemReference {\n /**\n * A reference to a variable in the `item` namespace. Ie, \"item.name\"\n */\n item_reference: string;\n\n /**\n * The type of input messages. Always `item_reference`.\n */\n type: 'item_reference';\n }\n\n export interface SamplingParams {\n /**\n * The maximum number of tokens in the generated output.\n */\n max_completion_tokens?: number;\n\n /**\n * A seed value to initialize the randomness, during sampling.\n */\n seed?: number;\n\n /**\n * A higher temperature increases randomness in the outputs.\n */\n temperature?: number;\n\n /**\n * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n */\n top_p?: number;\n }\n }\n\n export interface PerModelUsage {\n /**\n * The number of tokens retrieved from cache.\n */\n cached_tokens: number;\n\n /**\n * The number of completion tokens generated.\n */\n completion_tokens: number;\n\n /**\n * The number of invocations.\n */\n invocation_count: number;\n\n /**\n * The name of the model.\n */\n model_name: string;\n\n /**\n * The number of prompt tokens used.\n */\n prompt_tokens: number;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n }\n\n export interface PerTestingCriteriaResult {\n /**\n * Number of tests failed for this criteria.\n */\n failed: number;\n\n /**\n * Number of tests passed for this criteria.\n */\n passed: number;\n\n /**\n * A description of the testing criteria.\n */\n testing_criteria: string;\n }\n\n /**\n * Counters summarizing the outcomes of the evaluation run.\n */\n export interface ResultCounts {\n /**\n * Number of output items that resulted in an error.\n */\n errored: number;\n\n /**\n * Number of output items that failed to pass the evaluation.\n */\n failed: number;\n\n /**\n * Number of output items that passed the evaluation.\n */\n passed: number;\n\n /**\n * Total number of executed output items.\n */\n total: number;\n }\n}\n\nexport interface RunCreateParams {\n /**\n * Details about the run's data source.\n */\n data_source:\n | CreateEvalJSONLRunDataSource\n | CreateEvalCompletionsRunDataSource\n | RunCreateParams.CreateEvalResponsesRunDataSource;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The name of the run.\n */\n name?: string;\n}\n\nexport namespace RunCreateParams {\n /**\n * A ResponsesRunDataSource object describing a model sampling configuration.\n */\n export interface CreateEvalResponsesRunDataSource {\n /**\n * Determines what populates the `item` namespace in this run's data source.\n */\n source:\n | CreateEvalResponsesRunDataSource.FileContent\n | CreateEvalResponsesRunDataSource.FileID\n | CreateEvalResponsesRunDataSource.Responses;\n\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Used when sampling from a model. Dictates the structure of the messages passed\n * into the model. Can either be a reference to a prebuilt trajectory (ie,\n * `item.input_trajectory`), or a template with variable references to the `item`\n * namespace.\n */\n input_messages?:\n | CreateEvalResponsesRunDataSource.Template\n | CreateEvalResponsesRunDataSource.ItemReference;\n\n /**\n * The name of the model to use for generating completions (e.g. \"o3-mini\").\n */\n model?: string;\n\n sampling_params?: CreateEvalResponsesRunDataSource.SamplingParams;\n }\n\n export namespace CreateEvalResponsesRunDataSource {\n export interface FileContent {\n /**\n * The content of the jsonl file.\n */\n content: Array<FileContent.Content>;\n\n /**\n * The type of jsonl source. Always `file_content`.\n */\n type: 'file_content';\n }\n\n export namespace FileContent {\n export interface Content {\n item: Record<string, unknown>;\n\n sample?: Record<string, unknown>;\n }\n }\n\n export interface FileID {\n /**\n * The identifier of the file.\n */\n id: string;\n\n /**\n * The type of jsonl source. Always `file_id`.\n */\n type: 'file_id';\n }\n\n /**\n * A EvalResponsesSource object describing a run data source configuration.\n */\n export interface Responses {\n /**\n * The type of run data source. Always `responses`.\n */\n type: 'responses';\n\n /**\n * Only include items created after this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_after?: number | null;\n\n /**\n * Only include items created before this timestamp (inclusive). This is a query\n * parameter used to select responses.\n */\n created_before?: number | null;\n\n /**\n * Optional string to search the 'instructions' field. This is a query parameter\n * used to select responses.\n */\n instructions_search?: string | null;\n\n /**\n * Metadata filter for the responses. This is a query parameter used to select\n * responses.\n */\n metadata?: unknown | null;\n\n /**\n * The name of the model to find responses for. This is a query parameter used to\n * select responses.\n */\n model?: string | null;\n\n /**\n * Optional reasoning effort parameter. This is a query parameter used to select\n * responses.\n */\n reasoning_effort?: Shared.ReasoningEffort | null;\n\n /**\n * Sampling temperature. This is a query parameter used to select responses.\n */\n temperature?: number | null;\n\n /**\n * List of tool names. This is a query parameter used to select responses.\n */\n tools?: Array<string> | null;\n\n /**\n * Nucleus sampling parameter. This is a query parameter used to select responses.\n */\n top_p?: number | null;\n\n /**\n * List of user identifiers. This is a query parameter used to select responses.\n */\n users?: Array<string> | null;\n }\n\n export interface Template {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n template: Array<Template.ChatMessage | Template.EvalItem>;\n\n /**\n * The type of input messages. Always `template`.\n */\n type: 'template';\n }\n\n export namespace Template {\n export interface ChatMessage {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role: string;\n }\n\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface EvalItem {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | EvalItem.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace EvalItem {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n export interface ItemReference {\n /**\n * A reference to a variable in the `item` namespace. Ie, \"item.name\"\n */\n item_reference: string;\n\n /**\n * The type of input messages. Always `item_reference`.\n */\n type: 'item_reference';\n }\n\n export interface SamplingParams {\n /**\n * The maximum number of tokens in the generated output.\n */\n max_completion_tokens?: number;\n\n /**\n * A seed value to initialize the randomness, during sampling.\n */\n seed?: number;\n\n /**\n * A higher temperature increases randomness in the outputs.\n */\n temperature?: number;\n\n /**\n * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n */\n top_p?: number;\n }\n }\n}\n\nexport interface RunListParams extends CursorPageParams {\n /**\n * Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for\n * descending order. Defaults to `asc`.\n */\n order?: 'asc' | 'desc';\n\n /**\n * Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed`\n * | `canceled`.\n */\n status?: 'queued' | 'in_progress' | 'completed' | 'canceled' | 'failed';\n}\n\nRuns.RunListResponsesPage = RunListResponsesPage;\nRuns.OutputItems = OutputItems;\nRuns.OutputItemListResponsesPage = OutputItemListResponsesPage;\n\nexport declare namespace Runs {\n export {\n type CreateEvalCompletionsRunDataSource as CreateEvalCompletionsRunDataSource,\n type CreateEvalJSONLRunDataSource as CreateEvalJSONLRunDataSource,\n type EvalAPIError as EvalAPIError,\n type RunCreateResponse as RunCreateResponse,\n type RunRetrieveResponse as RunRetrieveResponse,\n type RunListResponse as RunListResponse,\n type RunDeleteResponse as RunDeleteResponse,\n type RunCancelResponse as RunCancelResponse,\n RunListResponsesPage as RunListResponsesPage,\n type RunCreateParams as RunCreateParams,\n type RunListParams as RunListParams,\n };\n\n export {\n OutputItems as OutputItems,\n type OutputItemRetrieveResponse as OutputItemRetrieveResponse,\n type OutputItemListResponse as OutputItemListResponse,\n OutputItemListResponsesPage as OutputItemListResponsesPage,\n type OutputItemListParams as OutputItemListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { isRequestOptions } from '../../core';\nimport * as Core from '../../core';\nimport * as Shared from '../shared';\nimport * as GraderModelsAPI from '../graders/grader-models';\nimport * as ResponsesAPI from '../responses/responses';\nimport * as RunsAPI from './runs/runs';\nimport {\n CreateEvalCompletionsRunDataSource,\n CreateEvalJSONLRunDataSource,\n EvalAPIError,\n RunCancelResponse,\n RunCreateParams,\n RunCreateResponse,\n RunDeleteResponse,\n RunListParams,\n RunListResponse,\n RunListResponsesPage,\n RunRetrieveResponse,\n Runs,\n} from './runs/runs';\nimport { CursorPage, type CursorPageParams } from '../../pagination';\n\nexport class Evals extends APIResource {\n runs: RunsAPI.Runs = new RunsAPI.Runs(this._client);\n\n /**\n * Create the structure of an evaluation that can be used to test a model's\n * performance. An evaluation is a set of testing criteria and the config for a\n * data source, which dictates the schema of the data used in the evaluation. After\n * creating an evaluation, you can run it on different models and model parameters.\n * We support several types of graders and datasources. For more information, see\n * the [Evals guide](https://platform.openai.com/docs/guides/evals).\n */\n create(body: EvalCreateParams, options?: Core.RequestOptions): Core.APIPromise<EvalCreateResponse> {\n return this._client.post('/evals', { body, ...options });\n }\n\n /**\n * Get an evaluation by ID.\n */\n retrieve(evalId: string, options?: Core.RequestOptions): Core.APIPromise<EvalRetrieveResponse> {\n return this._client.get(`/evals/${evalId}`, options);\n }\n\n /**\n * Update certain properties of an evaluation.\n */\n update(\n evalId: string,\n body: EvalUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<EvalUpdateResponse> {\n return this._client.post(`/evals/${evalId}`, { body, ...options });\n }\n\n /**\n * List evaluations for a project.\n */\n list(\n query?: EvalListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<EvalListResponsesPage, EvalListResponse>;\n list(options?: Core.RequestOptions): Core.PagePromise<EvalListResponsesPage, EvalListResponse>;\n list(\n query: EvalListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<EvalListResponsesPage, EvalListResponse> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/evals', EvalListResponsesPage, { query, ...options });\n }\n\n /**\n * Delete an evaluation.\n */\n del(evalId: string, options?: Core.RequestOptions): Core.APIPromise<EvalDeleteResponse> {\n return this._client.delete(`/evals/${evalId}`, options);\n }\n}\n\nexport class EvalListResponsesPage extends CursorPage<EvalListResponse> {}\n\n/**\n * A CustomDataSourceConfig which specifies the schema of your `item` and\n * optionally `sample` namespaces. The response schema defines the shape of the\n * data that will be:\n *\n * - Used to define your testing criteria and\n * - What data is required when creating a run\n */\nexport interface EvalCustomDataSourceConfig {\n /**\n * The json schema for the run data source items. Learn how to build JSON schemas\n * [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `custom`.\n */\n type: 'custom';\n}\n\n/**\n * @deprecated Deprecated in favor of LogsDataSourceConfig.\n */\nexport interface EvalStoredCompletionsDataSourceConfig {\n /**\n * The json schema for the run data source items. Learn how to build JSON schemas\n * [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `stored_completions`.\n */\n type: 'stored_completions';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n}\n\n/**\n * An Eval object with a data source config and testing criteria. An Eval\n * represents a task to be done for your LLM integration. Like:\n *\n * - Improve the quality of my chatbot\n * - See how well my chatbot handles customer support\n * - Check if o4-mini is better at my usecase than gpt-4o\n */\nexport interface EvalCreateResponse {\n /**\n * Unique identifier for the evaluation.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the eval was created.\n */\n created_at: number;\n\n /**\n * Configuration of data sources used in runs of the evaluation.\n */\n data_source_config:\n | EvalCustomDataSourceConfig\n | EvalCreateResponse.Logs\n | EvalStoredCompletionsDataSourceConfig;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The name of the evaluation.\n */\n name: string;\n\n /**\n * The object type.\n */\n object: 'eval';\n\n /**\n * A list of testing criteria.\n */\n testing_criteria: Array<\n | GraderModelsAPI.LabelModelGrader\n | GraderModelsAPI.StringCheckGrader\n | EvalCreateResponse.EvalGraderTextSimilarity\n | EvalCreateResponse.EvalGraderPython\n | EvalCreateResponse.EvalGraderScoreModel\n >;\n}\n\nexport namespace EvalCreateResponse {\n /**\n * A LogsDataSourceConfig which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The\n * schema returned by this data source config is used to defined what variables are\n * available in your evals. `item` and `sample` are both defined when using this\n * data source config.\n */\n export interface Logs {\n /**\n * The json schema for the run data source items. Learn how to build JSON schemas\n * [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `logs`.\n */\n type: 'logs';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n /**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\n export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold: number;\n }\n\n /**\n * A PythonGrader object that runs a python script on the input.\n */\n export interface EvalGraderPython extends GraderModelsAPI.PythonGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n\n /**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\n export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n}\n\n/**\n * An Eval object with a data source config and testing criteria. An Eval\n * represents a task to be done for your LLM integration. Like:\n *\n * - Improve the quality of my chatbot\n * - See how well my chatbot handles customer support\n * - Check if o4-mini is better at my usecase than gpt-4o\n */\nexport interface EvalRetrieveResponse {\n /**\n * Unique identifier for the evaluation.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the eval was created.\n */\n created_at: number;\n\n /**\n * Configuration of data sources used in runs of the evaluation.\n */\n data_source_config:\n | EvalCustomDataSourceConfig\n | EvalRetrieveResponse.Logs\n | EvalStoredCompletionsDataSourceConfig;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The name of the evaluation.\n */\n name: string;\n\n /**\n * The object type.\n */\n object: 'eval';\n\n /**\n * A list of testing criteria.\n */\n testing_criteria: Array<\n | GraderModelsAPI.LabelModelGrader\n | GraderModelsAPI.StringCheckGrader\n | EvalRetrieveResponse.EvalGraderTextSimilarity\n | EvalRetrieveResponse.EvalGraderPython\n | EvalRetrieveResponse.EvalGraderScoreModel\n >;\n}\n\nexport namespace EvalRetrieveResponse {\n /**\n * A LogsDataSourceConfig which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The\n * schema returned by this data source config is used to defined what variables are\n * available in your evals. `item` and `sample` are both defined when using this\n * data source config.\n */\n export interface Logs {\n /**\n * The json schema for the run data source items. Learn how to build JSON schemas\n * [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `logs`.\n */\n type: 'logs';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n /**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\n export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold: number;\n }\n\n /**\n * A PythonGrader object that runs a python script on the input.\n */\n export interface EvalGraderPython extends GraderModelsAPI.PythonGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n\n /**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\n export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n}\n\n/**\n * An Eval object with a data source config and testing criteria. An Eval\n * represents a task to be done for your LLM integration. Like:\n *\n * - Improve the quality of my chatbot\n * - See how well my chatbot handles customer support\n * - Check if o4-mini is better at my usecase than gpt-4o\n */\nexport interface EvalUpdateResponse {\n /**\n * Unique identifier for the evaluation.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the eval was created.\n */\n created_at: number;\n\n /**\n * Configuration of data sources used in runs of the evaluation.\n */\n data_source_config:\n | EvalCustomDataSourceConfig\n | EvalUpdateResponse.Logs\n | EvalStoredCompletionsDataSourceConfig;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The name of the evaluation.\n */\n name: string;\n\n /**\n * The object type.\n */\n object: 'eval';\n\n /**\n * A list of testing criteria.\n */\n testing_criteria: Array<\n | GraderModelsAPI.LabelModelGrader\n | GraderModelsAPI.StringCheckGrader\n | EvalUpdateResponse.EvalGraderTextSimilarity\n | EvalUpdateResponse.EvalGraderPython\n | EvalUpdateResponse.EvalGraderScoreModel\n >;\n}\n\nexport namespace EvalUpdateResponse {\n /**\n * A LogsDataSourceConfig which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The\n * schema returned by this data source config is used to defined what variables are\n * available in your evals. `item` and `sample` are both defined when using this\n * data source config.\n */\n export interface Logs {\n /**\n * The json schema for the run data source items. Learn how to build JSON schemas\n * [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `logs`.\n */\n type: 'logs';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n /**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\n export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold: number;\n }\n\n /**\n * A PythonGrader object that runs a python script on the input.\n */\n export interface EvalGraderPython extends GraderModelsAPI.PythonGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n\n /**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\n export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n}\n\n/**\n * An Eval object with a data source config and testing criteria. An Eval\n * represents a task to be done for your LLM integration. Like:\n *\n * - Improve the quality of my chatbot\n * - See how well my chatbot handles customer support\n * - Check if o4-mini is better at my usecase than gpt-4o\n */\nexport interface EvalListResponse {\n /**\n * Unique identifier for the evaluation.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the eval was created.\n */\n created_at: number;\n\n /**\n * Configuration of data sources used in runs of the evaluation.\n */\n data_source_config:\n | EvalCustomDataSourceConfig\n | EvalListResponse.Logs\n | EvalStoredCompletionsDataSourceConfig;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The name of the evaluation.\n */\n name: string;\n\n /**\n * The object type.\n */\n object: 'eval';\n\n /**\n * A list of testing criteria.\n */\n testing_criteria: Array<\n | GraderModelsAPI.LabelModelGrader\n | GraderModelsAPI.StringCheckGrader\n | EvalListResponse.EvalGraderTextSimilarity\n | EvalListResponse.EvalGraderPython\n | EvalListResponse.EvalGraderScoreModel\n >;\n}\n\nexport namespace EvalListResponse {\n /**\n * A LogsDataSourceConfig which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc. The\n * schema returned by this data source config is used to defined what variables are\n * available in your evals. `item` and `sample` are both defined when using this\n * data source config.\n */\n export interface Logs {\n /**\n * The json schema for the run data source items. Learn how to build JSON schemas\n * [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `logs`.\n */\n type: 'logs';\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n }\n\n /**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\n export interface EvalGraderTextSimilarity extends GraderModelsAPI.TextSimilarityGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold: number;\n }\n\n /**\n * A PythonGrader object that runs a python script on the input.\n */\n export interface EvalGraderPython extends GraderModelsAPI.PythonGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n\n /**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\n export interface EvalGraderScoreModel extends GraderModelsAPI.ScoreModelGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n}\n\nexport interface EvalDeleteResponse {\n deleted: boolean;\n\n eval_id: string;\n\n object: string;\n}\n\nexport interface EvalCreateParams {\n /**\n * The configuration for the data source used for the evaluation runs. Dictates the\n * schema of the data used in the evaluation.\n */\n data_source_config: EvalCreateParams.Custom | EvalCreateParams.Logs | EvalCreateParams.StoredCompletions;\n\n /**\n * A list of graders for all eval runs in this group. Graders can reference\n * variables in the data source using double curly braces notation, like\n * `{{item.variable_name}}`. To reference the model's output, use the `sample`\n * namespace (ie, `{{sample.output_text}}`).\n */\n testing_criteria: Array<\n | EvalCreateParams.LabelModel\n | GraderModelsAPI.StringCheckGrader\n | EvalCreateParams.TextSimilarity\n | EvalCreateParams.Python\n | EvalCreateParams.ScoreModel\n >;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The name of the evaluation.\n */\n name?: string;\n}\n\nexport namespace EvalCreateParams {\n /**\n * A CustomDataSourceConfig object that defines the schema for the data source used\n * for the evaluation runs. This schema is used to define the shape of the data\n * that will be:\n *\n * - Used to define your testing criteria and\n * - What data is required when creating a run\n */\n export interface Custom {\n /**\n * The json schema for each row in the data source.\n */\n item_schema: Record<string, unknown>;\n\n /**\n * The type of data source. Always `custom`.\n */\n type: 'custom';\n\n /**\n * Whether the eval should expect you to populate the sample namespace (ie, by\n * generating responses off of your data source)\n */\n include_sample_schema?: boolean;\n }\n\n /**\n * A data source config which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc.\n */\n export interface Logs {\n /**\n * The type of data source. Always `logs`.\n */\n type: 'logs';\n\n /**\n * Metadata filters for the logs data source.\n */\n metadata?: Record<string, unknown>;\n }\n\n /**\n * @deprecated Deprecated in favor of LogsDataSourceConfig.\n */\n export interface StoredCompletions {\n /**\n * The type of data source. Always `stored_completions`.\n */\n type: 'stored_completions';\n\n /**\n * Metadata filters for the stored completions data source.\n */\n metadata?: Record<string, unknown>;\n }\n\n /**\n * A LabelModelGrader object which uses a model to assign labels to each item in\n * the evaluation.\n */\n export interface LabelModel {\n /**\n * A list of chat messages forming the prompt or context. May include variable\n * references to the `item` namespace, ie {{item.name}}.\n */\n input: Array<LabelModel.SimpleInputMessage | LabelModel.EvalItem>;\n\n /**\n * The labels to classify to each item in the evaluation.\n */\n labels: Array<string>;\n\n /**\n * The model to use for the evaluation. Must support structured outputs.\n */\n model: string;\n\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The labels that indicate a passing result. Must be a subset of labels.\n */\n passing_labels: Array<string>;\n\n /**\n * The object type, which is always `label_model`.\n */\n type: 'label_model';\n }\n\n export namespace LabelModel {\n export interface SimpleInputMessage {\n /**\n * The content of the message.\n */\n content: string;\n\n /**\n * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n */\n role: string;\n }\n\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface EvalItem {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | EvalItem.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace EvalItem {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n }\n\n /**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\n export interface TextSimilarity extends GraderModelsAPI.TextSimilarityGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold: number;\n }\n\n /**\n * A PythonGrader object that runs a python script on the input.\n */\n export interface Python extends GraderModelsAPI.PythonGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n\n /**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\n export interface ScoreModel extends GraderModelsAPI.ScoreModelGrader {\n /**\n * The threshold for the score.\n */\n pass_threshold?: number;\n }\n}\n\nexport interface EvalUpdateParams {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * Rename the evaluation.\n */\n name?: string;\n}\n\nexport interface EvalListParams extends CursorPageParams {\n /**\n * Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for\n * descending order.\n */\n order?: 'asc' | 'desc';\n\n /**\n * Evals can be ordered by creation time or last updated time. Use `created_at` for\n * creation time or `updated_at` for last updated time.\n */\n order_by?: 'created_at' | 'updated_at';\n}\n\nEvals.EvalListResponsesPage = EvalListResponsesPage;\nEvals.Runs = Runs;\nEvals.RunListResponsesPage = RunListResponsesPage;\n\nexport declare namespace Evals {\n export {\n type EvalCustomDataSourceConfig as EvalCustomDataSourceConfig,\n type EvalStoredCompletionsDataSourceConfig as EvalStoredCompletionsDataSourceConfig,\n type EvalCreateResponse as EvalCreateResponse,\n type EvalRetrieveResponse as EvalRetrieveResponse,\n type EvalUpdateResponse as EvalUpdateResponse,\n type EvalListResponse as EvalListResponse,\n type EvalDeleteResponse as EvalDeleteResponse,\n EvalListResponsesPage as EvalListResponsesPage,\n type EvalCreateParams as EvalCreateParams,\n type EvalUpdateParams as EvalUpdateParams,\n type EvalListParams as EvalListParams,\n };\n\n export {\n Runs as Runs,\n type CreateEvalCompletionsRunDataSource as CreateEvalCompletionsRunDataSource,\n type CreateEvalJSONLRunDataSource as CreateEvalJSONLRunDataSource,\n type EvalAPIError as EvalAPIError,\n type RunCreateResponse as RunCreateResponse,\n type RunRetrieveResponse as RunRetrieveResponse,\n type RunListResponse as RunListResponse,\n type RunDeleteResponse as RunDeleteResponse,\n type RunCancelResponse as RunCancelResponse,\n RunListResponsesPage as RunListResponsesPage,\n type RunCreateParams as RunCreateParams,\n type RunListParams as RunListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport { isRequestOptions } from '../core';\nimport { sleep } from '../core';\nimport { APIConnectionTimeoutError } from '../error';\nimport * as Core from '../core';\nimport { CursorPage, type CursorPageParams } from '../pagination';\nimport { type Response } from '../_shims/index';\n\nexport class Files extends APIResource {\n /**\n * Upload a file that can be used across various endpoints. Individual files can be\n * up to 512 MB, and the size of all files uploaded by one organization can be up\n * to 100 GB.\n *\n * The Assistants API supports files up to 2 million tokens and of specific file\n * types. See the\n * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for\n * details.\n *\n * The Fine-tuning API only supports `.jsonl` files. The input also has certain\n * required formats for fine-tuning\n * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or\n * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)\n * models.\n *\n * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also\n * has a specific required\n * [format](https://platform.openai.com/docs/api-reference/batch/request-input).\n *\n * Please [contact us](https://help.openai.com/) if you need to increase these\n * storage limits.\n */\n create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise<FileObject> {\n return this._client.post('/files', Core.multipartFormRequestOptions({ body, ...options }));\n }\n\n /**\n * Returns information about a specific file.\n */\n retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise<FileObject> {\n return this._client.get(`/files/${fileId}`, options);\n }\n\n /**\n * Returns a list of files.\n */\n list(query?: FileListParams, options?: Core.RequestOptions): Core.PagePromise<FileObjectsPage, FileObject>;\n list(options?: Core.RequestOptions): Core.PagePromise<FileObjectsPage, FileObject>;\n list(\n query: FileListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<FileObjectsPage, FileObject> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });\n }\n\n /**\n * Delete a file.\n */\n del(fileId: string, options?: Core.RequestOptions): Core.APIPromise<FileDeleted> {\n return this._client.delete(`/files/${fileId}`, options);\n }\n\n /**\n * Returns the contents of the specified file.\n */\n content(fileId: string, options?: Core.RequestOptions): Core.APIPromise<Response> {\n return this._client.get(`/files/${fileId}/content`, {\n ...options,\n headers: { Accept: 'application/binary', ...options?.headers },\n __binaryResponse: true,\n });\n }\n\n /**\n * Returns the contents of the specified file.\n *\n * @deprecated The `.content()` method should be used instead\n */\n retrieveContent(fileId: string, options?: Core.RequestOptions): Core.APIPromise<string> {\n return this._client.get(`/files/${fileId}/content`, options);\n }\n\n /**\n * Waits for the given file to be processed, default timeout is 30 mins.\n */\n async waitForProcessing(\n id: string,\n { pollInterval = 5000, maxWait = 30 * 60 * 1000 }: { pollInterval?: number; maxWait?: number } = {},\n ): Promise<FileObject> {\n const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);\n\n const start = Date.now();\n let file = await this.retrieve(id);\n\n while (!file.status || !TERMINAL_STATES.has(file.status)) {\n await sleep(pollInterval);\n\n file = await this.retrieve(id);\n if (Date.now() - start > maxWait) {\n throw new APIConnectionTimeoutError({\n message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,\n });\n }\n }\n\n return file;\n }\n}\n\nexport class FileObjectsPage extends CursorPage<FileObject> {}\n\nexport type FileContent = string;\n\nexport interface FileDeleted {\n id: string;\n\n deleted: boolean;\n\n object: 'file';\n}\n\n/**\n * The `File` object represents a document that has been uploaded to OpenAI.\n */\nexport interface FileObject {\n /**\n * The file identifier, which can be referenced in the API endpoints.\n */\n id: string;\n\n /**\n * The size of the file, in bytes.\n */\n bytes: number;\n\n /**\n * The Unix timestamp (in seconds) for when the file was created.\n */\n created_at: number;\n\n /**\n * The name of the file.\n */\n filename: string;\n\n /**\n * The object type, which is always `file`.\n */\n object: 'file';\n\n /**\n * The intended purpose of the file. Supported values are `assistants`,\n * `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`\n * and `vision`.\n */\n purpose:\n | 'assistants'\n | 'assistants_output'\n | 'batch'\n | 'batch_output'\n | 'fine-tune'\n | 'fine-tune-results'\n | 'vision';\n\n /**\n * @deprecated Deprecated. The current status of the file, which can be either\n * `uploaded`, `processed`, or `error`.\n */\n status: 'uploaded' | 'processed' | 'error';\n\n /**\n * The Unix timestamp (in seconds) for when the file will expire.\n */\n expires_at?: number;\n\n /**\n * @deprecated Deprecated. For details on why a fine-tuning training file failed\n * validation, see the `error` field on `fine_tuning.job`.\n */\n status_details?: string;\n}\n\n/**\n * The intended purpose of the uploaded file. One of: - `assistants`: Used in the\n * Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for\n * fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:\n * Flexible file type for any purpose - `evals`: Used for eval data sets\n */\nexport type FilePurpose = 'assistants' | 'batch' | 'fine-tune' | 'vision' | 'user_data' | 'evals';\n\nexport interface FileCreateParams {\n /**\n * The File object (not file name) to be uploaded.\n */\n file: Core.Uploadable;\n\n /**\n * The intended purpose of the uploaded file. One of: - `assistants`: Used in the\n * Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for\n * fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:\n * Flexible file type for any purpose - `evals`: Used for eval data sets\n */\n purpose: FilePurpose;\n}\n\nexport interface FileListParams extends CursorPageParams {\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n\n /**\n * Only return files with the given purpose.\n */\n purpose?: string;\n}\n\nFiles.FileObjectsPage = FileObjectsPage;\n\nexport declare namespace Files {\n export {\n type FileContent as FileContent,\n type FileDeleted as FileDeleted,\n type FileObject as FileObject,\n type FilePurpose as FilePurpose,\n FileObjectsPage as FileObjectsPage,\n type FileCreateParams as FileCreateParams,\n type FileListParams as FileListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as GraderModelsAPI from '../graders/grader-models';\n\nexport class Methods extends APIResource {}\n\n/**\n * The hyperparameters used for the DPO fine-tuning job.\n */\nexport interface DpoHyperparameters {\n /**\n * Number of examples in each batch. A larger batch size means that model\n * parameters are updated less frequently, but with lower variance.\n */\n batch_size?: 'auto' | number;\n\n /**\n * The beta value for the DPO method. A higher beta value will increase the weight\n * of the penalty between the policy and reference model.\n */\n beta?: 'auto' | number;\n\n /**\n * Scaling factor for the learning rate. A smaller learning rate may be useful to\n * avoid overfitting.\n */\n learning_rate_multiplier?: 'auto' | number;\n\n /**\n * The number of epochs to train the model for. An epoch refers to one full cycle\n * through the training dataset.\n */\n n_epochs?: 'auto' | number;\n}\n\n/**\n * Configuration for the DPO fine-tuning method.\n */\nexport interface DpoMethod {\n /**\n * The hyperparameters used for the DPO fine-tuning job.\n */\n hyperparameters?: DpoHyperparameters;\n}\n\n/**\n * The hyperparameters used for the reinforcement fine-tuning job.\n */\nexport interface ReinforcementHyperparameters {\n /**\n * Number of examples in each batch. A larger batch size means that model\n * parameters are updated less frequently, but with lower variance.\n */\n batch_size?: 'auto' | number;\n\n /**\n * Multiplier on amount of compute used for exploring search space during training.\n */\n compute_multiplier?: 'auto' | number;\n\n /**\n * The number of training steps between evaluation runs.\n */\n eval_interval?: 'auto' | number;\n\n /**\n * Number of evaluation samples to generate per training step.\n */\n eval_samples?: 'auto' | number;\n\n /**\n * Scaling factor for the learning rate. A smaller learning rate may be useful to\n * avoid overfitting.\n */\n learning_rate_multiplier?: 'auto' | number;\n\n /**\n * The number of epochs to train the model for. An epoch refers to one full cycle\n * through the training dataset.\n */\n n_epochs?: 'auto' | number;\n\n /**\n * Level of reasoning effort.\n */\n reasoning_effort?: 'default' | 'low' | 'medium' | 'high';\n}\n\n/**\n * Configuration for the reinforcement fine-tuning method.\n */\nexport interface ReinforcementMethod {\n /**\n * The grader used for the fine-tuning job.\n */\n grader:\n | GraderModelsAPI.StringCheckGrader\n | GraderModelsAPI.TextSimilarityGrader\n | GraderModelsAPI.PythonGrader\n | GraderModelsAPI.ScoreModelGrader\n | GraderModelsAPI.MultiGrader;\n\n /**\n * The hyperparameters used for the reinforcement fine-tuning job.\n */\n hyperparameters?: ReinforcementHyperparameters;\n}\n\n/**\n * The hyperparameters used for the fine-tuning job.\n */\nexport interface SupervisedHyperparameters {\n /**\n * Number of examples in each batch. A larger batch size means that model\n * parameters are updated less frequently, but with lower variance.\n */\n batch_size?: 'auto' | number;\n\n /**\n * Scaling factor for the learning rate. A smaller learning rate may be useful to\n * avoid overfitting.\n */\n learning_rate_multiplier?: 'auto' | number;\n\n /**\n * The number of epochs to train the model for. An epoch refers to one full cycle\n * through the training dataset.\n */\n n_epochs?: 'auto' | number;\n}\n\n/**\n * Configuration for the supervised fine-tuning method.\n */\nexport interface SupervisedMethod {\n /**\n * The hyperparameters used for the fine-tuning job.\n */\n hyperparameters?: SupervisedHyperparameters;\n}\n\nexport declare namespace Methods {\n export {\n type DpoHyperparameters as DpoHyperparameters,\n type DpoMethod as DpoMethod,\n type ReinforcementHyperparameters as ReinforcementHyperparameters,\n type ReinforcementMethod as ReinforcementMethod,\n type SupervisedHyperparameters as SupervisedHyperparameters,\n type SupervisedMethod as SupervisedMethod,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as Core from '../../../core';\nimport * as GraderModelsAPI from '../../graders/grader-models';\n\nexport class Graders extends APIResource {\n /**\n * Run a grader.\n *\n * @example\n * ```ts\n * const response = await client.fineTuning.alpha.graders.run({\n * grader: {\n * input: 'input',\n * name: 'name',\n * operation: 'eq',\n * reference: 'reference',\n * type: 'string_check',\n * },\n * model_sample: 'model_sample',\n * reference_answer: 'string',\n * });\n * ```\n */\n run(body: GraderRunParams, options?: Core.RequestOptions): Core.APIPromise<GraderRunResponse> {\n return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options });\n }\n\n /**\n * Validate a grader.\n *\n * @example\n * ```ts\n * const response =\n * await client.fineTuning.alpha.graders.validate({\n * grader: {\n * input: 'input',\n * name: 'name',\n * operation: 'eq',\n * reference: 'reference',\n * type: 'string_check',\n * },\n * });\n * ```\n */\n validate(\n body: GraderValidateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<GraderValidateResponse> {\n return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options });\n }\n}\n\nexport interface GraderRunResponse {\n metadata: GraderRunResponse.Metadata;\n\n model_grader_token_usage_per_model: Record<string, unknown>;\n\n reward: number;\n\n sub_rewards: Record<string, unknown>;\n}\n\nexport namespace GraderRunResponse {\n export interface Metadata {\n errors: Metadata.Errors;\n\n execution_time: number;\n\n name: string;\n\n sampled_model_name: string | null;\n\n scores: Record<string, unknown>;\n\n token_usage: number | null;\n\n type: string;\n }\n\n export namespace Metadata {\n export interface Errors {\n formula_parse_error: boolean;\n\n invalid_variable_error: boolean;\n\n model_grader_parse_error: boolean;\n\n model_grader_refusal_error: boolean;\n\n model_grader_server_error: boolean;\n\n model_grader_server_error_details: string | null;\n\n other_error: boolean;\n\n python_grader_runtime_error: boolean;\n\n python_grader_runtime_error_details: string | null;\n\n python_grader_server_error: boolean;\n\n python_grader_server_error_type: string | null;\n\n sample_parse_error: boolean;\n\n truncated_observation_error: boolean;\n\n unresponsive_reward_error: boolean;\n }\n }\n}\n\nexport interface GraderValidateResponse {\n /**\n * The grader used for the fine-tuning job.\n */\n grader?:\n | GraderModelsAPI.StringCheckGrader\n | GraderModelsAPI.TextSimilarityGrader\n | GraderModelsAPI.PythonGrader\n | GraderModelsAPI.ScoreModelGrader\n | GraderModelsAPI.MultiGrader;\n}\n\nexport interface GraderRunParams {\n /**\n * The grader used for the fine-tuning job.\n */\n grader:\n | GraderModelsAPI.StringCheckGrader\n | GraderModelsAPI.TextSimilarityGrader\n | GraderModelsAPI.PythonGrader\n | GraderModelsAPI.ScoreModelGrader\n | GraderModelsAPI.MultiGrader;\n\n /**\n * The model sample to be evaluated.\n */\n model_sample: string;\n\n /**\n * The reference answer for the evaluation.\n */\n reference_answer: string | unknown | Array<unknown> | number;\n}\n\nexport interface GraderValidateParams {\n /**\n * The grader used for the fine-tuning job.\n */\n grader:\n | GraderModelsAPI.StringCheckGrader\n | GraderModelsAPI.TextSimilarityGrader\n | GraderModelsAPI.PythonGrader\n | GraderModelsAPI.ScoreModelGrader\n | GraderModelsAPI.MultiGrader;\n}\n\nexport declare namespace Graders {\n export {\n type GraderRunResponse as GraderRunResponse,\n type GraderValidateResponse as GraderValidateResponse,\n type GraderRunParams as GraderRunParams,\n type GraderValidateParams as GraderValidateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as GradersAPI from './graders';\nimport {\n GraderRunParams,\n GraderRunResponse,\n GraderValidateParams,\n GraderValidateResponse,\n Graders,\n} from './graders';\n\nexport class Alpha extends APIResource {\n graders: GradersAPI.Graders = new GradersAPI.Graders(this._client);\n}\n\nAlpha.Graders = Graders;\n\nexport declare namespace Alpha {\n export {\n Graders as Graders,\n type GraderRunResponse as GraderRunResponse,\n type GraderValidateResponse as GraderValidateResponse,\n type GraderRunParams as GraderRunParams,\n type GraderValidateParams as GraderValidateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport { Page } from '../../../pagination';\n\nexport class Permissions extends APIResource {\n /**\n * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).\n *\n * This enables organization owners to share fine-tuned models with other projects\n * in their organization.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(\n * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',\n * { project_ids: ['string'] },\n * )) {\n * // ...\n * }\n * ```\n */\n create(\n fineTunedModelCheckpoint: string,\n body: PermissionCreateParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<PermissionCreateResponsesPage, PermissionCreateResponse> {\n return this._client.getAPIList(\n `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`,\n PermissionCreateResponsesPage,\n { body, method: 'post', ...options },\n );\n }\n\n /**\n * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n *\n * Organization owners can use this endpoint to view all permissions for a\n * fine-tuned model checkpoint.\n *\n * @example\n * ```ts\n * const permission =\n * await client.fineTuning.checkpoints.permissions.retrieve(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n retrieve(\n fineTunedModelCheckpoint: string,\n query?: PermissionRetrieveParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<PermissionRetrieveResponse>;\n retrieve(\n fineTunedModelCheckpoint: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<PermissionRetrieveResponse>;\n retrieve(\n fineTunedModelCheckpoint: string,\n query: PermissionRetrieveParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.APIPromise<PermissionRetrieveResponse> {\n if (isRequestOptions(query)) {\n return this.retrieve(fineTunedModelCheckpoint, {}, query);\n }\n return this._client.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {\n query,\n ...options,\n });\n }\n\n /**\n * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n *\n * Organization owners can use this endpoint to delete a permission for a\n * fine-tuned model checkpoint.\n *\n * @example\n * ```ts\n * const permission =\n * await client.fineTuning.checkpoints.permissions.del(\n * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',\n * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB',\n * );\n * ```\n */\n del(\n fineTunedModelCheckpoint: string,\n permissionId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<PermissionDeleteResponse> {\n return this._client.delete(\n `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`,\n options,\n );\n }\n}\n\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class PermissionCreateResponsesPage extends Page<PermissionCreateResponse> {}\n\n/**\n * The `checkpoint.permission` object represents a permission for a fine-tuned\n * model checkpoint.\n */\nexport interface PermissionCreateResponse {\n /**\n * The permission identifier, which can be referenced in the API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the permission was created.\n */\n created_at: number;\n\n /**\n * The object type, which is always \"checkpoint.permission\".\n */\n object: 'checkpoint.permission';\n\n /**\n * The project identifier that the permission is for.\n */\n project_id: string;\n}\n\nexport interface PermissionRetrieveResponse {\n data: Array<PermissionRetrieveResponse.Data>;\n\n has_more: boolean;\n\n object: 'list';\n\n first_id?: string | null;\n\n last_id?: string | null;\n}\n\nexport namespace PermissionRetrieveResponse {\n /**\n * The `checkpoint.permission` object represents a permission for a fine-tuned\n * model checkpoint.\n */\n export interface Data {\n /**\n * The permission identifier, which can be referenced in the API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the permission was created.\n */\n created_at: number;\n\n /**\n * The object type, which is always \"checkpoint.permission\".\n */\n object: 'checkpoint.permission';\n\n /**\n * The project identifier that the permission is for.\n */\n project_id: string;\n }\n}\n\nexport interface PermissionDeleteResponse {\n /**\n * The ID of the fine-tuned model checkpoint permission that was deleted.\n */\n id: string;\n\n /**\n * Whether the fine-tuned model checkpoint permission was successfully deleted.\n */\n deleted: boolean;\n\n /**\n * The object type, which is always \"checkpoint.permission\".\n */\n object: 'checkpoint.permission';\n}\n\nexport interface PermissionCreateParams {\n /**\n * The project identifiers to grant access to.\n */\n project_ids: Array<string>;\n}\n\nexport interface PermissionRetrieveParams {\n /**\n * Identifier for the last permission ID from the previous pagination request.\n */\n after?: string;\n\n /**\n * Number of permissions to retrieve.\n */\n limit?: number;\n\n /**\n * The order in which to retrieve permissions.\n */\n order?: 'ascending' | 'descending';\n\n /**\n * The ID of the project to get permissions for.\n */\n project_id?: string;\n}\n\nPermissions.PermissionCreateResponsesPage = PermissionCreateResponsesPage;\n\nexport declare namespace Permissions {\n export {\n type PermissionCreateResponse as PermissionCreateResponse,\n type PermissionRetrieveResponse as PermissionRetrieveResponse,\n type PermissionDeleteResponse as PermissionDeleteResponse,\n PermissionCreateResponsesPage as PermissionCreateResponsesPage,\n type PermissionCreateParams as PermissionCreateParams,\n type PermissionRetrieveParams as PermissionRetrieveParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport * as PermissionsAPI from './permissions';\nimport {\n PermissionCreateParams,\n PermissionCreateResponse,\n PermissionCreateResponsesPage,\n PermissionDeleteResponse,\n PermissionRetrieveParams,\n PermissionRetrieveResponse,\n Permissions,\n} from './permissions';\n\nexport class Checkpoints extends APIResource {\n permissions: PermissionsAPI.Permissions = new PermissionsAPI.Permissions(this._client);\n}\n\nCheckpoints.Permissions = Permissions;\nCheckpoints.PermissionCreateResponsesPage = PermissionCreateResponsesPage;\n\nexport declare namespace Checkpoints {\n export {\n Permissions as Permissions,\n type PermissionCreateResponse as PermissionCreateResponse,\n type PermissionRetrieveResponse as PermissionRetrieveResponse,\n type PermissionDeleteResponse as PermissionDeleteResponse,\n PermissionCreateResponsesPage as PermissionCreateResponsesPage,\n type PermissionCreateParams as PermissionCreateParams,\n type PermissionRetrieveParams as PermissionRetrieveParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\n\nexport class Checkpoints extends APIResource {\n /**\n * List checkpoints for a fine-tuning job.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n fineTuningJobId: string,\n query?: CheckpointListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobCheckpointsPage, FineTuningJobCheckpoint>;\n list(\n fineTuningJobId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobCheckpointsPage, FineTuningJobCheckpoint>;\n list(\n fineTuningJobId: string,\n query: CheckpointListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobCheckpointsPage, FineTuningJobCheckpoint> {\n if (isRequestOptions(query)) {\n return this.list(fineTuningJobId, {}, query);\n }\n return this._client.getAPIList(\n `/fine_tuning/jobs/${fineTuningJobId}/checkpoints`,\n FineTuningJobCheckpointsPage,\n { query, ...options },\n );\n }\n}\n\nexport class FineTuningJobCheckpointsPage extends CursorPage<FineTuningJobCheckpoint> {}\n\n/**\n * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a\n * fine-tuning job that is ready to use.\n */\nexport interface FineTuningJobCheckpoint {\n /**\n * The checkpoint identifier, which can be referenced in the API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the checkpoint was created.\n */\n created_at: number;\n\n /**\n * The name of the fine-tuned checkpoint model that is created.\n */\n fine_tuned_model_checkpoint: string;\n\n /**\n * The name of the fine-tuning job that this checkpoint was created from.\n */\n fine_tuning_job_id: string;\n\n /**\n * Metrics at the step number during the fine-tuning job.\n */\n metrics: FineTuningJobCheckpoint.Metrics;\n\n /**\n * The object type, which is always \"fine_tuning.job.checkpoint\".\n */\n object: 'fine_tuning.job.checkpoint';\n\n /**\n * The step number that the checkpoint was created at.\n */\n step_number: number;\n}\n\nexport namespace FineTuningJobCheckpoint {\n /**\n * Metrics at the step number during the fine-tuning job.\n */\n export interface Metrics {\n full_valid_loss?: number;\n\n full_valid_mean_token_accuracy?: number;\n\n step?: number;\n\n train_loss?: number;\n\n train_mean_token_accuracy?: number;\n\n valid_loss?: number;\n\n valid_mean_token_accuracy?: number;\n }\n}\n\nexport interface CheckpointListParams extends CursorPageParams {}\n\nCheckpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;\n\nexport declare namespace Checkpoints {\n export {\n type FineTuningJobCheckpoint as FineTuningJobCheckpoint,\n FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage,\n type CheckpointListParams as CheckpointListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../resource';\nimport { isRequestOptions } from '../../../core';\nimport * as Core from '../../../core';\nimport * as MethodsAPI from '../methods';\nimport * as CheckpointsAPI from './checkpoints';\nimport {\n CheckpointListParams,\n Checkpoints,\n FineTuningJobCheckpoint,\n FineTuningJobCheckpointsPage,\n} from './checkpoints';\nimport { CursorPage, type CursorPageParams } from '../../../pagination';\n\nexport class Jobs extends APIResource {\n checkpoints: CheckpointsAPI.Checkpoints = new CheckpointsAPI.Checkpoints(this._client);\n\n /**\n * Creates a fine-tuning job which begins the process of creating a new model from\n * a given dataset.\n *\n * Response includes details of the enqueued job including job status and the name\n * of the fine-tuned models once complete.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.create({\n * model: 'gpt-4o-mini',\n * training_file: 'file-abc123',\n * });\n * ```\n */\n create(body: JobCreateParams, options?: Core.RequestOptions): Core.APIPromise<FineTuningJob> {\n return this._client.post('/fine_tuning/jobs', { body, ...options });\n }\n\n /**\n * Get info about a fine-tuning job.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.retrieve(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n retrieve(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise<FineTuningJob> {\n return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);\n }\n\n /**\n * List your organization's fine-tuning jobs\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fineTuningJob of client.fineTuning.jobs.list()) {\n * // ...\n * }\n * ```\n */\n list(\n query?: JobListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobsPage, FineTuningJob>;\n list(options?: Core.RequestOptions): Core.PagePromise<FineTuningJobsPage, FineTuningJob>;\n list(\n query: JobListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobsPage, FineTuningJob> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });\n }\n\n /**\n * Immediately cancel a fine-tune job.\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.cancel(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n cancel(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise<FineTuningJob> {\n return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);\n }\n\n /**\n * Get status updates for a fine-tuning job.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * )) {\n * // ...\n * }\n * ```\n */\n listEvents(\n fineTuningJobId: string,\n query?: JobListEventsParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobEventsPage, FineTuningJobEvent>;\n listEvents(\n fineTuningJobId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobEventsPage, FineTuningJobEvent>;\n listEvents(\n fineTuningJobId: string,\n query: JobListEventsParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<FineTuningJobEventsPage, FineTuningJobEvent> {\n if (isRequestOptions(query)) {\n return this.listEvents(fineTuningJobId, {}, query);\n }\n return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {\n query,\n ...options,\n });\n }\n\n /**\n * Pause a fine-tune job.\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.pause(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n pause(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise<FineTuningJob> {\n return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`, options);\n }\n\n /**\n * Resume a fine-tune job.\n *\n * @example\n * ```ts\n * const fineTuningJob = await client.fineTuning.jobs.resume(\n * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n * );\n * ```\n */\n resume(fineTuningJobId: string, options?: Core.RequestOptions): Core.APIPromise<FineTuningJob> {\n return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`, options);\n }\n}\n\nexport class FineTuningJobsPage extends CursorPage<FineTuningJob> {}\n\nexport class FineTuningJobEventsPage extends CursorPage<FineTuningJobEvent> {}\n\n/**\n * The `fine_tuning.job` object represents a fine-tuning job that has been created\n * through the API.\n */\nexport interface FineTuningJob {\n /**\n * The object identifier, which can be referenced in the API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the fine-tuning job was created.\n */\n created_at: number;\n\n /**\n * For fine-tuning jobs that have `failed`, this will contain more information on\n * the cause of the failure.\n */\n error: FineTuningJob.Error | null;\n\n /**\n * The name of the fine-tuned model that is being created. The value will be null\n * if the fine-tuning job is still running.\n */\n fine_tuned_model: string | null;\n\n /**\n * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The\n * value will be null if the fine-tuning job is still running.\n */\n finished_at: number | null;\n\n /**\n * The hyperparameters used for the fine-tuning job. This value will only be\n * returned when running `supervised` jobs.\n */\n hyperparameters: FineTuningJob.Hyperparameters;\n\n /**\n * The base model that is being fine-tuned.\n */\n model: string;\n\n /**\n * The object type, which is always \"fine_tuning.job\".\n */\n object: 'fine_tuning.job';\n\n /**\n * The organization that owns the fine-tuning job.\n */\n organization_id: string;\n\n /**\n * The compiled results file ID(s) for the fine-tuning job. You can retrieve the\n * results with the\n * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).\n */\n result_files: Array<string>;\n\n /**\n * The seed used for the fine-tuning job.\n */\n seed: number;\n\n /**\n * The current status of the fine-tuning job, which can be either\n * `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.\n */\n status: 'validating_files' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';\n\n /**\n * The total number of billable tokens processed by this fine-tuning job. The value\n * will be null if the fine-tuning job is still running.\n */\n trained_tokens: number | null;\n\n /**\n * The file ID used for training. You can retrieve the training data with the\n * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).\n */\n training_file: string;\n\n /**\n * The file ID used for validation. You can retrieve the validation results with\n * the\n * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).\n */\n validation_file: string | null;\n\n /**\n * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to\n * finish. The value will be null if the fine-tuning job is not running.\n */\n estimated_finish?: number | null;\n\n /**\n * A list of integrations to enable for this fine-tuning job.\n */\n integrations?: Array<FineTuningJobWandbIntegrationObject> | null;\n\n /**\n * The method used for fine-tuning.\n */\n method?: FineTuningJob.Method;\n}\n\nexport namespace FineTuningJob {\n /**\n * For fine-tuning jobs that have `failed`, this will contain more information on\n * the cause of the failure.\n */\n export interface Error {\n /**\n * A machine-readable error code.\n */\n code: string;\n\n /**\n * A human-readable error message.\n */\n message: string;\n\n /**\n * The parameter that was invalid, usually `training_file` or `validation_file`.\n * This field will be null if the failure was not parameter-specific.\n */\n param: string | null;\n }\n\n /**\n * The hyperparameters used for the fine-tuning job. This value will only be\n * returned when running `supervised` jobs.\n */\n export interface Hyperparameters {\n /**\n * Number of examples in each batch. A larger batch size means that model\n * parameters are updated less frequently, but with lower variance.\n */\n batch_size?: unknown | 'auto' | number | null;\n\n /**\n * Scaling factor for the learning rate. A smaller learning rate may be useful to\n * avoid overfitting.\n */\n learning_rate_multiplier?: 'auto' | number;\n\n /**\n * The number of epochs to train the model for. An epoch refers to one full cycle\n * through the training dataset.\n */\n n_epochs?: 'auto' | number;\n }\n\n /**\n * The method used for fine-tuning.\n */\n export interface Method {\n /**\n * The type of method. Is either `supervised`, `dpo`, or `reinforcement`.\n */\n type: 'supervised' | 'dpo' | 'reinforcement';\n\n /**\n * Configuration for the DPO fine-tuning method.\n */\n dpo?: MethodsAPI.DpoMethod;\n\n /**\n * Configuration for the reinforcement fine-tuning method.\n */\n reinforcement?: MethodsAPI.ReinforcementMethod;\n\n /**\n * Configuration for the supervised fine-tuning method.\n */\n supervised?: MethodsAPI.SupervisedMethod;\n }\n}\n\n/**\n * Fine-tuning job event object\n */\nexport interface FineTuningJobEvent {\n /**\n * The object identifier.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the fine-tuning job was created.\n */\n created_at: number;\n\n /**\n * The log level of the event.\n */\n level: 'info' | 'warn' | 'error';\n\n /**\n * The message of the event.\n */\n message: string;\n\n /**\n * The object type, which is always \"fine_tuning.job.event\".\n */\n object: 'fine_tuning.job.event';\n\n /**\n * The data associated with the event.\n */\n data?: unknown;\n\n /**\n * The type of event.\n */\n type?: 'message' | 'metrics';\n}\n\nexport type FineTuningJobIntegration = FineTuningJobWandbIntegrationObject;\n\n/**\n * The settings for your integration with Weights and Biases. This payload\n * specifies the project that metrics will be sent to. Optionally, you can set an\n * explicit display name for your run, add tags to your run, and set a default\n * entity (team, username, etc) to be associated with your run.\n */\nexport interface FineTuningJobWandbIntegration {\n /**\n * The name of the project that the new run will be created under.\n */\n project: string;\n\n /**\n * The entity to use for the run. This allows you to set the team or username of\n * the WandB user that you would like associated with the run. If not set, the\n * default entity for the registered WandB API key is used.\n */\n entity?: string | null;\n\n /**\n * A display name to set for the run. If not set, we will use the Job ID as the\n * name.\n */\n name?: string | null;\n\n /**\n * A list of tags to be attached to the newly created run. These tags are passed\n * through directly to WandB. Some default tags are generated by OpenAI:\n * \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n */\n tags?: Array<string>;\n}\n\nexport interface FineTuningJobWandbIntegrationObject {\n /**\n * The type of the integration being enabled for the fine-tuning job\n */\n type: 'wandb';\n\n /**\n * The settings for your integration with Weights and Biases. This payload\n * specifies the project that metrics will be sent to. Optionally, you can set an\n * explicit display name for your run, add tags to your run, and set a default\n * entity (team, username, etc) to be associated with your run.\n */\n wandb: FineTuningJobWandbIntegration;\n}\n\nexport interface JobCreateParams {\n /**\n * The name of the model to fine-tune. You can select one of the\n * [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned).\n */\n model: (string & {}) | 'babbage-002' | 'davinci-002' | 'gpt-3.5-turbo' | 'gpt-4o-mini';\n\n /**\n * The ID of an uploaded file that contains training data.\n *\n * See [upload file](https://platform.openai.com/docs/api-reference/files/create)\n * for how to upload a file.\n *\n * Your dataset must be formatted as a JSONL file. Additionally, you must upload\n * your file with the purpose `fine-tune`.\n *\n * The contents of the file should differ depending on if the model uses the\n * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input),\n * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)\n * format, or if the fine-tuning method uses the\n * [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input)\n * format.\n *\n * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning)\n * for more details.\n */\n training_file: string;\n\n /**\n * @deprecated The hyperparameters used for the fine-tuning job. This value is now\n * deprecated in favor of `method`, and should be passed in under the `method`\n * parameter.\n */\n hyperparameters?: JobCreateParams.Hyperparameters;\n\n /**\n * A list of integrations to enable for your fine-tuning job.\n */\n integrations?: Array<JobCreateParams.Integration> | null;\n\n /**\n * The method used for fine-tuning.\n */\n method?: JobCreateParams.Method;\n\n /**\n * The seed controls the reproducibility of the job. Passing in the same seed and\n * job parameters should produce the same results, but may differ in rare cases. If\n * a seed is not specified, one will be generated for you.\n */\n seed?: number | null;\n\n /**\n * A string of up to 64 characters that will be added to your fine-tuned model\n * name.\n *\n * For example, a `suffix` of \"custom-model-name\" would produce a model name like\n * `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n */\n suffix?: string | null;\n\n /**\n * The ID of an uploaded file that contains validation data.\n *\n * If you provide this file, the data is used to generate validation metrics\n * periodically during fine-tuning. These metrics can be viewed in the fine-tuning\n * results file. The same data should not be present in both train and validation\n * files.\n *\n * Your dataset must be formatted as a JSONL file. You must upload your file with\n * the purpose `fine-tune`.\n *\n * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning)\n * for more details.\n */\n validation_file?: string | null;\n}\n\nexport namespace JobCreateParams {\n /**\n * @deprecated The hyperparameters used for the fine-tuning job. This value is now\n * deprecated in favor of `method`, and should be passed in under the `method`\n * parameter.\n */\n export interface Hyperparameters {\n /**\n * Number of examples in each batch. A larger batch size means that model\n * parameters are updated less frequently, but with lower variance.\n */\n batch_size?: 'auto' | number;\n\n /**\n * Scaling factor for the learning rate. A smaller learning rate may be useful to\n * avoid overfitting.\n */\n learning_rate_multiplier?: 'auto' | number;\n\n /**\n * The number of epochs to train the model for. An epoch refers to one full cycle\n * through the training dataset.\n */\n n_epochs?: 'auto' | number;\n }\n\n export interface Integration {\n /**\n * The type of integration to enable. Currently, only \"wandb\" (Weights and Biases)\n * is supported.\n */\n type: 'wandb';\n\n /**\n * The settings for your integration with Weights and Biases. This payload\n * specifies the project that metrics will be sent to. Optionally, you can set an\n * explicit display name for your run, add tags to your run, and set a default\n * entity (team, username, etc) to be associated with your run.\n */\n wandb: Integration.Wandb;\n }\n\n export namespace Integration {\n /**\n * The settings for your integration with Weights and Biases. This payload\n * specifies the project that metrics will be sent to. Optionally, you can set an\n * explicit display name for your run, add tags to your run, and set a default\n * entity (team, username, etc) to be associated with your run.\n */\n export interface Wandb {\n /**\n * The name of the project that the new run will be created under.\n */\n project: string;\n\n /**\n * The entity to use for the run. This allows you to set the team or username of\n * the WandB user that you would like associated with the run. If not set, the\n * default entity for the registered WandB API key is used.\n */\n entity?: string | null;\n\n /**\n * A display name to set for the run. If not set, we will use the Job ID as the\n * name.\n */\n name?: string | null;\n\n /**\n * A list of tags to be attached to the newly created run. These tags are passed\n * through directly to WandB. Some default tags are generated by OpenAI:\n * \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n */\n tags?: Array<string>;\n }\n }\n\n /**\n * The method used for fine-tuning.\n */\n export interface Method {\n /**\n * The type of method. Is either `supervised`, `dpo`, or `reinforcement`.\n */\n type: 'supervised' | 'dpo' | 'reinforcement';\n\n /**\n * Configuration for the DPO fine-tuning method.\n */\n dpo?: MethodsAPI.DpoMethod;\n\n /**\n * Configuration for the reinforcement fine-tuning method.\n */\n reinforcement?: MethodsAPI.ReinforcementMethod;\n\n /**\n * Configuration for the supervised fine-tuning method.\n */\n supervised?: MethodsAPI.SupervisedMethod;\n }\n}\n\nexport interface JobListParams extends CursorPageParams {}\n\nexport interface JobListEventsParams extends CursorPageParams {}\n\nJobs.FineTuningJobsPage = FineTuningJobsPage;\nJobs.FineTuningJobEventsPage = FineTuningJobEventsPage;\nJobs.Checkpoints = Checkpoints;\nJobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;\n\nexport declare namespace Jobs {\n export {\n type FineTuningJob as FineTuningJob,\n type FineTuningJobEvent as FineTuningJobEvent,\n type FineTuningJobIntegration as FineTuningJobIntegration,\n type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration,\n type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject,\n FineTuningJobsPage as FineTuningJobsPage,\n FineTuningJobEventsPage as FineTuningJobEventsPage,\n type JobCreateParams as JobCreateParams,\n type JobListParams as JobListParams,\n type JobListEventsParams as JobListEventsParams,\n };\n\n export {\n Checkpoints as Checkpoints,\n type FineTuningJobCheckpoint as FineTuningJobCheckpoint,\n FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage,\n type CheckpointListParams as CheckpointListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as MethodsAPI from './methods';\nimport {\n DpoHyperparameters,\n DpoMethod,\n Methods,\n ReinforcementHyperparameters,\n ReinforcementMethod,\n SupervisedHyperparameters,\n SupervisedMethod,\n} from './methods';\nimport * as AlphaAPI from './alpha/alpha';\nimport { Alpha } from './alpha/alpha';\nimport * as CheckpointsAPI from './checkpoints/checkpoints';\nimport { Checkpoints } from './checkpoints/checkpoints';\nimport * as JobsAPI from './jobs/jobs';\nimport {\n FineTuningJob,\n FineTuningJobEvent,\n FineTuningJobEventsPage,\n FineTuningJobIntegration,\n FineTuningJobWandbIntegration,\n FineTuningJobWandbIntegrationObject,\n FineTuningJobsPage,\n JobCreateParams,\n JobListEventsParams,\n JobListParams,\n Jobs,\n} from './jobs/jobs';\n\nexport class FineTuning extends APIResource {\n methods: MethodsAPI.Methods = new MethodsAPI.Methods(this._client);\n jobs: JobsAPI.Jobs = new JobsAPI.Jobs(this._client);\n checkpoints: CheckpointsAPI.Checkpoints = new CheckpointsAPI.Checkpoints(this._client);\n alpha: AlphaAPI.Alpha = new AlphaAPI.Alpha(this._client);\n}\n\nFineTuning.Methods = Methods;\nFineTuning.Jobs = Jobs;\nFineTuning.FineTuningJobsPage = FineTuningJobsPage;\nFineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;\nFineTuning.Checkpoints = Checkpoints;\nFineTuning.Alpha = Alpha;\n\nexport declare namespace FineTuning {\n export {\n Methods as Methods,\n type DpoHyperparameters as DpoHyperparameters,\n type DpoMethod as DpoMethod,\n type ReinforcementHyperparameters as ReinforcementHyperparameters,\n type ReinforcementMethod as ReinforcementMethod,\n type SupervisedHyperparameters as SupervisedHyperparameters,\n type SupervisedMethod as SupervisedMethod,\n };\n\n export {\n Jobs as Jobs,\n type FineTuningJob as FineTuningJob,\n type FineTuningJobEvent as FineTuningJobEvent,\n type FineTuningJobIntegration as FineTuningJobIntegration,\n type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration,\n type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject,\n FineTuningJobsPage as FineTuningJobsPage,\n FineTuningJobEventsPage as FineTuningJobEventsPage,\n type JobCreateParams as JobCreateParams,\n type JobListParams as JobListParams,\n type JobListEventsParams as JobListEventsParams,\n };\n\n export { Checkpoints as Checkpoints };\n\n export { Alpha as Alpha };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as ResponsesAPI from '../responses/responses';\n\nexport class GraderModels extends APIResource {}\n\n/**\n * A LabelModelGrader object which uses a model to assign labels to each item in\n * the evaluation.\n */\nexport interface LabelModelGrader {\n input: Array<LabelModelGrader.Input>;\n\n /**\n * The labels to assign to each item in the evaluation.\n */\n labels: Array<string>;\n\n /**\n * The model to use for the evaluation. Must support structured outputs.\n */\n model: string;\n\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The labels that indicate a passing result. Must be a subset of labels.\n */\n passing_labels: Array<string>;\n\n /**\n * The object type, which is always `label_model`.\n */\n type: 'label_model';\n}\n\nexport namespace LabelModelGrader {\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface Input {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | Input.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace Input {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n}\n\n/**\n * A MultiGrader object combines the output of multiple graders to produce a single\n * score.\n */\nexport interface MultiGrader {\n /**\n * A formula to calculate the output based on grader results.\n */\n calculate_output: string;\n\n graders: Record<\n string,\n StringCheckGrader | TextSimilarityGrader | PythonGrader | ScoreModelGrader | LabelModelGrader\n >;\n\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The object type, which is always `multi`.\n */\n type: 'multi';\n}\n\n/**\n * A PythonGrader object that runs a python script on the input.\n */\nexport interface PythonGrader {\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The source code of the python script.\n */\n source: string;\n\n /**\n * The object type, which is always `python`.\n */\n type: 'python';\n\n /**\n * The image tag to use for the python script.\n */\n image_tag?: string;\n}\n\n/**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\nexport interface ScoreModelGrader {\n /**\n * The input text. This may include template strings.\n */\n input: Array<ScoreModelGrader.Input>;\n\n /**\n * The model to use for the evaluation.\n */\n model: string;\n\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The object type, which is always `score_model`.\n */\n type: 'score_model';\n\n /**\n * The range of the score. Defaults to `[0, 1]`.\n */\n range?: Array<number>;\n\n /**\n * The sampling parameters for the model.\n */\n sampling_params?: unknown;\n}\n\nexport namespace ScoreModelGrader {\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\n export interface Input {\n /**\n * Text inputs to the model - can contain template strings.\n */\n content: string | ResponsesAPI.ResponseInputText | Input.OutputText;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n }\n\n export namespace Input {\n /**\n * A text output from the model.\n */\n export interface OutputText {\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n }\n }\n}\n\n/**\n * A StringCheckGrader object that performs a string comparison between input and\n * reference using a specified operation.\n */\nexport interface StringCheckGrader {\n /**\n * The input text. This may include template strings.\n */\n input: string;\n\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.\n */\n operation: 'eq' | 'ne' | 'like' | 'ilike';\n\n /**\n * The reference text. This may include template strings.\n */\n reference: string;\n\n /**\n * The object type, which is always `string_check`.\n */\n type: 'string_check';\n}\n\n/**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\nexport interface TextSimilarityGrader {\n /**\n * The evaluation metric to use. One of `fuzzy_match`, `bleu`, `gleu`, `meteor`,\n * `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`.\n */\n evaluation_metric:\n | 'fuzzy_match'\n | 'bleu'\n | 'gleu'\n | 'meteor'\n | 'rouge_1'\n | 'rouge_2'\n | 'rouge_3'\n | 'rouge_4'\n | 'rouge_5'\n | 'rouge_l';\n\n /**\n * The text being graded.\n */\n input: string;\n\n /**\n * The name of the grader.\n */\n name: string;\n\n /**\n * The text being graded against.\n */\n reference: string;\n\n /**\n * The type of grader.\n */\n type: 'text_similarity';\n}\n\nexport declare namespace GraderModels {\n export {\n type LabelModelGrader as LabelModelGrader,\n type MultiGrader as MultiGrader,\n type PythonGrader as PythonGrader,\n type ScoreModelGrader as ScoreModelGrader,\n type StringCheckGrader as StringCheckGrader,\n type TextSimilarityGrader as TextSimilarityGrader,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as GraderModelsAPI from './grader-models';\nimport {\n GraderModels,\n LabelModelGrader,\n MultiGrader,\n PythonGrader,\n ScoreModelGrader,\n StringCheckGrader,\n TextSimilarityGrader,\n} from './grader-models';\n\nexport class Graders extends APIResource {\n graderModels: GraderModelsAPI.GraderModels = new GraderModelsAPI.GraderModels(this._client);\n}\n\nGraders.GraderModels = GraderModels;\n\nexport declare namespace Graders {\n export {\n GraderModels as GraderModels,\n type LabelModelGrader as LabelModelGrader,\n type MultiGrader as MultiGrader,\n type PythonGrader as PythonGrader,\n type ScoreModelGrader as ScoreModelGrader,\n type StringCheckGrader as StringCheckGrader,\n type TextSimilarityGrader as TextSimilarityGrader,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport * as Core from '../core';\n\nexport class Images extends APIResource {\n /**\n * Creates a variation of a given image. This endpoint only supports `dall-e-2`.\n *\n * @example\n * ```ts\n * const imagesResponse = await client.images.createVariation({\n * image: fs.createReadStream('otter.png'),\n * });\n * ```\n */\n createVariation(\n body: ImageCreateVariationParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<ImagesResponse> {\n return this._client.post('/images/variations', Core.multipartFormRequestOptions({ body, ...options }));\n }\n\n /**\n * Creates an edited or extended image given one or more source images and a\n * prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`.\n *\n * @example\n * ```ts\n * const imagesResponse = await client.images.edit({\n * image: fs.createReadStream('path/to/file'),\n * prompt: 'A cute baby sea otter wearing a beret',\n * });\n * ```\n */\n edit(body: ImageEditParams, options?: Core.RequestOptions): Core.APIPromise<ImagesResponse> {\n return this._client.post('/images/edits', Core.multipartFormRequestOptions({ body, ...options }));\n }\n\n /**\n * Creates an image given a prompt.\n * [Learn more](https://platform.openai.com/docs/guides/images).\n *\n * @example\n * ```ts\n * const imagesResponse = await client.images.generate({\n * prompt: 'A cute baby sea otter',\n * });\n * ```\n */\n generate(body: ImageGenerateParams, options?: Core.RequestOptions): Core.APIPromise<ImagesResponse> {\n return this._client.post('/images/generations', { body, ...options });\n }\n}\n\n/**\n * Represents the content or the URL of an image generated by the OpenAI API.\n */\nexport interface Image {\n /**\n * The base64-encoded JSON of the generated image. Default value for `gpt-image-1`,\n * and only present if `response_format` is set to `b64_json` for `dall-e-2` and\n * `dall-e-3`.\n */\n b64_json?: string;\n\n /**\n * For `dall-e-3` only, the revised prompt that was used to generate the image.\n */\n revised_prompt?: string;\n\n /**\n * When using `dall-e-2` or `dall-e-3`, the URL of the generated image if\n * `response_format` is set to `url` (default value). Unsupported for\n * `gpt-image-1`.\n */\n url?: string;\n}\n\nexport type ImageModel = 'dall-e-2' | 'dall-e-3' | 'gpt-image-1';\n\n/**\n * The response from the image generation endpoint.\n */\nexport interface ImagesResponse {\n /**\n * The Unix timestamp (in seconds) of when the image was created.\n */\n created: number;\n\n /**\n * The list of generated images.\n */\n data?: Array<Image>;\n\n /**\n * For `gpt-image-1` only, the token usage information for the image generation.\n */\n usage?: ImagesResponse.Usage;\n}\n\nexport namespace ImagesResponse {\n /**\n * For `gpt-image-1` only, the token usage information for the image generation.\n */\n export interface Usage {\n /**\n * The number of tokens (images and text) in the input prompt.\n */\n input_tokens: number;\n\n /**\n * The input tokens detailed information for the image generation.\n */\n input_tokens_details: Usage.InputTokensDetails;\n\n /**\n * The number of image tokens in the output image.\n */\n output_tokens: number;\n\n /**\n * The total number of tokens (images and text) used for the image generation.\n */\n total_tokens: number;\n }\n\n export namespace Usage {\n /**\n * The input tokens detailed information for the image generation.\n */\n export interface InputTokensDetails {\n /**\n * The number of image tokens in the input prompt.\n */\n image_tokens: number;\n\n /**\n * The number of text tokens in the input prompt.\n */\n text_tokens: number;\n }\n }\n}\n\nexport interface ImageCreateVariationParams {\n /**\n * The image to use as the basis for the variation(s). Must be a valid PNG file,\n * less than 4MB, and square.\n */\n image: Core.Uploadable;\n\n /**\n * The model to use for image generation. Only `dall-e-2` is supported at this\n * time.\n */\n model?: (string & {}) | ImageModel | null;\n\n /**\n * The number of images to generate. Must be between 1 and 10.\n */\n n?: number | null;\n\n /**\n * The format in which the generated images are returned. Must be one of `url` or\n * `b64_json`. URLs are only valid for 60 minutes after the image has been\n * generated.\n */\n response_format?: 'url' | 'b64_json' | null;\n\n /**\n * The size of the generated images. Must be one of `256x256`, `512x512`, or\n * `1024x1024`.\n */\n size?: '256x256' | '512x512' | '1024x1024' | null;\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor\n * and detect abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport interface ImageEditParams {\n /**\n * The image(s) to edit. Must be a supported image file or an array of images.\n *\n * For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than\n * 25MB. You can provide up to 16 images.\n *\n * For `dall-e-2`, you can only provide one image, and it should be a square `png`\n * file less than 4MB.\n */\n image: Core.Uploadable | Array<Core.Uploadable>;\n\n /**\n * A text description of the desired image(s). The maximum length is 1000\n * characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.\n */\n prompt: string;\n\n /**\n * Allows to set transparency for the background of the generated image(s). This\n * parameter is only supported for `gpt-image-1`. Must be one of `transparent`,\n * `opaque` or `auto` (default value). When `auto` is used, the model will\n * automatically determine the best background for the image.\n *\n * If `transparent`, the output format needs to support transparency, so it should\n * be set to either `png` (default value) or `webp`.\n */\n background?: 'transparent' | 'opaque' | 'auto' | null;\n\n /**\n * An additional image whose fully transparent areas (e.g. where alpha is zero)\n * indicate where `image` should be edited. If there are multiple images provided,\n * the mask will be applied on the first image. Must be a valid PNG file, less than\n * 4MB, and have the same dimensions as `image`.\n */\n mask?: Core.Uploadable;\n\n /**\n * The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are\n * supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1`\n * is used.\n */\n model?: (string & {}) | ImageModel | null;\n\n /**\n * The number of images to generate. Must be between 1 and 10.\n */\n n?: number | null;\n\n /**\n * The quality of the image that will be generated. `high`, `medium` and `low` are\n * only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality.\n * Defaults to `auto`.\n */\n quality?: 'standard' | 'low' | 'medium' | 'high' | 'auto' | null;\n\n /**\n * The format in which the generated images are returned. Must be one of `url` or\n * `b64_json`. URLs are only valid for 60 minutes after the image has been\n * generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1`\n * will always return base64-encoded images.\n */\n response_format?: 'url' | 'b64_json' | null;\n\n /**\n * The size of the generated images. Must be one of `1024x1024`, `1536x1024`\n * (landscape), `1024x1536` (portrait), or `auto` (default value) for\n * `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.\n */\n size?: '256x256' | '512x512' | '1024x1024' | '1536x1024' | '1024x1536' | 'auto' | null;\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor\n * and detect abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport interface ImageGenerateParams {\n /**\n * A text description of the desired image(s). The maximum length is 32000\n * characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters\n * for `dall-e-3`.\n */\n prompt: string;\n\n /**\n * Allows to set transparency for the background of the generated image(s). This\n * parameter is only supported for `gpt-image-1`. Must be one of `transparent`,\n * `opaque` or `auto` (default value). When `auto` is used, the model will\n * automatically determine the best background for the image.\n *\n * If `transparent`, the output format needs to support transparency, so it should\n * be set to either `png` (default value) or `webp`.\n */\n background?: 'transparent' | 'opaque' | 'auto' | null;\n\n /**\n * The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or\n * `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to\n * `gpt-image-1` is used.\n */\n model?: (string & {}) | ImageModel | null;\n\n /**\n * Control the content-moderation level for images generated by `gpt-image-1`. Must\n * be either `low` for less restrictive filtering or `auto` (default value).\n */\n moderation?: 'low' | 'auto' | null;\n\n /**\n * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only\n * `n=1` is supported.\n */\n n?: number | null;\n\n /**\n * The compression level (0-100%) for the generated images. This parameter is only\n * supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and\n * defaults to 100.\n */\n output_compression?: number | null;\n\n /**\n * The format in which the generated images are returned. This parameter is only\n * supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n */\n output_format?: 'png' | 'jpeg' | 'webp' | null;\n\n /**\n * The quality of the image that will be generated.\n *\n * - `auto` (default value) will automatically select the best quality for the\n * given model.\n * - `high`, `medium` and `low` are supported for `gpt-image-1`.\n * - `hd` and `standard` are supported for `dall-e-3`.\n * - `standard` is the only option for `dall-e-2`.\n */\n quality?: 'standard' | 'hd' | 'low' | 'medium' | 'high' | 'auto' | null;\n\n /**\n * The format in which generated images with `dall-e-2` and `dall-e-3` are\n * returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes\n * after the image has been generated. This parameter isn't supported for\n * `gpt-image-1` which will always return base64-encoded images.\n */\n response_format?: 'url' | 'b64_json' | null;\n\n /**\n * The size of the generated images. Must be one of `1024x1024`, `1536x1024`\n * (landscape), `1024x1536` (portrait), or `auto` (default value) for\n * `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and\n * one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.\n */\n size?:\n | 'auto'\n | '1024x1024'\n | '1536x1024'\n | '1024x1536'\n | '256x256'\n | '512x512'\n | '1792x1024'\n | '1024x1792'\n | null;\n\n /**\n * The style of the generated images. This parameter is only supported for\n * `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean\n * towards generating hyper-real and dramatic images. Natural causes the model to\n * produce more natural, less hyper-real looking images.\n */\n style?: 'vivid' | 'natural' | null;\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor\n * and detect abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport declare namespace Images {\n export {\n type Image as Image,\n type ImageModel as ImageModel,\n type ImagesResponse as ImagesResponse,\n type ImageCreateVariationParams as ImageCreateVariationParams,\n type ImageEditParams as ImageEditParams,\n type ImageGenerateParams as ImageGenerateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport * as Core from '../core';\nimport { Page } from '../pagination';\n\nexport class Models extends APIResource {\n /**\n * Retrieves a model instance, providing basic information about the model such as\n * the owner and permissioning.\n */\n retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise<Model> {\n return this._client.get(`/models/${model}`, options);\n }\n\n /**\n * Lists the currently available models, and provides basic information about each\n * one such as the owner and availability.\n */\n list(options?: Core.RequestOptions): Core.PagePromise<ModelsPage, Model> {\n return this._client.getAPIList('/models', ModelsPage, options);\n }\n\n /**\n * Delete a fine-tuned model. You must have the Owner role in your organization to\n * delete a model.\n */\n del(model: string, options?: Core.RequestOptions): Core.APIPromise<ModelDeleted> {\n return this._client.delete(`/models/${model}`, options);\n }\n}\n\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class ModelsPage extends Page<Model> {}\n\n/**\n * Describes an OpenAI model offering that can be used with the API.\n */\nexport interface Model {\n /**\n * The model identifier, which can be referenced in the API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) when the model was created.\n */\n created: number;\n\n /**\n * The object type, which is always \"model\".\n */\n object: 'model';\n\n /**\n * The organization that owns the model.\n */\n owned_by: string;\n}\n\nexport interface ModelDeleted {\n id: string;\n\n deleted: boolean;\n\n object: string;\n}\n\nModels.ModelsPage = ModelsPage;\n\nexport declare namespace Models {\n export { type Model as Model, type ModelDeleted as ModelDeleted, ModelsPage as ModelsPage };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../resource';\nimport * as Core from '../core';\n\nexport class Moderations extends APIResource {\n /**\n * Classifies if text and/or image inputs are potentially harmful. Learn more in\n * the [moderation guide](https://platform.openai.com/docs/guides/moderation).\n */\n create(\n body: ModerationCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<ModerationCreateResponse> {\n return this._client.post('/moderations', { body, ...options });\n }\n}\n\nexport interface Moderation {\n /**\n * A list of the categories, and whether they are flagged or not.\n */\n categories: Moderation.Categories;\n\n /**\n * A list of the categories along with the input type(s) that the score applies to.\n */\n category_applied_input_types: Moderation.CategoryAppliedInputTypes;\n\n /**\n * A list of the categories along with their scores as predicted by model.\n */\n category_scores: Moderation.CategoryScores;\n\n /**\n * Whether any of the below categories are flagged.\n */\n flagged: boolean;\n}\n\nexport namespace Moderation {\n /**\n * A list of the categories, and whether they are flagged or not.\n */\n export interface Categories {\n /**\n * Content that expresses, incites, or promotes harassing language towards any\n * target.\n */\n harassment: boolean;\n\n /**\n * Harassment content that also includes violence or serious harm towards any\n * target.\n */\n 'harassment/threatening': boolean;\n\n /**\n * Content that expresses, incites, or promotes hate based on race, gender,\n * ethnicity, religion, nationality, sexual orientation, disability status, or\n * caste. Hateful content aimed at non-protected groups (e.g., chess players) is\n * harassment.\n */\n hate: boolean;\n\n /**\n * Hateful content that also includes violence or serious harm towards the targeted\n * group based on race, gender, ethnicity, religion, nationality, sexual\n * orientation, disability status, or caste.\n */\n 'hate/threatening': boolean;\n\n /**\n * Content that includes instructions or advice that facilitate the planning or\n * execution of wrongdoing, or that gives advice or instruction on how to commit\n * illicit acts. For example, \"how to shoplift\" would fit this category.\n */\n illicit: boolean | null;\n\n /**\n * Content that includes instructions or advice that facilitate the planning or\n * execution of wrongdoing that also includes violence, or that gives advice or\n * instruction on the procurement of any weapon.\n */\n 'illicit/violent': boolean | null;\n\n /**\n * Content that promotes, encourages, or depicts acts of self-harm, such as\n * suicide, cutting, and eating disorders.\n */\n 'self-harm': boolean;\n\n /**\n * Content that encourages performing acts of self-harm, such as suicide, cutting,\n * and eating disorders, or that gives instructions or advice on how to commit such\n * acts.\n */\n 'self-harm/instructions': boolean;\n\n /**\n * Content where the speaker expresses that they are engaging or intend to engage\n * in acts of self-harm, such as suicide, cutting, and eating disorders.\n */\n 'self-harm/intent': boolean;\n\n /**\n * Content meant to arouse sexual excitement, such as the description of sexual\n * activity, or that promotes sexual services (excluding sex education and\n * wellness).\n */\n sexual: boolean;\n\n /**\n * Sexual content that includes an individual who is under 18 years old.\n */\n 'sexual/minors': boolean;\n\n /**\n * Content that depicts death, violence, or physical injury.\n */\n violence: boolean;\n\n /**\n * Content that depicts death, violence, or physical injury in graphic detail.\n */\n 'violence/graphic': boolean;\n }\n\n /**\n * A list of the categories along with the input type(s) that the score applies to.\n */\n export interface CategoryAppliedInputTypes {\n /**\n * The applied input type(s) for the category 'harassment'.\n */\n harassment: Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'harassment/threatening'.\n */\n 'harassment/threatening': Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'hate'.\n */\n hate: Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'hate/threatening'.\n */\n 'hate/threatening': Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'illicit'.\n */\n illicit: Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'illicit/violent'.\n */\n 'illicit/violent': Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'self-harm'.\n */\n 'self-harm': Array<'text' | 'image'>;\n\n /**\n * The applied input type(s) for the category 'self-harm/instructions'.\n */\n 'self-harm/instructions': Array<'text' | 'image'>;\n\n /**\n * The applied input type(s) for the category 'self-harm/intent'.\n */\n 'self-harm/intent': Array<'text' | 'image'>;\n\n /**\n * The applied input type(s) for the category 'sexual'.\n */\n sexual: Array<'text' | 'image'>;\n\n /**\n * The applied input type(s) for the category 'sexual/minors'.\n */\n 'sexual/minors': Array<'text'>;\n\n /**\n * The applied input type(s) for the category 'violence'.\n */\n violence: Array<'text' | 'image'>;\n\n /**\n * The applied input type(s) for the category 'violence/graphic'.\n */\n 'violence/graphic': Array<'text' | 'image'>;\n }\n\n /**\n * A list of the categories along with their scores as predicted by model.\n */\n export interface CategoryScores {\n /**\n * The score for the category 'harassment'.\n */\n harassment: number;\n\n /**\n * The score for the category 'harassment/threatening'.\n */\n 'harassment/threatening': number;\n\n /**\n * The score for the category 'hate'.\n */\n hate: number;\n\n /**\n * The score for the category 'hate/threatening'.\n */\n 'hate/threatening': number;\n\n /**\n * The score for the category 'illicit'.\n */\n illicit: number;\n\n /**\n * The score for the category 'illicit/violent'.\n */\n 'illicit/violent': number;\n\n /**\n * The score for the category 'self-harm'.\n */\n 'self-harm': number;\n\n /**\n * The score for the category 'self-harm/instructions'.\n */\n 'self-harm/instructions': number;\n\n /**\n * The score for the category 'self-harm/intent'.\n */\n 'self-harm/intent': number;\n\n /**\n * The score for the category 'sexual'.\n */\n sexual: number;\n\n /**\n * The score for the category 'sexual/minors'.\n */\n 'sexual/minors': number;\n\n /**\n * The score for the category 'violence'.\n */\n violence: number;\n\n /**\n * The score for the category 'violence/graphic'.\n */\n 'violence/graphic': number;\n }\n}\n\n/**\n * An object describing an image to classify.\n */\nexport interface ModerationImageURLInput {\n /**\n * Contains either an image URL or a data URL for a base64 encoded image.\n */\n image_url: ModerationImageURLInput.ImageURL;\n\n /**\n * Always `image_url`.\n */\n type: 'image_url';\n}\n\nexport namespace ModerationImageURLInput {\n /**\n * Contains either an image URL or a data URL for a base64 encoded image.\n */\n export interface ImageURL {\n /**\n * Either a URL of the image or the base64 encoded image data.\n */\n url: string;\n }\n}\n\nexport type ModerationModel =\n | 'omni-moderation-latest'\n | 'omni-moderation-2024-09-26'\n | 'text-moderation-latest'\n | 'text-moderation-stable';\n\n/**\n * An object describing an image to classify.\n */\nexport type ModerationMultiModalInput = ModerationImageURLInput | ModerationTextInput;\n\n/**\n * An object describing text to classify.\n */\nexport interface ModerationTextInput {\n /**\n * A string of text to classify.\n */\n text: string;\n\n /**\n * Always `text`.\n */\n type: 'text';\n}\n\n/**\n * Represents if a given text input is potentially harmful.\n */\nexport interface ModerationCreateResponse {\n /**\n * The unique identifier for the moderation request.\n */\n id: string;\n\n /**\n * The model used to generate the moderation results.\n */\n model: string;\n\n /**\n * A list of moderation objects.\n */\n results: Array<Moderation>;\n}\n\nexport interface ModerationCreateParams {\n /**\n * Input (or inputs) to classify. Can be a single string, an array of strings, or\n * an array of multi-modal input objects similar to other models.\n */\n input: string | Array<string> | Array<ModerationMultiModalInput>;\n\n /**\n * The content moderation model you would like to use. Learn more in\n * [the moderation guide](https://platform.openai.com/docs/guides/moderation), and\n * learn about available models\n * [here](https://platform.openai.com/docs/models#moderation).\n */\n model?: (string & {}) | ModerationModel;\n}\n\nexport declare namespace Moderations {\n export {\n type Moderation as Moderation,\n type ModerationImageURLInput as ModerationImageURLInput,\n type ModerationModel as ModerationModel,\n type ModerationMultiModalInput as ModerationMultiModalInput,\n type ModerationTextInput as ModerationTextInput,\n type ModerationCreateResponse as ModerationCreateResponse,\n type ModerationCreateParams as ModerationCreateParams,\n };\n}\n","import { OpenAIError } from '../error';\nimport type { ChatCompletionTool } from '../resources/chat/completions';\nimport {\n ResponseTextConfig,\n type FunctionTool,\n type ParsedContent,\n type ParsedResponse,\n type ParsedResponseFunctionToolCall,\n type ParsedResponseOutputItem,\n type Response,\n type ResponseCreateParamsBase,\n type ResponseCreateParamsNonStreaming,\n type ResponseFunctionToolCall,\n type Tool,\n} from '../resources/responses/responses';\nimport { type AutoParseableTextFormat, isAutoParsableResponseFormat } from '../lib/parser';\n\nexport type ParseableToolsParams = Array<Tool> | ChatCompletionTool | null;\n\nexport type ResponseCreateParamsWithTools = ResponseCreateParamsBase & {\n tools?: ParseableToolsParams;\n};\n\ntype TextConfigParams = { text?: ResponseTextConfig };\n\nexport type ExtractParsedContentFromParams<Params extends TextConfigParams> =\n NonNullable<Params['text']>['format'] extends AutoParseableTextFormat<infer P> ? P : null;\n\nexport function maybeParseResponse<\n Params extends ResponseCreateParamsBase | null,\n ParsedT = Params extends null ? null : ExtractParsedContentFromParams<NonNullable<Params>>,\n>(response: Response, params: Params): ParsedResponse<ParsedT> {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...response,\n output_parsed: null,\n output: response.output.map((item) => {\n if (item.type === 'function_call') {\n return {\n ...item,\n parsed_arguments: null,\n };\n }\n\n if (item.type === 'message') {\n return {\n ...item,\n content: item.content.map((content) => ({\n ...content,\n parsed: null,\n })),\n };\n } else {\n return item;\n }\n }),\n };\n }\n\n return parseResponse(response, params);\n}\n\nexport function parseResponse<\n Params extends ResponseCreateParamsBase,\n ParsedT = ExtractParsedContentFromParams<Params>,\n>(response: Response, params: Params): ParsedResponse<ParsedT> {\n const output: Array<ParsedResponseOutputItem<ParsedT>> = response.output.map(\n (item): ParsedResponseOutputItem<ParsedT> => {\n if (item.type === 'function_call') {\n return {\n ...item,\n parsed_arguments: parseToolCall(params, item),\n };\n }\n if (item.type === 'message') {\n const content: Array<ParsedContent<ParsedT>> = item.content.map((content) => {\n if (content.type === 'output_text') {\n return {\n ...content,\n parsed: parseTextFormat(params, content.text),\n };\n }\n\n return content;\n });\n\n return {\n ...item,\n content,\n };\n }\n\n return item;\n },\n );\n\n const parsed: Omit<ParsedResponse<ParsedT>, 'output_parsed'> = Object.assign({}, response, { output });\n if (!Object.getOwnPropertyDescriptor(response, 'output_text')) {\n addOutputText(parsed);\n }\n\n Object.defineProperty(parsed, 'output_parsed', {\n enumerable: true,\n get() {\n for (const output of parsed.output) {\n if (output.type !== 'message') {\n continue;\n }\n\n for (const content of output.content) {\n if (content.type === 'output_text' && content.parsed !== null) {\n return content.parsed;\n }\n }\n }\n\n return null;\n },\n });\n\n return parsed as ParsedResponse<ParsedT>;\n}\n\nfunction parseTextFormat<\n Params extends ResponseCreateParamsBase,\n ParsedT = ExtractParsedContentFromParams<Params>,\n>(params: Params, content: string): ParsedT | null {\n if (params.text?.format?.type !== 'json_schema') {\n return null;\n }\n\n if ('$parseRaw' in params.text?.format) {\n const text_format = params.text?.format as unknown as AutoParseableTextFormat<ParsedT>;\n return text_format.$parseRaw(content);\n }\n\n return JSON.parse(content);\n}\n\nexport function hasAutoParseableInput(params: ResponseCreateParamsWithTools): boolean {\n if (isAutoParsableResponseFormat(params.text?.format)) {\n return true;\n }\n\n return false;\n}\n\ntype ToolOptions = {\n name: string;\n arguments: any;\n function?: ((args: any) => any) | undefined;\n};\n\nexport type AutoParseableResponseTool<\n OptionsT extends ToolOptions,\n HasFunction = OptionsT['function'] extends Function ? true : false,\n> = FunctionTool & {\n __arguments: OptionsT['arguments']; // type-level only\n __name: OptionsT['name']; // type-level only\n\n $brand: 'auto-parseable-tool';\n $callback: ((args: OptionsT['arguments']) => any) | undefined;\n $parseRaw(args: string): OptionsT['arguments'];\n};\n\nexport function makeParseableResponseTool<OptionsT extends ToolOptions>(\n tool: FunctionTool,\n {\n parser,\n callback,\n }: {\n parser: (content: string) => OptionsT['arguments'];\n callback: ((args: any) => any) | undefined;\n },\n): AutoParseableResponseTool<OptionsT['arguments']> {\n const obj = { ...tool };\n\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n\n return obj as AutoParseableResponseTool<OptionsT['arguments']>;\n}\n\nexport function isAutoParsableTool(tool: any): tool is AutoParseableResponseTool<any> {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\n\nfunction getInputToolByName(input_tools: Array<Tool>, name: string): FunctionTool | undefined {\n return input_tools.find((tool) => tool.type === 'function' && tool.name === name) as\n | FunctionTool\n | undefined;\n}\n\nfunction parseToolCall<Params extends ResponseCreateParamsBase>(\n params: Params,\n toolCall: ResponseFunctionToolCall,\n): ParsedResponseFunctionToolCall {\n const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);\n\n return {\n ...toolCall,\n ...toolCall,\n parsed_arguments:\n isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments)\n : inputTool?.strict ? JSON.parse(toolCall.arguments)\n : null,\n };\n}\n\nexport function shouldParseToolCall(\n params: ResponseCreateParamsNonStreaming | null | undefined,\n toolCall: ResponseFunctionToolCall,\n): boolean {\n if (!params) {\n return false;\n }\n\n const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);\n return isAutoParsableTool(inputTool) || inputTool?.strict || false;\n}\n\nexport function validateInputTools(tools: ChatCompletionTool[] | undefined) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(\n `Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``,\n );\n }\n\n if (tool.function.strict !== true) {\n throw new OpenAIError(\n `The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`,\n );\n }\n }\n}\n\nexport function addOutputText(rsp: Response): void {\n const texts: string[] = [];\n for (const output of rsp.output) {\n if (output.type !== 'message') {\n continue;\n }\n\n for (const content of output.content) {\n if (content.type === 'output_text') {\n texts.push(content.text);\n }\n }\n }\n\n rsp.output_text = texts.join('');\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { isRequestOptions } from '../../core';\nimport * as Core from '../../core';\nimport * as ResponsesAPI from './responses';\nimport { ResponseItemsPage } from './responses';\nimport { type CursorPageParams } from '../../pagination';\n\nexport class InputItems extends APIResource {\n /**\n * Returns a list of input items for a given response.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const responseItem of client.responses.inputItems.list(\n * 'response_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n responseId: string,\n query?: InputItemListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<ResponseItemsPage, ResponsesAPI.ResponseItem>;\n list(\n responseId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<ResponseItemsPage, ResponsesAPI.ResponseItem>;\n list(\n responseId: string,\n query: InputItemListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<ResponseItemsPage, ResponsesAPI.ResponseItem> {\n if (isRequestOptions(query)) {\n return this.list(responseId, {}, query);\n }\n return this._client.getAPIList(`/responses/${responseId}/input_items`, ResponseItemsPage, {\n query,\n ...options,\n });\n }\n}\n\n/**\n * A list of Response items.\n */\nexport interface ResponseItemList {\n /**\n * A list of items used to generate this response.\n */\n data: Array<ResponsesAPI.ResponseItem>;\n\n /**\n * The ID of the first item in the list.\n */\n first_id: string;\n\n /**\n * Whether there are more items available.\n */\n has_more: boolean;\n\n /**\n * The ID of the last item in the list.\n */\n last_id: string;\n\n /**\n * The type of object returned, must be `list`.\n */\n object: 'list';\n}\n\nexport interface InputItemListParams extends CursorPageParams {\n /**\n * An item ID to list items before, used in pagination.\n */\n before?: string;\n\n /**\n * Additional fields to include in the response. See the `include` parameter for\n * Response creation above for more information.\n */\n include?: Array<ResponsesAPI.ResponseIncludable>;\n\n /**\n * The order to return the input items in. Default is `desc`.\n *\n * - `asc`: Return the input items in ascending order.\n * - `desc`: Return the input items in descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nexport declare namespace InputItems {\n export { type ResponseItemList as ResponseItemList, type InputItemListParams as InputItemListParams };\n}\n\nexport { ResponseItemsPage };\n","import {\n ResponseTextConfig,\n type ParsedResponse,\n type Response,\n type ResponseCreateParamsBase,\n type ResponseCreateParamsStreaming,\n type ResponseStreamEvent,\n} from '../../resources/responses/responses';\nimport * as Core from '../../core';\nimport { APIUserAbortError, OpenAIError } from '../../error';\nimport OpenAI from '../../index';\nimport { type BaseEvents, EventStream } from '../EventStream';\nimport { type ResponseFunctionCallArgumentsDeltaEvent, type ResponseTextDeltaEvent } from './EventTypes';\nimport { maybeParseResponse, ParseableToolsParams } from '../ResponsesParser';\nimport { Stream } from \"../../streaming\";\n\nexport type ResponseStreamParams = ResponseCreateAndStreamParams | ResponseStreamByIdParams;\n\nexport type ResponseCreateAndStreamParams = Omit<ResponseCreateParamsBase, 'stream'> & {\n stream?: true;\n};\n\nexport type ResponseStreamByIdParams = {\n /**\n * The ID of the response to stream.\n */\n response_id: string;\n /**\n * If provided, the stream will start after the event with the given sequence number.\n */\n starting_after?: number;\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data. Learn more:\n *\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n */\n text?: ResponseTextConfig;\n\n /**\n * An array of tools the model may call while generating a response. When continuing a stream, provide\n * the same tools as the original request.\n */\n tools?: ParseableToolsParams;\n};\n\ntype ResponseEvents = BaseEvents &\n Omit<\n {\n [K in ResponseStreamEvent['type']]: (event: Extract<ResponseStreamEvent, { type: K }>) => void;\n },\n 'response.output_text.delta' | 'response.function_call_arguments.delta'\n > & {\n event: (event: ResponseStreamEvent) => void;\n 'response.output_text.delta': (event: ResponseTextDeltaEvent) => void;\n 'response.function_call_arguments.delta': (event: ResponseFunctionCallArgumentsDeltaEvent) => void;\n };\n\nexport type ResponseStreamingParams = Omit<ResponseCreateParamsBase, 'stream'> & {\n stream?: true;\n};\n\nexport class ResponseStream<ParsedT = null>\n extends EventStream<ResponseEvents>\n implements AsyncIterable<ResponseStreamEvent>\n{\n #params: ResponseStreamingParams | null;\n #currentResponseSnapshot: Response | undefined;\n #finalResponse: ParsedResponse<ParsedT> | undefined;\n\n constructor(params: ResponseStreamingParams | null) {\n super();\n this.#params = params;\n }\n\n static createResponse<ParsedT>(\n client: OpenAI,\n params: ResponseStreamParams,\n options?: Core.RequestOptions,\n ): ResponseStream<ParsedT> {\n const runner = new ResponseStream<ParsedT>(params as ResponseCreateParamsStreaming);\n runner._run(() =>\n runner._createOrRetrieveResponse(client, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }),\n );\n return runner;\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentResponseSnapshot = undefined;\n }\n\n #addEvent(this: ResponseStream<ParsedT>, event: ResponseStreamEvent, starting_after: number | null) {\n if (this.ended) return;\n\n const maybeEmit = (name: string, event: ResponseStreamEvent & { snapshot?: string }) => {\n if (starting_after == null || event.sequence_number > starting_after) {\n this._emit(name as any, event);\n }\n };\n\n const response = this.#accumulateResponse(event);\n maybeEmit('event', event);\n\n switch (event.type) {\n case 'response.output_text.delta': {\n const output = response.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'message') {\n const content = output.content[event.content_index];\n if (!content) {\n throw new OpenAIError(`missing content at index ${event.content_index}`);\n }\n if (content.type !== 'output_text') {\n throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);\n }\n\n maybeEmit('response.output_text.delta', {\n ...event,\n snapshot: content.text,\n });\n }\n break;\n }\n case 'response.function_call_arguments.delta': {\n const output = response.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'function_call') {\n maybeEmit('response.function_call_arguments.delta', {\n ...event,\n snapshot: output.arguments,\n });\n }\n break;\n }\n default:\n maybeEmit(event.type, event);\n break;\n }\n }\n\n #endRequest(): ParsedResponse<ParsedT> {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentResponseSnapshot;\n if (!snapshot) {\n throw new OpenAIError(`request ended without sending any events`);\n }\n this.#currentResponseSnapshot = undefined;\n const parsedResponse = finalizeResponse<ParsedT>(snapshot, this.#params);\n this.#finalResponse = parsedResponse;\n\n return parsedResponse;\n }\n\n protected async _createOrRetrieveResponse(\n client: OpenAI,\n params: ResponseStreamParams,\n options?: Core.RequestOptions,\n ): Promise<ParsedResponse<ParsedT>> {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this.#beginRequest();\n\n let stream: Stream<ResponseStreamEvent> | undefined;\n let starting_after: number | null = null;\n if ('response_id' in params) {\n stream = await client.responses.retrieve(\n params.response_id,\n { stream: true },\n { ...options, signal: this.controller.signal, stream: true },\n );\n starting_after = params.starting_after ?? null;\n } else {\n stream = await client.responses.create(\n { ...params, stream: true },\n { ...options, signal: this.controller.signal },\n );\n }\n\n this._connected();\n for await (const event of stream) {\n this.#addEvent(event, starting_after);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this.#endRequest();\n }\n\n #accumulateResponse(event: ResponseStreamEvent): Response {\n let snapshot = this.#currentResponseSnapshot;\n if (!snapshot) {\n if (event.type !== 'response.created') {\n throw new OpenAIError(\n `When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`,\n );\n }\n snapshot = this.#currentResponseSnapshot = event.response;\n return snapshot;\n }\n\n switch (event.type) {\n case 'response.output_item.added': {\n snapshot.output.push(event.item);\n break;\n }\n case 'response.content_part.added': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'message') {\n output.content.push(event.part);\n }\n break;\n }\n case 'response.output_text.delta': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'message') {\n const content = output.content[event.content_index];\n if (!content) {\n throw new OpenAIError(`missing content at index ${event.content_index}`);\n }\n if (content.type !== 'output_text') {\n throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);\n }\n content.text += event.delta;\n }\n break;\n }\n case 'response.function_call_arguments.delta': {\n const output = snapshot.output[event.output_index];\n if (!output) {\n throw new OpenAIError(`missing output at index ${event.output_index}`);\n }\n if (output.type === 'function_call') {\n output.arguments += event.delta;\n }\n break;\n }\n case 'response.completed': {\n this.#currentResponseSnapshot = event.response;\n break;\n }\n }\n\n return snapshot;\n }\n\n [Symbol.asyncIterator](this: ResponseStream<ParsedT>): AsyncIterator<ResponseStreamEvent> {\n const pushQueue: ResponseStreamEvent[] = [];\n const readQueue: {\n resolve: (event: ResponseStreamEvent | undefined) => void;\n reject: (err: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('event', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<ResponseStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<ResponseStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true }));\n }\n const event = pushQueue.shift()!;\n return { value: event, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n /**\n * @returns a promise that resolves with the final Response, or rejects\n * if an error occurred or the stream ended prematurely without producing a REsponse.\n */\n async finalResponse(): Promise<ParsedResponse<ParsedT>> {\n await this.done();\n const response = this.#finalResponse;\n if (!response) throw new OpenAIError('stream ended without producing a ChatCompletion');\n return response;\n }\n}\n\nfunction finalizeResponse<ParsedT>(\n snapshot: Response,\n params: ResponseStreamingParams | null,\n): ParsedResponse<ParsedT> {\n return maybeParseResponse(snapshot, params);\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport {\n type ExtractParsedContentFromParams,\n parseResponse,\n type ResponseCreateParamsWithTools,\n addOutputText,\n} from '../../lib/ResponsesParser';\nimport * as Core from '../../core';\nimport { APIPromise } from '../../core';\nimport { APIResource } from '../../resource';\nimport * as Shared from '../shared';\nimport * as InputItemsAPI from './input-items';\nimport { InputItemListParams, InputItems, ResponseItemList } from './input-items';\nimport * as ResponsesAPI from './responses';\nimport { ResponseStream, ResponseStreamParams } from '../../lib/responses/ResponseStream';\nimport { CursorPage } from '../../pagination';\nimport { Stream } from '../../streaming';\n\nexport interface ParsedResponseOutputText<ParsedT> extends ResponseOutputText {\n parsed: ParsedT | null;\n}\n\nexport type ParsedContent<ParsedT> = ParsedResponseOutputText<ParsedT> | ResponseOutputRefusal;\n\nexport interface ParsedResponseOutputMessage<ParsedT> extends ResponseOutputMessage {\n content: ParsedContent<ParsedT>[];\n}\n\nexport interface ParsedResponseFunctionToolCall extends ResponseFunctionToolCall {\n parsed_arguments: any;\n}\n\nexport type ParsedResponseOutputItem<ParsedT> =\n | ParsedResponseOutputMessage<ParsedT>\n | ParsedResponseFunctionToolCall\n | ResponseFileSearchToolCall\n | ResponseFunctionWebSearch\n | ResponseComputerToolCall\n | ResponseReasoningItem\n | ResponseOutputItem.ImageGenerationCall\n | ResponseCodeInterpreterToolCall\n | ResponseOutputItem.LocalShellCall\n | ResponseOutputItem.McpCall\n | ResponseOutputItem.McpListTools\n | ResponseOutputItem.McpApprovalRequest;\n\nexport interface ParsedResponse<ParsedT> extends Response {\n output: Array<ParsedResponseOutputItem<ParsedT>>;\n\n output_parsed: ParsedT | null;\n}\n\nexport type ResponseParseParams = ResponseCreateParamsNonStreaming;\nexport class Responses extends APIResource {\n inputItems: InputItemsAPI.InputItems = new InputItemsAPI.InputItems(this._client);\n\n /**\n * Creates a model response. Provide\n * [text](https://platform.openai.com/docs/guides/text) or\n * [image](https://platform.openai.com/docs/guides/images) inputs to generate\n * [text](https://platform.openai.com/docs/guides/text) or\n * [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have\n * the model call your own\n * [custom code](https://platform.openai.com/docs/guides/function-calling) or use\n * built-in [tools](https://platform.openai.com/docs/guides/tools) like\n * [web search](https://platform.openai.com/docs/guides/tools-web-search) or\n * [file search](https://platform.openai.com/docs/guides/tools-file-search) to use\n * your own data as input for the model's response.\n *\n * @example\n * ```ts\n * const response = await client.responses.create({\n * input: 'string',\n * model: 'gpt-4o',\n * });\n * ```\n */\n create(body: ResponseCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Response>;\n create(\n body: ResponseCreateParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<ResponseStreamEvent>>;\n create(\n body: ResponseCreateParamsBase,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<ResponseStreamEvent> | Response>;\n create(\n body: ResponseCreateParams,\n options?: Core.RequestOptions,\n ): APIPromise<Response> | APIPromise<Stream<ResponseStreamEvent>> {\n return (\n this._client.post('/responses', { body, ...options, stream: body.stream ?? false }) as\n | APIPromise<Response>\n | APIPromise<Stream<ResponseStreamEvent>>\n )._thenUnwrap((rsp) => {\n if ('object' in rsp && rsp.object === 'response') {\n addOutputText(rsp as Response);\n }\n\n return rsp;\n }) as APIPromise<Response> | APIPromise<Stream<ResponseStreamEvent>>;\n }\n\n /**\n * Retrieves a model response with the given ID.\n *\n * @example\n * ```ts\n * const response = await client.responses.retrieve(\n * 'resp_677efb5139a88190b512bc3fef8e535d',\n * );\n * ```\n */\n\n retrieve(\n responseId: string,\n query?: ResponseRetrieveParamsNonStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Response>;\n retrieve(\n responseId: string,\n query: ResponseRetrieveParamsStreaming,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<ResponseStreamEvent>>;\n retrieve(\n responseId: string,\n query?: ResponseRetrieveParamsBase | undefined,\n options?: Core.RequestOptions,\n ): APIPromise<Stream<ResponseStreamEvent> | Response>;\n retrieve(\n responseId: string,\n query: ResponseRetrieveParams | undefined = {},\n options?: Core.RequestOptions,\n ): APIPromise<Response> | APIPromise<Stream<ResponseStreamEvent>> {\n return this._client.get(`/responses/${responseId}`, {\n query,\n ...options,\n stream: query?.stream ?? false,\n }) as APIPromise<Response> | APIPromise<Stream<ResponseStreamEvent>>;\n }\n\n /**\n * Deletes a model response with the given ID.\n *\n * @example\n * ```ts\n * await client.responses.del(\n * 'resp_677efb5139a88190b512bc3fef8e535d',\n * );\n * ```\n */\n del(responseId: string, options?: Core.RequestOptions): Core.APIPromise<void> {\n return this._client.delete(`/responses/${responseId}`, {\n ...options,\n headers: { Accept: '*/*', ...options?.headers },\n });\n }\n\n parse<Params extends ResponseCreateParamsWithTools, ParsedT = ExtractParsedContentFromParams<Params>>(\n body: Params,\n options?: Core.RequestOptions,\n ): Core.APIPromise<ParsedResponse<ParsedT>> {\n return this._client.responses\n .create(body, options)\n ._thenUnwrap((response) => parseResponse(response as Response, body));\n }\n\n /**\n * Creates a model response stream\n */\n\n stream<Params extends ResponseStreamParams, ParsedT = ExtractParsedContentFromParams<Params>>(\n body: Params,\n options?: Core.RequestOptions,\n ): ResponseStream<ParsedT> {\n return ResponseStream.createResponse<ParsedT>(this._client, body, options);\n }\n\n /**\n * Cancels a model response with the given ID. Only responses created with the\n * `background` parameter set to `true` can be cancelled.\n * [Learn more](https://platform.openai.com/docs/guides/background).\n *\n * @example\n * ```ts\n * await client.responses.cancel(\n * 'resp_677efb5139a88190b512bc3fef8e535d',\n * );\n * ```\n */\n\n cancel(responseId: string, options?: Core.RequestOptions): Core.APIPromise<void> {\n return this._client.post(`/responses/${responseId}/cancel`, {\n ...options,\n headers: { Accept: '*/*', ...options?.headers },\n });\n }\n}\n\nexport class ResponseItemsPage extends CursorPage<ResponseItem> {}\n\n/**\n * A tool that controls a virtual computer. Learn more about the\n * [computer tool](https://platform.openai.com/docs/guides/tools-computer-use).\n */\nexport interface ComputerTool {\n /**\n * The height of the computer display.\n */\n display_height: number;\n\n /**\n * The width of the computer display.\n */\n display_width: number;\n\n /**\n * The type of computer environment to control.\n */\n environment: 'windows' | 'mac' | 'linux' | 'ubuntu' | 'browser';\n\n /**\n * The type of the computer use tool. Always `computer_use_preview`.\n */\n type: 'computer-preview';\n}\n\n/**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\nexport interface EasyInputMessage {\n /**\n * Text, image, or audio input to the model, used to generate a response. Can also\n * contain previous assistant responses.\n */\n content: string | ResponseInputMessageContentList;\n\n /**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\n role: 'user' | 'assistant' | 'system' | 'developer';\n\n /**\n * The type of the message input. Always `message`.\n */\n type?: 'message';\n}\n\n/**\n * A tool that searches for relevant content from uploaded files. Learn more about\n * the\n * [file search tool](https://platform.openai.com/docs/guides/tools-file-search).\n */\nexport interface FileSearchTool {\n /**\n * The type of the file search tool. Always `file_search`.\n */\n type: 'file_search';\n\n /**\n * The IDs of the vector stores to search.\n */\n vector_store_ids: Array<string>;\n\n /**\n * A filter to apply.\n */\n filters?: Shared.ComparisonFilter | Shared.CompoundFilter | null;\n\n /**\n * The maximum number of results to return. This number should be between 1 and 50\n * inclusive.\n */\n max_num_results?: number;\n\n /**\n * Ranking options for search.\n */\n ranking_options?: FileSearchTool.RankingOptions;\n}\n\nexport namespace FileSearchTool {\n /**\n * Ranking options for search.\n */\n export interface RankingOptions {\n /**\n * The ranker to use for the file search.\n */\n ranker?: 'auto' | 'default-2024-11-15';\n\n /**\n * The score threshold for the file search, a number between 0 and 1. Numbers\n * closer to 1 will attempt to return only the most relevant results, but may\n * return fewer results.\n */\n score_threshold?: number;\n }\n}\n\n/**\n * Defines a function in your own code the model can choose to call. Learn more\n * about\n * [function calling](https://platform.openai.com/docs/guides/function-calling).\n */\nexport interface FunctionTool {\n /**\n * The name of the function to call.\n */\n name: string;\n\n /**\n * A JSON schema object describing the parameters of the function.\n */\n parameters: Record<string, unknown> | null;\n\n /**\n * Whether to enforce strict parameter validation. Default `true`.\n */\n strict: boolean | null;\n\n /**\n * The type of the function tool. Always `function`.\n */\n type: 'function';\n\n /**\n * A description of the function. Used by the model to determine whether or not to\n * call the function.\n */\n description?: string | null;\n}\n\nexport interface Response {\n /**\n * Unique identifier for this Response.\n */\n id: string;\n\n /**\n * Unix timestamp (in seconds) of when this Response was created.\n */\n created_at: number;\n\n output_text: string;\n\n /**\n * An error object returned when the model fails to generate a Response.\n */\n error: ResponseError | null;\n\n /**\n * Details about why the response is incomplete.\n */\n incomplete_details: Response.IncompleteDetails | null;\n\n /**\n * Inserts a system (or developer) message as the first item in the model's\n * context.\n *\n * When using along with `previous_response_id`, the instructions from a previous\n * response will not be carried over to the next response. This makes it simple to\n * swap out system (or developer) messages in new responses.\n */\n instructions: string | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a\n * wide range of models with different capabilities, performance characteristics,\n * and price points. Refer to the\n * [model guide](https://platform.openai.com/docs/models) to browse and compare\n * available models.\n */\n model: Shared.ResponsesModel;\n\n /**\n * The object type of this resource - always set to `response`.\n */\n object: 'response';\n\n /**\n * An array of content items generated by the model.\n *\n * - The length and order of items in the `output` array is dependent on the\n * model's response.\n * - Rather than accessing the first item in the `output` array and assuming it's\n * an `assistant` message with the content generated by the model, you might\n * consider using the `output_text` property where supported in SDKs.\n */\n output: Array<ResponseOutputItem>;\n\n /**\n * Whether to allow the model to run tool calls in parallel.\n */\n parallel_tool_calls: boolean;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic. We generally recommend altering this or `top_p` but\n * not both.\n */\n temperature: number | null;\n\n /**\n * How the model should select which tool (or tools) to use when generating a\n * response. See the `tools` parameter to see how to specify which tools the model\n * can call.\n */\n tool_choice: ToolChoiceOptions | ToolChoiceTypes | ToolChoiceFunction;\n\n /**\n * An array of tools the model may call while generating a response. You can\n * specify which tool to use by setting the `tool_choice` parameter.\n *\n * The two categories of tools you can provide the model are:\n *\n * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's\n * capabilities, like\n * [web search](https://platform.openai.com/docs/guides/tools-web-search) or\n * [file search](https://platform.openai.com/docs/guides/tools-file-search).\n * Learn more about\n * [built-in tools](https://platform.openai.com/docs/guides/tools).\n * - **Function calls (custom tools)**: Functions that are defined by you, enabling\n * the model to call your own code. Learn more about\n * [function calling](https://platform.openai.com/docs/guides/function-calling).\n */\n tools: Array<Tool>;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or `temperature` but not both.\n */\n top_p: number | null;\n\n /**\n * Whether to run the model response in the background.\n * [Learn more](https://platform.openai.com/docs/guides/background).\n */\n background?: boolean | null;\n\n /**\n * An upper bound for the number of tokens that can be generated for a response,\n * including visible output tokens and\n * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n */\n max_output_tokens?: number | null;\n\n /**\n * The unique ID of the previous response to the model. Use this to create\n * multi-turn conversations. Learn more about\n * [conversation state](https://platform.openai.com/docs/guides/conversation-state).\n */\n previous_response_id?: string | null;\n\n /**\n * **o-series models only**\n *\n * Configuration options for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning).\n */\n reasoning?: Shared.Reasoning | null;\n\n /**\n * Specifies the latency tier to use for processing the request. This parameter is\n * relevant for customers subscribed to the scale tier service:\n *\n * - If set to 'auto', and the Project is Scale tier enabled, the system will\n * utilize scale tier credits until they are exhausted.\n * - If set to 'auto', and the Project is not Scale tier enabled, the request will\n * be processed using the default service tier with a lower uptime SLA and no\n * latency guarentee.\n * - If set to 'default', the request will be processed using the default service\n * tier with a lower uptime SLA and no latency guarentee.\n * - If set to 'flex', the request will be processed with the Flex Processing\n * service tier.\n * [Learn more](https://platform.openai.com/docs/guides/flex-processing).\n * - When not set, the default behavior is 'auto'.\n *\n * When this parameter is set, the response body will include the `service_tier`\n * utilized.\n */\n service_tier?: 'auto' | 'default' | 'flex' | null;\n\n /**\n * The status of the response generation. One of `completed`, `failed`,\n * `in_progress`, `cancelled`, `queued`, or `incomplete`.\n */\n status?: ResponseStatus;\n\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data. Learn more:\n *\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n */\n text?: ResponseTextConfig;\n\n /**\n * The truncation strategy to use for the model response.\n *\n * - `auto`: If the context of this response and previous ones exceeds the model's\n * context window size, the model will truncate the response to fit the context\n * window by dropping input items in the middle of the conversation.\n * - `disabled` (default): If a model response will exceed the context window size\n * for a model, the request will fail with a 400 error.\n */\n truncation?: 'auto' | 'disabled' | null;\n\n /**\n * Represents token usage details including input tokens, output tokens, a\n * breakdown of output tokens, and the total tokens used.\n */\n usage?: ResponseUsage;\n\n /**\n * A stable identifier for your end-users. Used to boost cache hit rates by better\n * bucketing similar requests and to help OpenAI detect and prevent abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport namespace Response {\n /**\n * Details about why the response is incomplete.\n */\n export interface IncompleteDetails {\n /**\n * The reason why the response is incomplete.\n */\n reason?: 'max_output_tokens' | 'content_filter';\n }\n}\n\n/**\n * Emitted when there is a partial audio response.\n */\nexport interface ResponseAudioDeltaEvent {\n /**\n * A chunk of Base64 encoded response audio bytes.\n */\n delta: string;\n\n /**\n * A sequence number for this chunk of the stream response.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.audio.delta`.\n */\n type: 'response.audio.delta';\n}\n\n/**\n * Emitted when the audio response is complete.\n */\nexport interface ResponseAudioDoneEvent {\n /**\n * The sequence number of the delta.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.audio.done`.\n */\n type: 'response.audio.done';\n}\n\n/**\n * Emitted when there is a partial transcript of audio.\n */\nexport interface ResponseAudioTranscriptDeltaEvent {\n /**\n * The partial transcript of the audio response.\n */\n delta: string;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.audio.transcript.delta`.\n */\n type: 'response.audio.transcript.delta';\n}\n\n/**\n * Emitted when the full audio transcript is completed.\n */\nexport interface ResponseAudioTranscriptDoneEvent {\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.audio.transcript.done`.\n */\n type: 'response.audio.transcript.done';\n}\n\n/**\n * Emitted when a partial code snippet is added by the code interpreter.\n */\nexport interface ResponseCodeInterpreterCallCodeDeltaEvent {\n /**\n * The partial code snippet added by the code interpreter.\n */\n delta: string;\n\n /**\n * The index of the output item that the code interpreter call is in progress.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.code_interpreter_call.code.delta`.\n */\n type: 'response.code_interpreter_call.code.delta';\n}\n\n/**\n * Emitted when code snippet output is finalized by the code interpreter.\n */\nexport interface ResponseCodeInterpreterCallCodeDoneEvent {\n /**\n * The final code snippet output by the code interpreter.\n */\n code: string;\n\n /**\n * The index of the output item that the code interpreter call is in progress.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.code_interpreter_call.code.done`.\n */\n type: 'response.code_interpreter_call.code.done';\n}\n\n/**\n * Emitted when the code interpreter call is completed.\n */\nexport interface ResponseCodeInterpreterCallCompletedEvent {\n /**\n * A tool call to run code.\n */\n code_interpreter_call: ResponseCodeInterpreterToolCall;\n\n /**\n * The index of the output item that the code interpreter call is in progress.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.code_interpreter_call.completed`.\n */\n type: 'response.code_interpreter_call.completed';\n}\n\n/**\n * Emitted when a code interpreter call is in progress.\n */\nexport interface ResponseCodeInterpreterCallInProgressEvent {\n /**\n * A tool call to run code.\n */\n code_interpreter_call: ResponseCodeInterpreterToolCall;\n\n /**\n * The index of the output item that the code interpreter call is in progress.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.code_interpreter_call.in_progress`.\n */\n type: 'response.code_interpreter_call.in_progress';\n}\n\n/**\n * Emitted when the code interpreter is actively interpreting the code snippet.\n */\nexport interface ResponseCodeInterpreterCallInterpretingEvent {\n /**\n * A tool call to run code.\n */\n code_interpreter_call: ResponseCodeInterpreterToolCall;\n\n /**\n * The index of the output item that the code interpreter call is in progress.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.code_interpreter_call.interpreting`.\n */\n type: 'response.code_interpreter_call.interpreting';\n}\n\n/**\n * A tool call to run code.\n */\nexport interface ResponseCodeInterpreterToolCall {\n /**\n * The unique ID of the code interpreter tool call.\n */\n id: string;\n\n /**\n * The code to run.\n */\n code: string;\n\n /**\n * The results of the code interpreter tool call.\n */\n results: Array<ResponseCodeInterpreterToolCall.Logs | ResponseCodeInterpreterToolCall.Files>;\n\n /**\n * The status of the code interpreter tool call.\n */\n status: 'in_progress' | 'interpreting' | 'completed';\n\n /**\n * The type of the code interpreter tool call. Always `code_interpreter_call`.\n */\n type: 'code_interpreter_call';\n\n /**\n * The ID of the container used to run the code.\n */\n container_id?: string;\n}\n\nexport namespace ResponseCodeInterpreterToolCall {\n /**\n * The output of a code interpreter tool call that is text.\n */\n export interface Logs {\n /**\n * The logs of the code interpreter tool call.\n */\n logs: string;\n\n /**\n * The type of the code interpreter text output. Always `logs`.\n */\n type: 'logs';\n }\n\n /**\n * The output of a code interpreter tool call that is a file.\n */\n export interface Files {\n files: Array<Files.File>;\n\n /**\n * The type of the code interpreter file output. Always `files`.\n */\n type: 'files';\n }\n\n export namespace Files {\n export interface File {\n /**\n * The ID of the file.\n */\n file_id: string;\n\n /**\n * The MIME type of the file.\n */\n mime_type: string;\n }\n }\n}\n\n/**\n * Emitted when the model response is complete.\n */\nexport interface ResponseCompletedEvent {\n /**\n * Properties of the completed response.\n */\n response: Response;\n\n /**\n * The sequence number for this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.completed`.\n */\n type: 'response.completed';\n}\n\n/**\n * A tool call to a computer use tool. See the\n * [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use)\n * for more information.\n */\nexport interface ResponseComputerToolCall {\n /**\n * The unique ID of the computer call.\n */\n id: string;\n\n /**\n * A click action.\n */\n action:\n | ResponseComputerToolCall.Click\n | ResponseComputerToolCall.DoubleClick\n | ResponseComputerToolCall.Drag\n | ResponseComputerToolCall.Keypress\n | ResponseComputerToolCall.Move\n | ResponseComputerToolCall.Screenshot\n | ResponseComputerToolCall.Scroll\n | ResponseComputerToolCall.Type\n | ResponseComputerToolCall.Wait;\n\n /**\n * An identifier used when responding to the tool call with output.\n */\n call_id: string;\n\n /**\n * The pending safety checks for the computer call.\n */\n pending_safety_checks: Array<ResponseComputerToolCall.PendingSafetyCheck>;\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the computer call. Always `computer_call`.\n */\n type: 'computer_call';\n}\n\nexport namespace ResponseComputerToolCall {\n /**\n * A click action.\n */\n export interface Click {\n /**\n * Indicates which mouse button was pressed during the click. One of `left`,\n * `right`, `wheel`, `back`, or `forward`.\n */\n button: 'left' | 'right' | 'wheel' | 'back' | 'forward';\n\n /**\n * Specifies the event type. For a click action, this property is always set to\n * `click`.\n */\n type: 'click';\n\n /**\n * The x-coordinate where the click occurred.\n */\n x: number;\n\n /**\n * The y-coordinate where the click occurred.\n */\n y: number;\n }\n\n /**\n * A double click action.\n */\n export interface DoubleClick {\n /**\n * Specifies the event type. For a double click action, this property is always set\n * to `double_click`.\n */\n type: 'double_click';\n\n /**\n * The x-coordinate where the double click occurred.\n */\n x: number;\n\n /**\n * The y-coordinate where the double click occurred.\n */\n y: number;\n }\n\n /**\n * A drag action.\n */\n export interface Drag {\n /**\n * An array of coordinates representing the path of the drag action. Coordinates\n * will appear as an array of objects, eg\n *\n * ```\n * [\n * { x: 100, y: 200 },\n * { x: 200, y: 300 }\n * ]\n * ```\n */\n path: Array<Drag.Path>;\n\n /**\n * Specifies the event type. For a drag action, this property is always set to\n * `drag`.\n */\n type: 'drag';\n }\n\n export namespace Drag {\n /**\n * A series of x/y coordinate pairs in the drag path.\n */\n export interface Path {\n /**\n * The x-coordinate.\n */\n x: number;\n\n /**\n * The y-coordinate.\n */\n y: number;\n }\n }\n\n /**\n * A collection of keypresses the model would like to perform.\n */\n export interface Keypress {\n /**\n * The combination of keys the model is requesting to be pressed. This is an array\n * of strings, each representing a key.\n */\n keys: Array<string>;\n\n /**\n * Specifies the event type. For a keypress action, this property is always set to\n * `keypress`.\n */\n type: 'keypress';\n }\n\n /**\n * A mouse move action.\n */\n export interface Move {\n /**\n * Specifies the event type. For a move action, this property is always set to\n * `move`.\n */\n type: 'move';\n\n /**\n * The x-coordinate to move to.\n */\n x: number;\n\n /**\n * The y-coordinate to move to.\n */\n y: number;\n }\n\n /**\n * A screenshot action.\n */\n export interface Screenshot {\n /**\n * Specifies the event type. For a screenshot action, this property is always set\n * to `screenshot`.\n */\n type: 'screenshot';\n }\n\n /**\n * A scroll action.\n */\n export interface Scroll {\n /**\n * The horizontal scroll distance.\n */\n scroll_x: number;\n\n /**\n * The vertical scroll distance.\n */\n scroll_y: number;\n\n /**\n * Specifies the event type. For a scroll action, this property is always set to\n * `scroll`.\n */\n type: 'scroll';\n\n /**\n * The x-coordinate where the scroll occurred.\n */\n x: number;\n\n /**\n * The y-coordinate where the scroll occurred.\n */\n y: number;\n }\n\n /**\n * An action to type in text.\n */\n export interface Type {\n /**\n * The text to type.\n */\n text: string;\n\n /**\n * Specifies the event type. For a type action, this property is always set to\n * `type`.\n */\n type: 'type';\n }\n\n /**\n * A wait action.\n */\n export interface Wait {\n /**\n * Specifies the event type. For a wait action, this property is always set to\n * `wait`.\n */\n type: 'wait';\n }\n\n /**\n * A pending safety check for the computer call.\n */\n export interface PendingSafetyCheck {\n /**\n * The ID of the pending safety check.\n */\n id: string;\n\n /**\n * The type of the pending safety check.\n */\n code: string;\n\n /**\n * Details about the pending safety check.\n */\n message: string;\n }\n}\n\nexport interface ResponseComputerToolCallOutputItem {\n /**\n * The unique ID of the computer call tool output.\n */\n id: string;\n\n /**\n * The ID of the computer tool call that produced the output.\n */\n call_id: string;\n\n /**\n * A computer screenshot image used with the computer use tool.\n */\n output: ResponseComputerToolCallOutputScreenshot;\n\n /**\n * The type of the computer tool call output. Always `computer_call_output`.\n */\n type: 'computer_call_output';\n\n /**\n * The safety checks reported by the API that have been acknowledged by the\n * developer.\n */\n acknowledged_safety_checks?: Array<ResponseComputerToolCallOutputItem.AcknowledgedSafetyCheck>;\n\n /**\n * The status of the message input. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when input items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete';\n}\n\nexport namespace ResponseComputerToolCallOutputItem {\n /**\n * A pending safety check for the computer call.\n */\n export interface AcknowledgedSafetyCheck {\n /**\n * The ID of the pending safety check.\n */\n id: string;\n\n /**\n * The type of the pending safety check.\n */\n code: string;\n\n /**\n * Details about the pending safety check.\n */\n message: string;\n }\n}\n\n/**\n * A computer screenshot image used with the computer use tool.\n */\nexport interface ResponseComputerToolCallOutputScreenshot {\n /**\n * Specifies the event type. For a computer screenshot, this property is always set\n * to `computer_screenshot`.\n */\n type: 'computer_screenshot';\n\n /**\n * The identifier of an uploaded file that contains the screenshot.\n */\n file_id?: string;\n\n /**\n * The URL of the screenshot image.\n */\n image_url?: string;\n}\n\n/**\n * Multi-modal input and output contents.\n */\nexport type ResponseContent =\n | ResponseInputText\n | ResponseInputImage\n | ResponseInputFile\n | ResponseOutputText\n | ResponseOutputRefusal;\n\n/**\n * Emitted when a new content part is added.\n */\nexport interface ResponseContentPartAddedEvent {\n /**\n * The index of the content part that was added.\n */\n content_index: number;\n\n /**\n * The ID of the output item that the content part was added to.\n */\n item_id: string;\n\n /**\n * The index of the output item that the content part was added to.\n */\n output_index: number;\n\n /**\n * The content part that was added.\n */\n part: ResponseOutputText | ResponseOutputRefusal;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.content_part.added`.\n */\n type: 'response.content_part.added';\n}\n\n/**\n * Emitted when a content part is done.\n */\nexport interface ResponseContentPartDoneEvent {\n /**\n * The index of the content part that is done.\n */\n content_index: number;\n\n /**\n * The ID of the output item that the content part was added to.\n */\n item_id: string;\n\n /**\n * The index of the output item that the content part was added to.\n */\n output_index: number;\n\n /**\n * The content part that is done.\n */\n part: ResponseOutputText | ResponseOutputRefusal;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.content_part.done`.\n */\n type: 'response.content_part.done';\n}\n\n/**\n * An event that is emitted when a response is created.\n */\nexport interface ResponseCreatedEvent {\n /**\n * The response that was created.\n */\n response: Response;\n\n /**\n * The sequence number for this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.created`.\n */\n type: 'response.created';\n}\n\n/**\n * An error object returned when the model fails to generate a Response.\n */\nexport interface ResponseError {\n /**\n * The error code for the response.\n */\n code:\n | 'server_error'\n | 'rate_limit_exceeded'\n | 'invalid_prompt'\n | 'vector_store_timeout'\n | 'invalid_image'\n | 'invalid_image_format'\n | 'invalid_base64_image'\n | 'invalid_image_url'\n | 'image_too_large'\n | 'image_too_small'\n | 'image_parse_error'\n | 'image_content_policy_violation'\n | 'invalid_image_mode'\n | 'image_file_too_large'\n | 'unsupported_image_media_type'\n | 'empty_image_file'\n | 'failed_to_download_image'\n | 'image_file_not_found';\n\n /**\n * A human-readable description of the error.\n */\n message: string;\n}\n\n/**\n * Emitted when an error occurs.\n */\nexport interface ResponseErrorEvent {\n /**\n * The error code.\n */\n code: string | null;\n\n /**\n * The error message.\n */\n message: string;\n\n /**\n * The error parameter.\n */\n param: string | null;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `error`.\n */\n type: 'error';\n}\n\n/**\n * An event that is emitted when a response fails.\n */\nexport interface ResponseFailedEvent {\n /**\n * The response that failed.\n */\n response: Response;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.failed`.\n */\n type: 'response.failed';\n}\n\n/**\n * Emitted when a file search call is completed (results found).\n */\nexport interface ResponseFileSearchCallCompletedEvent {\n /**\n * The ID of the output item that the file search call is initiated.\n */\n item_id: string;\n\n /**\n * The index of the output item that the file search call is initiated.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.file_search_call.completed`.\n */\n type: 'response.file_search_call.completed';\n}\n\n/**\n * Emitted when a file search call is initiated.\n */\nexport interface ResponseFileSearchCallInProgressEvent {\n /**\n * The ID of the output item that the file search call is initiated.\n */\n item_id: string;\n\n /**\n * The index of the output item that the file search call is initiated.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.file_search_call.in_progress`.\n */\n type: 'response.file_search_call.in_progress';\n}\n\n/**\n * Emitted when a file search is currently searching.\n */\nexport interface ResponseFileSearchCallSearchingEvent {\n /**\n * The ID of the output item that the file search call is initiated.\n */\n item_id: string;\n\n /**\n * The index of the output item that the file search call is searching.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.file_search_call.searching`.\n */\n type: 'response.file_search_call.searching';\n}\n\n/**\n * The results of a file search tool call. See the\n * [file search guide](https://platform.openai.com/docs/guides/tools-file-search)\n * for more information.\n */\nexport interface ResponseFileSearchToolCall {\n /**\n * The unique ID of the file search tool call.\n */\n id: string;\n\n /**\n * The queries used to search for files.\n */\n queries: Array<string>;\n\n /**\n * The status of the file search tool call. One of `in_progress`, `searching`,\n * `incomplete` or `failed`,\n */\n status: 'in_progress' | 'searching' | 'completed' | 'incomplete' | 'failed';\n\n /**\n * The type of the file search tool call. Always `file_search_call`.\n */\n type: 'file_search_call';\n\n /**\n * The results of the file search tool call.\n */\n results?: Array<ResponseFileSearchToolCall.Result> | null;\n}\n\nexport namespace ResponseFileSearchToolCall {\n export interface Result {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard. Keys are strings with a maximum\n * length of 64 characters. Values are strings with a maximum length of 512\n * characters, booleans, or numbers.\n */\n attributes?: Record<string, string | number | boolean> | null;\n\n /**\n * The unique ID of the file.\n */\n file_id?: string;\n\n /**\n * The name of the file.\n */\n filename?: string;\n\n /**\n * The relevance score of the file - a value between 0 and 1.\n */\n score?: number;\n\n /**\n * The text that was retrieved from the file.\n */\n text?: string;\n }\n}\n\n/**\n * An object specifying the format that the model must output.\n *\n * Configuring `{ \"type\": \"json_schema\" }` enables Structured Outputs, which\n * ensures the model will match your supplied JSON schema. Learn more in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * The default format is `{ \"type\": \"text\" }` with no additional options.\n *\n * **Not recommended for gpt-4o and newer models:**\n *\n * Setting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\n * ensures the message the model generates is valid JSON. Using `json_schema` is\n * preferred for models that support it.\n */\nexport type ResponseFormatTextConfig =\n | Shared.ResponseFormatText\n | ResponseFormatTextJSONSchemaConfig\n | Shared.ResponseFormatJSONObject;\n\n/**\n * JSON Schema response format. Used to generate structured JSON responses. Learn\n * more about\n * [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n */\nexport interface ResponseFormatTextJSONSchemaConfig {\n /**\n * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores\n * and dashes, with a maximum length of 64.\n */\n name: string;\n\n /**\n * The schema for the response format, described as a JSON Schema object. Learn how\n * to build JSON schemas [here](https://json-schema.org/).\n */\n schema: Record<string, unknown>;\n\n /**\n * The type of response format being defined. Always `json_schema`.\n */\n type: 'json_schema';\n\n /**\n * A description of what the response format is for, used by the model to determine\n * how to respond in the format.\n */\n description?: string;\n\n /**\n * Whether to enable strict schema adherence when generating the output. If set to\n * true, the model will always follow the exact schema defined in the `schema`\n * field. Only a subset of JSON Schema is supported when `strict` is `true`. To\n * learn more, read the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n */\n strict?: boolean | null;\n}\n\n/**\n * Emitted when there is a partial function-call arguments delta.\n */\nexport interface ResponseFunctionCallArgumentsDeltaEvent {\n /**\n * The function-call arguments delta that is added.\n */\n delta: string;\n\n /**\n * The ID of the output item that the function-call arguments delta is added to.\n */\n item_id: string;\n\n /**\n * The index of the output item that the function-call arguments delta is added to.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.function_call_arguments.delta`.\n */\n type: 'response.function_call_arguments.delta';\n}\n\n/**\n * Emitted when function-call arguments are finalized.\n */\nexport interface ResponseFunctionCallArgumentsDoneEvent {\n /**\n * The function-call arguments.\n */\n arguments: string;\n\n /**\n * The ID of the item.\n */\n item_id: string;\n\n /**\n * The index of the output item.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n type: 'response.function_call_arguments.done';\n}\n\n/**\n * A tool call to run a function. See the\n * [function calling guide](https://platform.openai.com/docs/guides/function-calling)\n * for more information.\n */\nexport interface ResponseFunctionToolCall {\n /**\n * A JSON string of the arguments to pass to the function.\n */\n arguments: string;\n\n /**\n * The unique ID of the function tool call generated by the model.\n */\n call_id: string;\n\n /**\n * The name of the function to run.\n */\n name: string;\n\n /**\n * The type of the function tool call. Always `function_call`.\n */\n type: 'function_call';\n\n /**\n * The unique ID of the function tool call.\n */\n id?: string;\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete';\n}\n\n/**\n * A tool call to run a function. See the\n * [function calling guide](https://platform.openai.com/docs/guides/function-calling)\n * for more information.\n */\nexport interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall {\n /**\n * The unique ID of the function tool call.\n */\n id: string;\n}\n\nexport interface ResponseFunctionToolCallOutputItem {\n /**\n * The unique ID of the function call tool output.\n */\n id: string;\n\n /**\n * The unique ID of the function tool call generated by the model.\n */\n call_id: string;\n\n /**\n * A JSON string of the output of the function tool call.\n */\n output: string;\n\n /**\n * The type of the function tool call output. Always `function_call_output`.\n */\n type: 'function_call_output';\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete';\n}\n\n/**\n * The results of a web search tool call. See the\n * [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for\n * more information.\n */\nexport interface ResponseFunctionWebSearch {\n /**\n * The unique ID of the web search tool call.\n */\n id: string;\n\n /**\n * The status of the web search tool call.\n */\n status: 'in_progress' | 'searching' | 'completed' | 'failed';\n\n /**\n * The type of the web search tool call. Always `web_search_call`.\n */\n type: 'web_search_call';\n}\n\n/**\n * Emitted when an image generation tool call has completed and the final image is\n * available.\n */\nexport interface ResponseImageGenCallCompletedEvent {\n /**\n * The unique identifier of the image generation item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.image_generation_call.completed'.\n */\n type: 'response.image_generation_call.completed';\n}\n\n/**\n * Emitted when an image generation tool call is actively generating an image\n * (intermediate state).\n */\nexport interface ResponseImageGenCallGeneratingEvent {\n /**\n * The unique identifier of the image generation item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of the image generation item being processed.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.image_generation_call.generating'.\n */\n type: 'response.image_generation_call.generating';\n}\n\n/**\n * Emitted when an image generation tool call is in progress.\n */\nexport interface ResponseImageGenCallInProgressEvent {\n /**\n * The unique identifier of the image generation item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of the image generation item being processed.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.image_generation_call.in_progress'.\n */\n type: 'response.image_generation_call.in_progress';\n}\n\n/**\n * Emitted when a partial image is available during image generation streaming.\n */\nexport interface ResponseImageGenCallPartialImageEvent {\n /**\n * The unique identifier of the image generation item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * Base64-encoded partial image data, suitable for rendering as an image.\n */\n partial_image_b64: string;\n\n /**\n * 0-based index for the partial image (backend is 1-based, but this is 0-based for\n * the user).\n */\n partial_image_index: number;\n\n /**\n * The sequence number of the image generation item being processed.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.image_generation_call.partial_image'.\n */\n type: 'response.image_generation_call.partial_image';\n}\n\n/**\n * Emitted when the response is in progress.\n */\nexport interface ResponseInProgressEvent {\n /**\n * The response that is in progress.\n */\n response: Response;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.in_progress`.\n */\n type: 'response.in_progress';\n}\n\n/**\n * Specify additional output data to include in the model response. Currently\n * supported values are:\n *\n * - `file_search_call.results`: Include the search results of the file search tool\n * call.\n * - `message.input_image.image_url`: Include image urls from the input message.\n * - `computer_call_output.output.image_url`: Include image urls from the computer\n * call output.\n * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning\n * tokens in reasoning item outputs. This enables reasoning items to be used in\n * multi-turn conversations when using the Responses API statelessly (like when\n * the `store` parameter is set to `false`, or when an organization is enrolled\n * in the zero data retention program).\n */\nexport type ResponseIncludable =\n | 'file_search_call.results'\n | 'message.input_image.image_url'\n | 'computer_call_output.output.image_url'\n | 'reasoning.encrypted_content';\n\n/**\n * An event that is emitted when a response finishes as incomplete.\n */\nexport interface ResponseIncompleteEvent {\n /**\n * The response that was incomplete.\n */\n response: Response;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.incomplete`.\n */\n type: 'response.incomplete';\n}\n\n/**\n * A list of one or many input items to the model, containing different content\n * types.\n */\nexport type ResponseInput = Array<ResponseInputItem>;\n\n/**\n * An audio input to the model.\n */\nexport interface ResponseInputAudio {\n /**\n * Base64-encoded audio data.\n */\n data: string;\n\n /**\n * The format of the audio data. Currently supported formats are `mp3` and `wav`.\n */\n format: 'mp3' | 'wav';\n\n /**\n * The type of the input item. Always `input_audio`.\n */\n type: 'input_audio';\n}\n\n/**\n * A text input to the model.\n */\nexport type ResponseInputContent = ResponseInputText | ResponseInputImage | ResponseInputFile;\n\n/**\n * A file input to the model.\n */\nexport interface ResponseInputFile {\n /**\n * The type of the input item. Always `input_file`.\n */\n type: 'input_file';\n\n /**\n * The content of the file to be sent to the model.\n */\n file_data?: string;\n\n /**\n * The ID of the file to be sent to the model.\n */\n file_id?: string | null;\n\n /**\n * The name of the file to be sent to the model.\n */\n filename?: string;\n}\n\n/**\n * An image input to the model. Learn about\n * [image inputs](https://platform.openai.com/docs/guides/vision).\n */\nexport interface ResponseInputImage {\n /**\n * The detail level of the image to be sent to the model. One of `high`, `low`, or\n * `auto`. Defaults to `auto`.\n */\n detail: 'low' | 'high' | 'auto';\n\n /**\n * The type of the input item. Always `input_image`.\n */\n type: 'input_image';\n\n /**\n * The ID of the file to be sent to the model.\n */\n file_id?: string | null;\n\n /**\n * The URL of the image to be sent to the model. A fully qualified URL or base64\n * encoded image in a data URL.\n */\n image_url?: string | null;\n}\n\n/**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\nexport type ResponseInputItem =\n | EasyInputMessage\n | ResponseInputItem.Message\n | ResponseOutputMessage\n | ResponseFileSearchToolCall\n | ResponseComputerToolCall\n | ResponseInputItem.ComputerCallOutput\n | ResponseFunctionWebSearch\n | ResponseFunctionToolCall\n | ResponseInputItem.FunctionCallOutput\n | ResponseReasoningItem\n | ResponseInputItem.ImageGenerationCall\n | ResponseCodeInterpreterToolCall\n | ResponseInputItem.LocalShellCall\n | ResponseInputItem.LocalShellCallOutput\n | ResponseInputItem.McpListTools\n | ResponseInputItem.McpApprovalRequest\n | ResponseInputItem.McpApprovalResponse\n | ResponseInputItem.McpCall\n | ResponseInputItem.ItemReference;\n\nexport namespace ResponseInputItem {\n /**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role.\n */\n export interface Message {\n /**\n * A list of one or many input items to the model, containing different content\n * types.\n */\n content: ResponsesAPI.ResponseInputMessageContentList;\n\n /**\n * The role of the message input. One of `user`, `system`, or `developer`.\n */\n role: 'user' | 'system' | 'developer';\n\n /**\n * The status of item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the message input. Always set to `message`.\n */\n type?: 'message';\n }\n\n /**\n * The output of a computer tool call.\n */\n export interface ComputerCallOutput {\n /**\n * The ID of the computer tool call that produced the output.\n */\n call_id: string;\n\n /**\n * A computer screenshot image used with the computer use tool.\n */\n output: ResponsesAPI.ResponseComputerToolCallOutputScreenshot;\n\n /**\n * The type of the computer tool call output. Always `computer_call_output`.\n */\n type: 'computer_call_output';\n\n /**\n * The ID of the computer tool call output.\n */\n id?: string | null;\n\n /**\n * The safety checks reported by the API that have been acknowledged by the\n * developer.\n */\n acknowledged_safety_checks?: Array<ComputerCallOutput.AcknowledgedSafetyCheck> | null;\n\n /**\n * The status of the message input. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when input items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete' | null;\n }\n\n export namespace ComputerCallOutput {\n /**\n * A pending safety check for the computer call.\n */\n export interface AcknowledgedSafetyCheck {\n /**\n * The ID of the pending safety check.\n */\n id: string;\n\n /**\n * The type of the pending safety check.\n */\n code?: string | null;\n\n /**\n * Details about the pending safety check.\n */\n message?: string | null;\n }\n }\n\n /**\n * The output of a function tool call.\n */\n export interface FunctionCallOutput {\n /**\n * The unique ID of the function tool call generated by the model.\n */\n call_id: string;\n\n /**\n * A JSON string of the output of the function tool call.\n */\n output: string;\n\n /**\n * The type of the function tool call output. Always `function_call_output`.\n */\n type: 'function_call_output';\n\n /**\n * The unique ID of the function tool call output. Populated when this item is\n * returned via API.\n */\n id?: string | null;\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete' | null;\n }\n\n /**\n * An image generation request made by the model.\n */\n export interface ImageGenerationCall {\n /**\n * The unique ID of the image generation call.\n */\n id: string;\n\n /**\n * The generated image encoded in base64.\n */\n result: string | null;\n\n /**\n * The status of the image generation call.\n */\n status: 'in_progress' | 'completed' | 'generating' | 'failed';\n\n /**\n * The type of the image generation call. Always `image_generation_call`.\n */\n type: 'image_generation_call';\n }\n\n /**\n * A tool call to run a command on the local shell.\n */\n export interface LocalShellCall {\n /**\n * The unique ID of the local shell call.\n */\n id: string;\n\n /**\n * Execute a shell command on the server.\n */\n action: LocalShellCall.Action;\n\n /**\n * The unique ID of the local shell tool call generated by the model.\n */\n call_id: string;\n\n /**\n * The status of the local shell call.\n */\n status: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the local shell call. Always `local_shell_call`.\n */\n type: 'local_shell_call';\n }\n\n export namespace LocalShellCall {\n /**\n * Execute a shell command on the server.\n */\n export interface Action {\n /**\n * The command to run.\n */\n command: Array<string>;\n\n /**\n * Environment variables to set for the command.\n */\n env: Record<string, string>;\n\n /**\n * The type of the local shell action. Always `exec`.\n */\n type: 'exec';\n\n /**\n * Optional timeout in milliseconds for the command.\n */\n timeout_ms?: number | null;\n\n /**\n * Optional user to run the command as.\n */\n user?: string | null;\n\n /**\n * Optional working directory to run the command in.\n */\n working_directory?: string | null;\n }\n }\n\n /**\n * The output of a local shell tool call.\n */\n export interface LocalShellCallOutput {\n /**\n * The unique ID of the local shell tool call generated by the model.\n */\n id: string;\n\n /**\n * A JSON string of the output of the local shell tool call.\n */\n output: string;\n\n /**\n * The type of the local shell tool call output. Always `local_shell_call_output`.\n */\n type: 'local_shell_call_output';\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n */\n status?: 'in_progress' | 'completed' | 'incomplete' | null;\n }\n\n /**\n * A list of tools available on an MCP server.\n */\n export interface McpListTools {\n /**\n * The unique ID of the list.\n */\n id: string;\n\n /**\n * The label of the MCP server.\n */\n server_label: string;\n\n /**\n * The tools available on the server.\n */\n tools: Array<McpListTools.Tool>;\n\n /**\n * The type of the item. Always `mcp_list_tools`.\n */\n type: 'mcp_list_tools';\n\n /**\n * Error message if the server could not list tools.\n */\n error?: string | null;\n }\n\n export namespace McpListTools {\n /**\n * A tool available on an MCP server.\n */\n export interface Tool {\n /**\n * The JSON schema describing the tool's input.\n */\n input_schema: unknown;\n\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * Additional annotations about the tool.\n */\n annotations?: unknown | null;\n\n /**\n * The description of the tool.\n */\n description?: string | null;\n }\n }\n\n /**\n * A request for human approval of a tool invocation.\n */\n export interface McpApprovalRequest {\n /**\n * The unique ID of the approval request.\n */\n id: string;\n\n /**\n * A JSON string of arguments for the tool.\n */\n arguments: string;\n\n /**\n * The name of the tool to run.\n */\n name: string;\n\n /**\n * The label of the MCP server making the request.\n */\n server_label: string;\n\n /**\n * The type of the item. Always `mcp_approval_request`.\n */\n type: 'mcp_approval_request';\n }\n\n /**\n * A response to an MCP approval request.\n */\n export interface McpApprovalResponse {\n /**\n * The ID of the approval request being answered.\n */\n approval_request_id: string;\n\n /**\n * Whether the request was approved.\n */\n approve: boolean;\n\n /**\n * The type of the item. Always `mcp_approval_response`.\n */\n type: 'mcp_approval_response';\n\n /**\n * The unique ID of the approval response\n */\n id?: string | null;\n\n /**\n * Optional reason for the decision.\n */\n reason?: string | null;\n }\n\n /**\n * An invocation of a tool on an MCP server.\n */\n export interface McpCall {\n /**\n * The unique ID of the tool call.\n */\n id: string;\n\n /**\n * A JSON string of the arguments passed to the tool.\n */\n arguments: string;\n\n /**\n * The name of the tool that was run.\n */\n name: string;\n\n /**\n * The label of the MCP server running the tool.\n */\n server_label: string;\n\n /**\n * The type of the item. Always `mcp_call`.\n */\n type: 'mcp_call';\n\n /**\n * The error from the tool call, if any.\n */\n error?: string | null;\n\n /**\n * The output from the tool call.\n */\n output?: string | null;\n }\n\n /**\n * An internal identifier for an item to reference.\n */\n export interface ItemReference {\n /**\n * The ID of the item to reference.\n */\n id: string;\n\n /**\n * The type of item to reference. Always `item_reference`.\n */\n type?: 'item_reference' | null;\n }\n}\n\n/**\n * A list of one or many input items to the model, containing different content\n * types.\n */\nexport type ResponseInputMessageContentList = Array<ResponseInputContent>;\n\nexport interface ResponseInputMessageItem {\n /**\n * The unique ID of the message input.\n */\n id: string;\n\n /**\n * A list of one or many input items to the model, containing different content\n * types.\n */\n content: ResponseInputMessageContentList;\n\n /**\n * The role of the message input. One of `user`, `system`, or `developer`.\n */\n role: 'user' | 'system' | 'developer';\n\n /**\n * The status of item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the message input. Always set to `message`.\n */\n type?: 'message';\n}\n\n/**\n * A text input to the model.\n */\nexport interface ResponseInputText {\n /**\n * The text input to the model.\n */\n text: string;\n\n /**\n * The type of the input item. Always `input_text`.\n */\n type: 'input_text';\n}\n\n/**\n * Content item used to generate a response.\n */\nexport type ResponseItem =\n | ResponseInputMessageItem\n | ResponseOutputMessage\n | ResponseFileSearchToolCall\n | ResponseComputerToolCall\n | ResponseComputerToolCallOutputItem\n | ResponseFunctionWebSearch\n | ResponseFunctionToolCallItem\n | ResponseFunctionToolCallOutputItem\n | ResponseItem.ImageGenerationCall\n | ResponseCodeInterpreterToolCall\n | ResponseItem.LocalShellCall\n | ResponseItem.LocalShellCallOutput\n | ResponseItem.McpListTools\n | ResponseItem.McpApprovalRequest\n | ResponseItem.McpApprovalResponse\n | ResponseItem.McpCall;\n\nexport namespace ResponseItem {\n /**\n * An image generation request made by the model.\n */\n export interface ImageGenerationCall {\n /**\n * The unique ID of the image generation call.\n */\n id: string;\n\n /**\n * The generated image encoded in base64.\n */\n result: string | null;\n\n /**\n * The status of the image generation call.\n */\n status: 'in_progress' | 'completed' | 'generating' | 'failed';\n\n /**\n * The type of the image generation call. Always `image_generation_call`.\n */\n type: 'image_generation_call';\n }\n\n /**\n * A tool call to run a command on the local shell.\n */\n export interface LocalShellCall {\n /**\n * The unique ID of the local shell call.\n */\n id: string;\n\n /**\n * Execute a shell command on the server.\n */\n action: LocalShellCall.Action;\n\n /**\n * The unique ID of the local shell tool call generated by the model.\n */\n call_id: string;\n\n /**\n * The status of the local shell call.\n */\n status: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the local shell call. Always `local_shell_call`.\n */\n type: 'local_shell_call';\n }\n\n export namespace LocalShellCall {\n /**\n * Execute a shell command on the server.\n */\n export interface Action {\n /**\n * The command to run.\n */\n command: Array<string>;\n\n /**\n * Environment variables to set for the command.\n */\n env: Record<string, string>;\n\n /**\n * The type of the local shell action. Always `exec`.\n */\n type: 'exec';\n\n /**\n * Optional timeout in milliseconds for the command.\n */\n timeout_ms?: number | null;\n\n /**\n * Optional user to run the command as.\n */\n user?: string | null;\n\n /**\n * Optional working directory to run the command in.\n */\n working_directory?: string | null;\n }\n }\n\n /**\n * The output of a local shell tool call.\n */\n export interface LocalShellCallOutput {\n /**\n * The unique ID of the local shell tool call generated by the model.\n */\n id: string;\n\n /**\n * A JSON string of the output of the local shell tool call.\n */\n output: string;\n\n /**\n * The type of the local shell tool call output. Always `local_shell_call_output`.\n */\n type: 'local_shell_call_output';\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n */\n status?: 'in_progress' | 'completed' | 'incomplete' | null;\n }\n\n /**\n * A list of tools available on an MCP server.\n */\n export interface McpListTools {\n /**\n * The unique ID of the list.\n */\n id: string;\n\n /**\n * The label of the MCP server.\n */\n server_label: string;\n\n /**\n * The tools available on the server.\n */\n tools: Array<McpListTools.Tool>;\n\n /**\n * The type of the item. Always `mcp_list_tools`.\n */\n type: 'mcp_list_tools';\n\n /**\n * Error message if the server could not list tools.\n */\n error?: string | null;\n }\n\n export namespace McpListTools {\n /**\n * A tool available on an MCP server.\n */\n export interface Tool {\n /**\n * The JSON schema describing the tool's input.\n */\n input_schema: unknown;\n\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * Additional annotations about the tool.\n */\n annotations?: unknown | null;\n\n /**\n * The description of the tool.\n */\n description?: string | null;\n }\n }\n\n /**\n * A request for human approval of a tool invocation.\n */\n export interface McpApprovalRequest {\n /**\n * The unique ID of the approval request.\n */\n id: string;\n\n /**\n * A JSON string of arguments for the tool.\n */\n arguments: string;\n\n /**\n * The name of the tool to run.\n */\n name: string;\n\n /**\n * The label of the MCP server making the request.\n */\n server_label: string;\n\n /**\n * The type of the item. Always `mcp_approval_request`.\n */\n type: 'mcp_approval_request';\n }\n\n /**\n * A response to an MCP approval request.\n */\n export interface McpApprovalResponse {\n /**\n * The unique ID of the approval response\n */\n id: string;\n\n /**\n * The ID of the approval request being answered.\n */\n approval_request_id: string;\n\n /**\n * Whether the request was approved.\n */\n approve: boolean;\n\n /**\n * The type of the item. Always `mcp_approval_response`.\n */\n type: 'mcp_approval_response';\n\n /**\n * Optional reason for the decision.\n */\n reason?: string | null;\n }\n\n /**\n * An invocation of a tool on an MCP server.\n */\n export interface McpCall {\n /**\n * The unique ID of the tool call.\n */\n id: string;\n\n /**\n * A JSON string of the arguments passed to the tool.\n */\n arguments: string;\n\n /**\n * The name of the tool that was run.\n */\n name: string;\n\n /**\n * The label of the MCP server running the tool.\n */\n server_label: string;\n\n /**\n * The type of the item. Always `mcp_call`.\n */\n type: 'mcp_call';\n\n /**\n * The error from the tool call, if any.\n */\n error?: string | null;\n\n /**\n * The output from the tool call.\n */\n output?: string | null;\n }\n}\n\n/**\n * Emitted when there is a delta (partial update) to the arguments of an MCP tool\n * call.\n */\nexport interface ResponseMcpCallArgumentsDeltaEvent {\n /**\n * The partial update to the arguments for the MCP tool call.\n */\n delta: unknown;\n\n /**\n * The unique identifier of the MCP tool call item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_call.arguments_delta'.\n */\n type: 'response.mcp_call.arguments_delta';\n}\n\n/**\n * Emitted when the arguments for an MCP tool call are finalized.\n */\nexport interface ResponseMcpCallArgumentsDoneEvent {\n /**\n * The finalized arguments for the MCP tool call.\n */\n arguments: unknown;\n\n /**\n * The unique identifier of the MCP tool call item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_call.arguments_done'.\n */\n type: 'response.mcp_call.arguments_done';\n}\n\n/**\n * Emitted when an MCP tool call has completed successfully.\n */\nexport interface ResponseMcpCallCompletedEvent {\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_call.completed'.\n */\n type: 'response.mcp_call.completed';\n}\n\n/**\n * Emitted when an MCP tool call has failed.\n */\nexport interface ResponseMcpCallFailedEvent {\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_call.failed'.\n */\n type: 'response.mcp_call.failed';\n}\n\n/**\n * Emitted when an MCP tool call is in progress.\n */\nexport interface ResponseMcpCallInProgressEvent {\n /**\n * The unique identifier of the MCP tool call item being processed.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_call.in_progress'.\n */\n type: 'response.mcp_call.in_progress';\n}\n\n/**\n * Emitted when the list of available MCP tools has been successfully retrieved.\n */\nexport interface ResponseMcpListToolsCompletedEvent {\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_list_tools.completed'.\n */\n type: 'response.mcp_list_tools.completed';\n}\n\n/**\n * Emitted when the attempt to list available MCP tools has failed.\n */\nexport interface ResponseMcpListToolsFailedEvent {\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_list_tools.failed'.\n */\n type: 'response.mcp_list_tools.failed';\n}\n\n/**\n * Emitted when the system is in the process of retrieving the list of available\n * MCP tools.\n */\nexport interface ResponseMcpListToolsInProgressEvent {\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.mcp_list_tools.in_progress'.\n */\n type: 'response.mcp_list_tools.in_progress';\n}\n\n/**\n * An audio output from the model.\n */\nexport interface ResponseOutputAudio {\n /**\n * Base64-encoded audio data from the model.\n */\n data: string;\n\n /**\n * The transcript of the audio data from the model.\n */\n transcript: string;\n\n /**\n * The type of the output audio. Always `output_audio`.\n */\n type: 'output_audio';\n}\n\n/**\n * An output message from the model.\n */\nexport type ResponseOutputItem =\n | ResponseOutputMessage\n | ResponseFileSearchToolCall\n | ResponseFunctionToolCall\n | ResponseFunctionWebSearch\n | ResponseComputerToolCall\n | ResponseReasoningItem\n | ResponseOutputItem.ImageGenerationCall\n | ResponseCodeInterpreterToolCall\n | ResponseOutputItem.LocalShellCall\n | ResponseOutputItem.McpCall\n | ResponseOutputItem.McpListTools\n | ResponseOutputItem.McpApprovalRequest;\n\nexport namespace ResponseOutputItem {\n /**\n * An image generation request made by the model.\n */\n export interface ImageGenerationCall {\n /**\n * The unique ID of the image generation call.\n */\n id: string;\n\n /**\n * The generated image encoded in base64.\n */\n result: string | null;\n\n /**\n * The status of the image generation call.\n */\n status: 'in_progress' | 'completed' | 'generating' | 'failed';\n\n /**\n * The type of the image generation call. Always `image_generation_call`.\n */\n type: 'image_generation_call';\n }\n\n /**\n * A tool call to run a command on the local shell.\n */\n export interface LocalShellCall {\n /**\n * The unique ID of the local shell call.\n */\n id: string;\n\n /**\n * Execute a shell command on the server.\n */\n action: LocalShellCall.Action;\n\n /**\n * The unique ID of the local shell tool call generated by the model.\n */\n call_id: string;\n\n /**\n * The status of the local shell call.\n */\n status: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the local shell call. Always `local_shell_call`.\n */\n type: 'local_shell_call';\n }\n\n export namespace LocalShellCall {\n /**\n * Execute a shell command on the server.\n */\n export interface Action {\n /**\n * The command to run.\n */\n command: Array<string>;\n\n /**\n * Environment variables to set for the command.\n */\n env: Record<string, string>;\n\n /**\n * The type of the local shell action. Always `exec`.\n */\n type: 'exec';\n\n /**\n * Optional timeout in milliseconds for the command.\n */\n timeout_ms?: number | null;\n\n /**\n * Optional user to run the command as.\n */\n user?: string | null;\n\n /**\n * Optional working directory to run the command in.\n */\n working_directory?: string | null;\n }\n }\n\n /**\n * An invocation of a tool on an MCP server.\n */\n export interface McpCall {\n /**\n * The unique ID of the tool call.\n */\n id: string;\n\n /**\n * A JSON string of the arguments passed to the tool.\n */\n arguments: string;\n\n /**\n * The name of the tool that was run.\n */\n name: string;\n\n /**\n * The label of the MCP server running the tool.\n */\n server_label: string;\n\n /**\n * The type of the item. Always `mcp_call`.\n */\n type: 'mcp_call';\n\n /**\n * The error from the tool call, if any.\n */\n error?: string | null;\n\n /**\n * The output from the tool call.\n */\n output?: string | null;\n }\n\n /**\n * A list of tools available on an MCP server.\n */\n export interface McpListTools {\n /**\n * The unique ID of the list.\n */\n id: string;\n\n /**\n * The label of the MCP server.\n */\n server_label: string;\n\n /**\n * The tools available on the server.\n */\n tools: Array<McpListTools.Tool>;\n\n /**\n * The type of the item. Always `mcp_list_tools`.\n */\n type: 'mcp_list_tools';\n\n /**\n * Error message if the server could not list tools.\n */\n error?: string | null;\n }\n\n export namespace McpListTools {\n /**\n * A tool available on an MCP server.\n */\n export interface Tool {\n /**\n * The JSON schema describing the tool's input.\n */\n input_schema: unknown;\n\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * Additional annotations about the tool.\n */\n annotations?: unknown | null;\n\n /**\n * The description of the tool.\n */\n description?: string | null;\n }\n }\n\n /**\n * A request for human approval of a tool invocation.\n */\n export interface McpApprovalRequest {\n /**\n * The unique ID of the approval request.\n */\n id: string;\n\n /**\n * A JSON string of arguments for the tool.\n */\n arguments: string;\n\n /**\n * The name of the tool to run.\n */\n name: string;\n\n /**\n * The label of the MCP server making the request.\n */\n server_label: string;\n\n /**\n * The type of the item. Always `mcp_approval_request`.\n */\n type: 'mcp_approval_request';\n }\n}\n\n/**\n * Emitted when a new output item is added.\n */\nexport interface ResponseOutputItemAddedEvent {\n /**\n * The output item that was added.\n */\n item: ResponseOutputItem;\n\n /**\n * The index of the output item that was added.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.output_item.added`.\n */\n type: 'response.output_item.added';\n}\n\n/**\n * Emitted when an output item is marked done.\n */\nexport interface ResponseOutputItemDoneEvent {\n /**\n * The output item that was marked done.\n */\n item: ResponseOutputItem;\n\n /**\n * The index of the output item that was marked done.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.output_item.done`.\n */\n type: 'response.output_item.done';\n}\n\n/**\n * An output message from the model.\n */\nexport interface ResponseOutputMessage {\n /**\n * The unique ID of the output message.\n */\n id: string;\n\n /**\n * The content of the output message.\n */\n content: Array<ResponseOutputText | ResponseOutputRefusal>;\n\n /**\n * The role of the output message. Always `assistant`.\n */\n role: 'assistant';\n\n /**\n * The status of the message input. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when input items are returned via API.\n */\n status: 'in_progress' | 'completed' | 'incomplete';\n\n /**\n * The type of the output message. Always `message`.\n */\n type: 'message';\n}\n\n/**\n * A refusal from the model.\n */\nexport interface ResponseOutputRefusal {\n /**\n * The refusal explanationfrom the model.\n */\n refusal: string;\n\n /**\n * The type of the refusal. Always `refusal`.\n */\n type: 'refusal';\n}\n\n/**\n * A text output from the model.\n */\nexport interface ResponseOutputText {\n /**\n * The annotations of the text output.\n */\n annotations: Array<\n ResponseOutputText.FileCitation | ResponseOutputText.URLCitation | ResponseOutputText.FilePath\n >;\n\n /**\n * The text output from the model.\n */\n text: string;\n\n /**\n * The type of the output text. Always `output_text`.\n */\n type: 'output_text';\n\n logprobs?: Array<ResponseOutputText.Logprob>;\n}\n\nexport namespace ResponseOutputText {\n /**\n * A citation to a file.\n */\n export interface FileCitation {\n /**\n * The ID of the file.\n */\n file_id: string;\n\n /**\n * The index of the file in the list of files.\n */\n index: number;\n\n /**\n * The type of the file citation. Always `file_citation`.\n */\n type: 'file_citation';\n }\n\n /**\n * A citation for a web resource used to generate a model response.\n */\n export interface URLCitation {\n /**\n * The index of the last character of the URL citation in the message.\n */\n end_index: number;\n\n /**\n * The index of the first character of the URL citation in the message.\n */\n start_index: number;\n\n /**\n * The title of the web resource.\n */\n title: string;\n\n /**\n * The type of the URL citation. Always `url_citation`.\n */\n type: 'url_citation';\n\n /**\n * The URL of the web resource.\n */\n url: string;\n }\n\n /**\n * A path to a file.\n */\n export interface FilePath {\n /**\n * The ID of the file.\n */\n file_id: string;\n\n /**\n * The index of the file in the list of files.\n */\n index: number;\n\n /**\n * The type of the file path. Always `file_path`.\n */\n type: 'file_path';\n }\n\n /**\n * The log probability of a token.\n */\n export interface Logprob {\n token: string;\n\n bytes: Array<number>;\n\n logprob: number;\n\n top_logprobs: Array<Logprob.TopLogprob>;\n }\n\n export namespace Logprob {\n /**\n * The top log probability of a token.\n */\n export interface TopLogprob {\n token: string;\n\n bytes: Array<number>;\n\n logprob: number;\n }\n }\n}\n\n/**\n * Emitted when an annotation is added to output text content.\n */\nexport interface ResponseOutputTextAnnotationAddedEvent {\n /**\n * The annotation object being added. (See annotation schema for details.)\n */\n annotation: unknown;\n\n /**\n * The index of the annotation within the content part.\n */\n annotation_index: number;\n\n /**\n * The index of the content part within the output item.\n */\n content_index: number;\n\n /**\n * The unique identifier of the item to which the annotation is being added.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.output_text_annotation.added'.\n */\n type: 'response.output_text_annotation.added';\n}\n\n/**\n * Emitted when a response is queued and waiting to be processed.\n */\nexport interface ResponseQueuedEvent {\n /**\n * The full response object that is queued.\n */\n response: Response;\n\n /**\n * The sequence number for this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.queued'.\n */\n type: 'response.queued';\n}\n\n/**\n * Emitted when there is a delta (partial update) to the reasoning content.\n */\nexport interface ResponseReasoningDeltaEvent {\n /**\n * The index of the reasoning content part within the output item.\n */\n content_index: number;\n\n /**\n * The partial update to the reasoning content.\n */\n delta: unknown;\n\n /**\n * The unique identifier of the item for which reasoning is being updated.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always 'response.reasoning.delta'.\n */\n type: 'response.reasoning.delta';\n}\n\n/**\n * Emitted when the reasoning content is finalized for an item.\n */\nexport interface ResponseReasoningDoneEvent {\n /**\n * The index of the reasoning content part within the output item.\n */\n content_index: number;\n\n /**\n * The unique identifier of the item for which reasoning is finalized.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The finalized reasoning text.\n */\n text: string;\n\n /**\n * The type of the event. Always 'response.reasoning.done'.\n */\n type: 'response.reasoning.done';\n}\n\n/**\n * A description of the chain of thought used by a reasoning model while generating\n * a response. Be sure to include these items in your `input` to the Responses API\n * for subsequent turns of a conversation if you are manually\n * [managing context](https://platform.openai.com/docs/guides/conversation-state).\n */\nexport interface ResponseReasoningItem {\n /**\n * The unique identifier of the reasoning content.\n */\n id: string;\n\n /**\n * Reasoning text contents.\n */\n summary: Array<ResponseReasoningItem.Summary>;\n\n /**\n * The type of the object. Always `reasoning`.\n */\n type: 'reasoning';\n\n /**\n * The encrypted content of the reasoning item - populated when a response is\n * generated with `reasoning.encrypted_content` in the `include` parameter.\n */\n encrypted_content?: string | null;\n\n /**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n * Populated when items are returned via API.\n */\n status?: 'in_progress' | 'completed' | 'incomplete';\n}\n\nexport namespace ResponseReasoningItem {\n export interface Summary {\n /**\n * A short summary of the reasoning used by the model when generating the response.\n */\n text: string;\n\n /**\n * The type of the object. Always `summary_text`.\n */\n type: 'summary_text';\n }\n}\n\n/**\n * Emitted when there is a delta (partial update) to the reasoning summary content.\n */\nexport interface ResponseReasoningSummaryDeltaEvent {\n /**\n * The partial update to the reasoning summary content.\n */\n delta: unknown;\n\n /**\n * The unique identifier of the item for which the reasoning summary is being\n * updated.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The index of the summary part within the output item.\n */\n summary_index: number;\n\n /**\n * The type of the event. Always 'response.reasoning_summary.delta'.\n */\n type: 'response.reasoning_summary.delta';\n}\n\n/**\n * Emitted when the reasoning summary content is finalized for an item.\n */\nexport interface ResponseReasoningSummaryDoneEvent {\n /**\n * The unique identifier of the item for which the reasoning summary is finalized.\n */\n item_id: string;\n\n /**\n * The index of the output item in the response's output array.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The index of the summary part within the output item.\n */\n summary_index: number;\n\n /**\n * The finalized reasoning summary text.\n */\n text: string;\n\n /**\n * The type of the event. Always 'response.reasoning_summary.done'.\n */\n type: 'response.reasoning_summary.done';\n}\n\n/**\n * Emitted when a new reasoning summary part is added.\n */\nexport interface ResponseReasoningSummaryPartAddedEvent {\n /**\n * The ID of the item this summary part is associated with.\n */\n item_id: string;\n\n /**\n * The index of the output item this summary part is associated with.\n */\n output_index: number;\n\n /**\n * The summary part that was added.\n */\n part: ResponseReasoningSummaryPartAddedEvent.Part;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The index of the summary part within the reasoning summary.\n */\n summary_index: number;\n\n /**\n * The type of the event. Always `response.reasoning_summary_part.added`.\n */\n type: 'response.reasoning_summary_part.added';\n}\n\nexport namespace ResponseReasoningSummaryPartAddedEvent {\n /**\n * The summary part that was added.\n */\n export interface Part {\n /**\n * The text of the summary part.\n */\n text: string;\n\n /**\n * The type of the summary part. Always `summary_text`.\n */\n type: 'summary_text';\n }\n}\n\n/**\n * Emitted when a reasoning summary part is completed.\n */\nexport interface ResponseReasoningSummaryPartDoneEvent {\n /**\n * The ID of the item this summary part is associated with.\n */\n item_id: string;\n\n /**\n * The index of the output item this summary part is associated with.\n */\n output_index: number;\n\n /**\n * The completed summary part.\n */\n part: ResponseReasoningSummaryPartDoneEvent.Part;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The index of the summary part within the reasoning summary.\n */\n summary_index: number;\n\n /**\n * The type of the event. Always `response.reasoning_summary_part.done`.\n */\n type: 'response.reasoning_summary_part.done';\n}\n\nexport namespace ResponseReasoningSummaryPartDoneEvent {\n /**\n * The completed summary part.\n */\n export interface Part {\n /**\n * The text of the summary part.\n */\n text: string;\n\n /**\n * The type of the summary part. Always `summary_text`.\n */\n type: 'summary_text';\n }\n}\n\n/**\n * Emitted when a delta is added to a reasoning summary text.\n */\nexport interface ResponseReasoningSummaryTextDeltaEvent {\n /**\n * The text delta that was added to the summary.\n */\n delta: string;\n\n /**\n * The ID of the item this summary text delta is associated with.\n */\n item_id: string;\n\n /**\n * The index of the output item this summary text delta is associated with.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The index of the summary part within the reasoning summary.\n */\n summary_index: number;\n\n /**\n * The type of the event. Always `response.reasoning_summary_text.delta`.\n */\n type: 'response.reasoning_summary_text.delta';\n}\n\n/**\n * Emitted when a reasoning summary text is completed.\n */\nexport interface ResponseReasoningSummaryTextDoneEvent {\n /**\n * The ID of the item this summary text is associated with.\n */\n item_id: string;\n\n /**\n * The index of the output item this summary text is associated with.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The index of the summary part within the reasoning summary.\n */\n summary_index: number;\n\n /**\n * The full text of the completed reasoning summary.\n */\n text: string;\n\n /**\n * The type of the event. Always `response.reasoning_summary_text.done`.\n */\n type: 'response.reasoning_summary_text.done';\n}\n\n/**\n * Emitted when there is a partial refusal text.\n */\nexport interface ResponseRefusalDeltaEvent {\n /**\n * The index of the content part that the refusal text is added to.\n */\n content_index: number;\n\n /**\n * The refusal text that is added.\n */\n delta: string;\n\n /**\n * The ID of the output item that the refusal text is added to.\n */\n item_id: string;\n\n /**\n * The index of the output item that the refusal text is added to.\n */\n output_index: number;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.refusal.delta`.\n */\n type: 'response.refusal.delta';\n}\n\n/**\n * Emitted when refusal text is finalized.\n */\nexport interface ResponseRefusalDoneEvent {\n /**\n * The index of the content part that the refusal text is finalized.\n */\n content_index: number;\n\n /**\n * The ID of the output item that the refusal text is finalized.\n */\n item_id: string;\n\n /**\n * The index of the output item that the refusal text is finalized.\n */\n output_index: number;\n\n /**\n * The refusal text that is finalized.\n */\n refusal: string;\n\n /**\n * The sequence number of this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.refusal.done`.\n */\n type: 'response.refusal.done';\n}\n\n/**\n * The status of the response generation. One of `completed`, `failed`,\n * `in_progress`, `cancelled`, `queued`, or `incomplete`.\n */\nexport type ResponseStatus = 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';\n\n/**\n * Emitted when there is a partial audio response.\n */\nexport type ResponseStreamEvent =\n | ResponseAudioDeltaEvent\n | ResponseAudioDoneEvent\n | ResponseAudioTranscriptDeltaEvent\n | ResponseAudioTranscriptDoneEvent\n | ResponseCodeInterpreterCallCodeDeltaEvent\n | ResponseCodeInterpreterCallCodeDoneEvent\n | ResponseCodeInterpreterCallCompletedEvent\n | ResponseCodeInterpreterCallInProgressEvent\n | ResponseCodeInterpreterCallInterpretingEvent\n | ResponseCompletedEvent\n | ResponseContentPartAddedEvent\n | ResponseContentPartDoneEvent\n | ResponseCreatedEvent\n | ResponseErrorEvent\n | ResponseFileSearchCallCompletedEvent\n | ResponseFileSearchCallInProgressEvent\n | ResponseFileSearchCallSearchingEvent\n | ResponseFunctionCallArgumentsDeltaEvent\n | ResponseFunctionCallArgumentsDoneEvent\n | ResponseInProgressEvent\n | ResponseFailedEvent\n | ResponseIncompleteEvent\n | ResponseOutputItemAddedEvent\n | ResponseOutputItemDoneEvent\n | ResponseReasoningSummaryPartAddedEvent\n | ResponseReasoningSummaryPartDoneEvent\n | ResponseReasoningSummaryTextDeltaEvent\n | ResponseReasoningSummaryTextDoneEvent\n | ResponseRefusalDeltaEvent\n | ResponseRefusalDoneEvent\n | ResponseTextDeltaEvent\n | ResponseTextDoneEvent\n | ResponseWebSearchCallCompletedEvent\n | ResponseWebSearchCallInProgressEvent\n | ResponseWebSearchCallSearchingEvent\n | ResponseImageGenCallCompletedEvent\n | ResponseImageGenCallGeneratingEvent\n | ResponseImageGenCallInProgressEvent\n | ResponseImageGenCallPartialImageEvent\n | ResponseMcpCallArgumentsDeltaEvent\n | ResponseMcpCallArgumentsDoneEvent\n | ResponseMcpCallCompletedEvent\n | ResponseMcpCallFailedEvent\n | ResponseMcpCallInProgressEvent\n | ResponseMcpListToolsCompletedEvent\n | ResponseMcpListToolsFailedEvent\n | ResponseMcpListToolsInProgressEvent\n | ResponseOutputTextAnnotationAddedEvent\n | ResponseQueuedEvent\n | ResponseReasoningDeltaEvent\n | ResponseReasoningDoneEvent\n | ResponseReasoningSummaryDeltaEvent\n | ResponseReasoningSummaryDoneEvent;\n\n/**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data. Learn more:\n *\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n */\nexport interface ResponseTextConfig {\n /**\n * An object specifying the format that the model must output.\n *\n * Configuring `{ \"type\": \"json_schema\" }` enables Structured Outputs, which\n * ensures the model will match your supplied JSON schema. Learn more in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * The default format is `{ \"type\": \"text\" }` with no additional options.\n *\n * **Not recommended for gpt-4o and newer models:**\n *\n * Setting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\n * ensures the message the model generates is valid JSON. Using `json_schema` is\n * preferred for models that support it.\n */\n format?: ResponseFormatTextConfig;\n}\n\n/**\n * Emitted when there is an additional text delta.\n */\nexport interface ResponseTextDeltaEvent {\n /**\n * The index of the content part that the text delta was added to.\n */\n content_index: number;\n\n /**\n * The text delta that was added.\n */\n delta: string;\n\n /**\n * The ID of the output item that the text delta was added to.\n */\n item_id: string;\n\n /**\n * The index of the output item that the text delta was added to.\n */\n output_index: number;\n\n /**\n * The sequence number for this event.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.output_text.delta`.\n */\n type: 'response.output_text.delta';\n}\n\n/**\n * Emitted when text content is finalized.\n */\nexport interface ResponseTextDoneEvent {\n /**\n * The index of the content part that the text content is finalized.\n */\n content_index: number;\n\n /**\n * The ID of the output item that the text content is finalized.\n */\n item_id: string;\n\n /**\n * The index of the output item that the text content is finalized.\n */\n output_index: number;\n\n /**\n * The sequence number for this event.\n */\n sequence_number: number;\n\n /**\n * The text content that is finalized.\n */\n text: string;\n\n /**\n * The type of the event. Always `response.output_text.done`.\n */\n type: 'response.output_text.done';\n}\n\n/**\n * Represents token usage details including input tokens, output tokens, a\n * breakdown of output tokens, and the total tokens used.\n */\nexport interface ResponseUsage {\n /**\n * The number of input tokens.\n */\n input_tokens: number;\n\n /**\n * A detailed breakdown of the input tokens.\n */\n input_tokens_details: ResponseUsage.InputTokensDetails;\n\n /**\n * The number of output tokens.\n */\n output_tokens: number;\n\n /**\n * A detailed breakdown of the output tokens.\n */\n output_tokens_details: ResponseUsage.OutputTokensDetails;\n\n /**\n * The total number of tokens used.\n */\n total_tokens: number;\n}\n\nexport namespace ResponseUsage {\n /**\n * A detailed breakdown of the input tokens.\n */\n export interface InputTokensDetails {\n /**\n * The number of tokens that were retrieved from the cache.\n * [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n */\n cached_tokens: number;\n }\n\n /**\n * A detailed breakdown of the output tokens.\n */\n export interface OutputTokensDetails {\n /**\n * The number of reasoning tokens.\n */\n reasoning_tokens: number;\n }\n}\n\n/**\n * Emitted when a web search call is completed.\n */\nexport interface ResponseWebSearchCallCompletedEvent {\n /**\n * Unique ID for the output item associated with the web search call.\n */\n item_id: string;\n\n /**\n * The index of the output item that the web search call is associated with.\n */\n output_index: number;\n\n /**\n * The sequence number of the web search call being processed.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.web_search_call.completed`.\n */\n type: 'response.web_search_call.completed';\n}\n\n/**\n * Emitted when a web search call is initiated.\n */\nexport interface ResponseWebSearchCallInProgressEvent {\n /**\n * Unique ID for the output item associated with the web search call.\n */\n item_id: string;\n\n /**\n * The index of the output item that the web search call is associated with.\n */\n output_index: number;\n\n /**\n * The sequence number of the web search call being processed.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.web_search_call.in_progress`.\n */\n type: 'response.web_search_call.in_progress';\n}\n\n/**\n * Emitted when a web search call is executing.\n */\nexport interface ResponseWebSearchCallSearchingEvent {\n /**\n * Unique ID for the output item associated with the web search call.\n */\n item_id: string;\n\n /**\n * The index of the output item that the web search call is associated with.\n */\n output_index: number;\n\n /**\n * The sequence number of the web search call being processed.\n */\n sequence_number: number;\n\n /**\n * The type of the event. Always `response.web_search_call.searching`.\n */\n type: 'response.web_search_call.searching';\n}\n\n/**\n * A tool that can be used to generate a response.\n */\nexport type Tool =\n | FunctionTool\n | FileSearchTool\n | WebSearchTool\n | ComputerTool\n | Tool.Mcp\n | Tool.CodeInterpreter\n | Tool.ImageGeneration\n | Tool.LocalShell;\n\nexport namespace Tool {\n /**\n * Give the model access to additional tools via remote Model Context Protocol\n * (MCP) servers.\n * [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp).\n */\n export interface Mcp {\n /**\n * A label for this MCP server, used to identify it in tool calls.\n */\n server_label: string;\n\n /**\n * The URL for the MCP server.\n */\n server_url: string;\n\n /**\n * The type of the MCP tool. Always `mcp`.\n */\n type: 'mcp';\n\n /**\n * List of allowed tool names or a filter object.\n */\n allowed_tools?: Array<string> | Mcp.McpAllowedToolsFilter | null;\n\n /**\n * Optional HTTP headers to send to the MCP server. Use for authentication or other\n * purposes.\n */\n headers?: Record<string, string> | null;\n\n /**\n * Specify which of the MCP server's tools require approval.\n */\n require_approval?: Mcp.McpToolApprovalFilter | 'always' | 'never' | null;\n }\n\n export namespace Mcp {\n /**\n * A filter object to specify which tools are allowed.\n */\n export interface McpAllowedToolsFilter {\n /**\n * List of allowed tool names.\n */\n tool_names?: Array<string>;\n }\n\n export interface McpToolApprovalFilter {\n /**\n * A list of tools that always require approval.\n */\n always?: McpToolApprovalFilter.Always;\n\n /**\n * A list of tools that never require approval.\n */\n never?: McpToolApprovalFilter.Never;\n }\n\n export namespace McpToolApprovalFilter {\n /**\n * A list of tools that always require approval.\n */\n export interface Always {\n /**\n * List of tools that require approval.\n */\n tool_names?: Array<string>;\n }\n\n /**\n * A list of tools that never require approval.\n */\n export interface Never {\n /**\n * List of tools that do not require approval.\n */\n tool_names?: Array<string>;\n }\n }\n }\n\n /**\n * A tool that runs Python code to help generate a response to a prompt.\n */\n export interface CodeInterpreter {\n /**\n * The code interpreter container. Can be a container ID or an object that\n * specifies uploaded file IDs to make available to your code.\n */\n container: string | CodeInterpreter.CodeInterpreterToolAuto;\n\n /**\n * The type of the code interpreter tool. Always `code_interpreter`.\n */\n type: 'code_interpreter';\n }\n\n export namespace CodeInterpreter {\n /**\n * Configuration for a code interpreter container. Optionally specify the IDs of\n * the files to run the code on.\n */\n export interface CodeInterpreterToolAuto {\n /**\n * Always `auto`.\n */\n type: 'auto';\n\n /**\n * An optional list of uploaded files to make available to your code.\n */\n file_ids?: Array<string>;\n }\n }\n\n /**\n * A tool that generates images using a model like `gpt-image-1`.\n */\n export interface ImageGeneration {\n /**\n * The type of the image generation tool. Always `image_generation`.\n */\n type: 'image_generation';\n\n /**\n * Background type for the generated image. One of `transparent`, `opaque`, or\n * `auto`. Default: `auto`.\n */\n background?: 'transparent' | 'opaque' | 'auto';\n\n /**\n * Optional mask for inpainting. Contains `image_url` (string, optional) and\n * `file_id` (string, optional).\n */\n input_image_mask?: ImageGeneration.InputImageMask;\n\n /**\n * The image generation model to use. Default: `gpt-image-1`.\n */\n model?: 'gpt-image-1';\n\n /**\n * Moderation level for the generated image. Default: `auto`.\n */\n moderation?: 'auto' | 'low';\n\n /**\n * Compression level for the output image. Default: 100.\n */\n output_compression?: number;\n\n /**\n * The output format of the generated image. One of `png`, `webp`, or `jpeg`.\n * Default: `png`.\n */\n output_format?: 'png' | 'webp' | 'jpeg';\n\n /**\n * Number of partial images to generate in streaming mode, from 0 (default value)\n * to 3.\n */\n partial_images?: number;\n\n /**\n * The quality of the generated image. One of `low`, `medium`, `high`, or `auto`.\n * Default: `auto`.\n */\n quality?: 'low' | 'medium' | 'high' | 'auto';\n\n /**\n * The size of the generated image. One of `1024x1024`, `1024x1536`, `1536x1024`,\n * or `auto`. Default: `auto`.\n */\n size?: '1024x1024' | '1024x1536' | '1536x1024' | 'auto';\n }\n\n export namespace ImageGeneration {\n /**\n * Optional mask for inpainting. Contains `image_url` (string, optional) and\n * `file_id` (string, optional).\n */\n export interface InputImageMask {\n /**\n * File ID for the mask image.\n */\n file_id?: string;\n\n /**\n * Base64-encoded mask image.\n */\n image_url?: string;\n }\n }\n\n /**\n * A tool that allows the model to execute shell commands in a local environment.\n */\n export interface LocalShell {\n /**\n * The type of the local shell tool. Always `local_shell`.\n */\n type: 'local_shell';\n }\n}\n\n/**\n * Use this option to force the model to call a specific function.\n */\nexport interface ToolChoiceFunction {\n /**\n * The name of the function to call.\n */\n name: string;\n\n /**\n * For function calling, the type is always `function`.\n */\n type: 'function';\n}\n\n/**\n * Controls which (if any) tool is called by the model.\n *\n * `none` means the model will not call any tool and instead generates a message.\n *\n * `auto` means the model can pick between generating a message or calling one or\n * more tools.\n *\n * `required` means the model must call one or more tools.\n */\nexport type ToolChoiceOptions = 'none' | 'auto' | 'required';\n\n/**\n * Indicates that the model should use a built-in tool to generate a response.\n * [Learn more about built-in tools](https://platform.openai.com/docs/guides/tools).\n */\nexport interface ToolChoiceTypes {\n /**\n * The type of hosted tool the model should to use. Learn more about\n * [built-in tools](https://platform.openai.com/docs/guides/tools).\n *\n * Allowed values are:\n *\n * - `file_search`\n * - `web_search_preview`\n * - `computer_use_preview`\n * - `code_interpreter`\n * - `mcp`\n * - `image_generation`\n */\n type:\n | 'file_search'\n | 'web_search_preview'\n | 'computer_use_preview'\n | 'web_search_preview_2025_03_11'\n | 'image_generation'\n | 'code_interpreter'\n | 'mcp';\n}\n\n/**\n * This tool searches the web for relevant results to use in a response. Learn more\n * about the\n * [web search tool](https://platform.openai.com/docs/guides/tools-web-search).\n */\nexport interface WebSearchTool {\n /**\n * The type of the web search tool. One of `web_search_preview` or\n * `web_search_preview_2025_03_11`.\n */\n type: 'web_search_preview' | 'web_search_preview_2025_03_11';\n\n /**\n * High level guidance for the amount of context window space to use for the\n * search. One of `low`, `medium`, or `high`. `medium` is the default.\n */\n search_context_size?: 'low' | 'medium' | 'high';\n\n /**\n * The user's location.\n */\n user_location?: WebSearchTool.UserLocation | null;\n}\n\nexport namespace WebSearchTool {\n /**\n * The user's location.\n */\n export interface UserLocation {\n /**\n * The type of location approximation. Always `approximate`.\n */\n type: 'approximate';\n\n /**\n * Free text input for the city of the user, e.g. `San Francisco`.\n */\n city?: string | null;\n\n /**\n * The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of\n * the user, e.g. `US`.\n */\n country?: string | null;\n\n /**\n * Free text input for the region of the user, e.g. `California`.\n */\n region?: string | null;\n\n /**\n * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the\n * user, e.g. `America/Los_Angeles`.\n */\n timezone?: string | null;\n }\n}\n\nexport type ResponseCreateParams = ResponseCreateParamsNonStreaming | ResponseCreateParamsStreaming;\n\nexport interface ResponseCreateParamsBase {\n /**\n * Text, image, or file inputs to the model, used to generate a response.\n *\n * Learn more:\n *\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Image inputs](https://platform.openai.com/docs/guides/images)\n * - [File inputs](https://platform.openai.com/docs/guides/pdf-files)\n * - [Conversation state](https://platform.openai.com/docs/guides/conversation-state)\n * - [Function calling](https://platform.openai.com/docs/guides/function-calling)\n */\n input: string | ResponseInput;\n\n /**\n * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a\n * wide range of models with different capabilities, performance characteristics,\n * and price points. Refer to the\n * [model guide](https://platform.openai.com/docs/models) to browse and compare\n * available models.\n */\n model: Shared.ResponsesModel;\n\n /**\n * Whether to run the model response in the background.\n * [Learn more](https://platform.openai.com/docs/guides/background).\n */\n background?: boolean | null;\n\n /**\n * Specify additional output data to include in the model response. Currently\n * supported values are:\n *\n * - `file_search_call.results`: Include the search results of the file search tool\n * call.\n * - `message.input_image.image_url`: Include image urls from the input message.\n * - `computer_call_output.output.image_url`: Include image urls from the computer\n * call output.\n * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning\n * tokens in reasoning item outputs. This enables reasoning items to be used in\n * multi-turn conversations when using the Responses API statelessly (like when\n * the `store` parameter is set to `false`, or when an organization is enrolled\n * in the zero data retention program).\n */\n include?: Array<ResponseIncludable> | null;\n\n /**\n * Inserts a system (or developer) message as the first item in the model's\n * context.\n *\n * When using along with `previous_response_id`, the instructions from a previous\n * response will not be carried over to the next response. This makes it simple to\n * swap out system (or developer) messages in new responses.\n */\n instructions?: string | null;\n\n /**\n * An upper bound for the number of tokens that can be generated for a response,\n * including visible output tokens and\n * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n */\n max_output_tokens?: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * Whether to allow the model to run tool calls in parallel.\n */\n parallel_tool_calls?: boolean | null;\n\n /**\n * The unique ID of the previous response to the model. Use this to create\n * multi-turn conversations. Learn more about\n * [conversation state](https://platform.openai.com/docs/guides/conversation-state).\n */\n previous_response_id?: string | null;\n\n /**\n * **o-series models only**\n *\n * Configuration options for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning).\n */\n reasoning?: Shared.Reasoning | null;\n\n /**\n * Specifies the latency tier to use for processing the request. This parameter is\n * relevant for customers subscribed to the scale tier service:\n *\n * - If set to 'auto', and the Project is Scale tier enabled, the system will\n * utilize scale tier credits until they are exhausted.\n * - If set to 'auto', and the Project is not Scale tier enabled, the request will\n * be processed using the default service tier with a lower uptime SLA and no\n * latency guarentee.\n * - If set to 'default', the request will be processed using the default service\n * tier with a lower uptime SLA and no latency guarentee.\n * - If set to 'flex', the request will be processed with the Flex Processing\n * service tier.\n * [Learn more](https://platform.openai.com/docs/guides/flex-processing).\n * - When not set, the default behavior is 'auto'.\n *\n * When this parameter is set, the response body will include the `service_tier`\n * utilized.\n */\n service_tier?: 'auto' | 'default' | 'flex' | null;\n\n /**\n * Whether to store the generated model response for later retrieval via API.\n */\n store?: boolean | null;\n\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\n * for more information.\n */\n stream?: boolean | null;\n\n /**\n * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will\n * make the output more random, while lower values like 0.2 will make it more\n * focused and deterministic. We generally recommend altering this or `top_p` but\n * not both.\n */\n temperature?: number | null;\n\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data. Learn more:\n *\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n */\n text?: ResponseTextConfig;\n\n /**\n * How the model should select which tool (or tools) to use when generating a\n * response. See the `tools` parameter to see how to specify which tools the model\n * can call.\n */\n tool_choice?: ToolChoiceOptions | ToolChoiceTypes | ToolChoiceFunction;\n\n /**\n * An array of tools the model may call while generating a response. You can\n * specify which tool to use by setting the `tool_choice` parameter.\n *\n * The two categories of tools you can provide the model are:\n *\n * - **Built-in tools**: Tools that are provided by OpenAI that extend the model's\n * capabilities, like\n * [web search](https://platform.openai.com/docs/guides/tools-web-search) or\n * [file search](https://platform.openai.com/docs/guides/tools-file-search).\n * Learn more about\n * [built-in tools](https://platform.openai.com/docs/guides/tools).\n * - **Function calls (custom tools)**: Functions that are defined by you, enabling\n * the model to call your own code. Learn more about\n * [function calling](https://platform.openai.com/docs/guides/function-calling).\n */\n tools?: Array<Tool>;\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the\n * model considers the results of the tokens with top_p probability mass. So 0.1\n * means only the tokens comprising the top 10% probability mass are considered.\n *\n * We generally recommend altering this or `temperature` but not both.\n */\n top_p?: number | null;\n\n /**\n * The truncation strategy to use for the model response.\n *\n * - `auto`: If the context of this response and previous ones exceeds the model's\n * context window size, the model will truncate the response to fit the context\n * window by dropping input items in the middle of the conversation.\n * - `disabled` (default): If a model response will exceed the context window size\n * for a model, the request will fail with a 400 error.\n */\n truncation?: 'auto' | 'disabled' | null;\n\n /**\n * A stable identifier for your end-users. Used to boost cache hit rates by better\n * bucketing similar requests and to help OpenAI detect and prevent abuse.\n * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n */\n user?: string;\n}\n\nexport namespace ResponseCreateParams {\n export type ResponseCreateParamsNonStreaming = ResponsesAPI.ResponseCreateParamsNonStreaming;\n export type ResponseCreateParamsStreaming = ResponsesAPI.ResponseCreateParamsStreaming;\n}\n\nexport interface ResponseCreateParamsNonStreaming extends ResponseCreateParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\n * for more information.\n */\n stream?: false | null;\n}\n\nexport interface ResponseCreateParamsStreaming extends ResponseCreateParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\n * for more information.\n */\n stream: true;\n}\n\nexport type ResponseRetrieveParams = ResponseRetrieveParamsNonStreaming | ResponseRetrieveParamsStreaming;\n\nexport interface ResponseRetrieveParamsBase {\n /**\n * Additional fields to include in the response. See the `include` parameter for\n * Response creation above for more information.\n */\n include?: Array<ResponseIncludable>;\n\n /**\n * The sequence number of the event after which to start streaming.\n */\n starting_after?: number;\n\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\n * for more information.\n */\n stream?: boolean;\n}\n\nexport namespace ResponseRetrieveParams {\n export type ResponseRetrieveParamsNonStreaming = ResponsesAPI.ResponseRetrieveParamsNonStreaming;\n export type ResponseRetrieveParamsStreaming = ResponsesAPI.ResponseRetrieveParamsStreaming;\n}\n\nexport interface ResponseRetrieveParamsNonStreaming extends ResponseRetrieveParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\n * for more information.\n */\n stream?: false;\n}\n\nexport interface ResponseRetrieveParamsStreaming extends ResponseRetrieveParamsBase {\n /**\n * If set to true, the model response data will be streamed to the client as it is\n * generated using\n * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n * See the\n * [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\n * for more information.\n */\n stream: true;\n}\n\nResponses.InputItems = InputItems;\n\nexport declare namespace Responses {\n export {\n type ComputerTool as ComputerTool,\n type EasyInputMessage as EasyInputMessage,\n type FileSearchTool as FileSearchTool,\n type FunctionTool as FunctionTool,\n type Response as Response,\n type ResponseAudioDeltaEvent as ResponseAudioDeltaEvent,\n type ResponseAudioDoneEvent as ResponseAudioDoneEvent,\n type ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent,\n type ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent,\n type ResponseCodeInterpreterCallCodeDeltaEvent as ResponseCodeInterpreterCallCodeDeltaEvent,\n type ResponseCodeInterpreterCallCodeDoneEvent as ResponseCodeInterpreterCallCodeDoneEvent,\n type ResponseCodeInterpreterCallCompletedEvent as ResponseCodeInterpreterCallCompletedEvent,\n type ResponseCodeInterpreterCallInProgressEvent as ResponseCodeInterpreterCallInProgressEvent,\n type ResponseCodeInterpreterCallInterpretingEvent as ResponseCodeInterpreterCallInterpretingEvent,\n type ResponseCodeInterpreterToolCall as ResponseCodeInterpreterToolCall,\n type ResponseCompletedEvent as ResponseCompletedEvent,\n type ResponseComputerToolCall as ResponseComputerToolCall,\n type ResponseComputerToolCallOutputItem as ResponseComputerToolCallOutputItem,\n type ResponseComputerToolCallOutputScreenshot as ResponseComputerToolCallOutputScreenshot,\n type ResponseContent as ResponseContent,\n type ResponseContentPartAddedEvent as ResponseContentPartAddedEvent,\n type ResponseContentPartDoneEvent as ResponseContentPartDoneEvent,\n type ResponseCreatedEvent as ResponseCreatedEvent,\n type ResponseError as ResponseError,\n type ResponseErrorEvent as ResponseErrorEvent,\n type ResponseFailedEvent as ResponseFailedEvent,\n type ResponseFileSearchCallCompletedEvent as ResponseFileSearchCallCompletedEvent,\n type ResponseFileSearchCallInProgressEvent as ResponseFileSearchCallInProgressEvent,\n type ResponseFileSearchCallSearchingEvent as ResponseFileSearchCallSearchingEvent,\n type ResponseFileSearchToolCall as ResponseFileSearchToolCall,\n type ResponseFormatTextConfig as ResponseFormatTextConfig,\n type ResponseFormatTextJSONSchemaConfig as ResponseFormatTextJSONSchemaConfig,\n type ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent,\n type ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent,\n type ResponseFunctionToolCall as ResponseFunctionToolCall,\n type ResponseFunctionToolCallItem as ResponseFunctionToolCallItem,\n type ResponseFunctionToolCallOutputItem as ResponseFunctionToolCallOutputItem,\n type ResponseFunctionWebSearch as ResponseFunctionWebSearch,\n type ResponseImageGenCallCompletedEvent as ResponseImageGenCallCompletedEvent,\n type ResponseImageGenCallGeneratingEvent as ResponseImageGenCallGeneratingEvent,\n type ResponseImageGenCallInProgressEvent as ResponseImageGenCallInProgressEvent,\n type ResponseImageGenCallPartialImageEvent as ResponseImageGenCallPartialImageEvent,\n type ResponseInProgressEvent as ResponseInProgressEvent,\n type ResponseIncludable as ResponseIncludable,\n type ResponseIncompleteEvent as ResponseIncompleteEvent,\n type ResponseInput as ResponseInput,\n type ResponseInputAudio as ResponseInputAudio,\n type ResponseInputContent as ResponseInputContent,\n type ResponseInputFile as ResponseInputFile,\n type ResponseInputImage as ResponseInputImage,\n type ResponseInputItem as ResponseInputItem,\n type ResponseInputMessageContentList as ResponseInputMessageContentList,\n type ResponseInputMessageItem as ResponseInputMessageItem,\n type ResponseInputText as ResponseInputText,\n type ResponseItem as ResponseItem,\n type ResponseMcpCallArgumentsDeltaEvent as ResponseMcpCallArgumentsDeltaEvent,\n type ResponseMcpCallArgumentsDoneEvent as ResponseMcpCallArgumentsDoneEvent,\n type ResponseMcpCallCompletedEvent as ResponseMcpCallCompletedEvent,\n type ResponseMcpCallFailedEvent as ResponseMcpCallFailedEvent,\n type ResponseMcpCallInProgressEvent as ResponseMcpCallInProgressEvent,\n type ResponseMcpListToolsCompletedEvent as ResponseMcpListToolsCompletedEvent,\n type ResponseMcpListToolsFailedEvent as ResponseMcpListToolsFailedEvent,\n type ResponseMcpListToolsInProgressEvent as ResponseMcpListToolsInProgressEvent,\n type ResponseOutputAudio as ResponseOutputAudio,\n type ResponseOutputItem as ResponseOutputItem,\n type ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent,\n type ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent,\n type ResponseOutputMessage as ResponseOutputMessage,\n type ResponseOutputRefusal as ResponseOutputRefusal,\n type ResponseOutputText as ResponseOutputText,\n type ResponseOutputTextAnnotationAddedEvent as ResponseOutputTextAnnotationAddedEvent,\n type ResponseQueuedEvent as ResponseQueuedEvent,\n type ResponseReasoningDeltaEvent as ResponseReasoningDeltaEvent,\n type ResponseReasoningDoneEvent as ResponseReasoningDoneEvent,\n type ResponseReasoningItem as ResponseReasoningItem,\n type ResponseReasoningSummaryDeltaEvent as ResponseReasoningSummaryDeltaEvent,\n type ResponseReasoningSummaryDoneEvent as ResponseReasoningSummaryDoneEvent,\n type ResponseReasoningSummaryPartAddedEvent as ResponseReasoningSummaryPartAddedEvent,\n type ResponseReasoningSummaryPartDoneEvent as ResponseReasoningSummaryPartDoneEvent,\n type ResponseReasoningSummaryTextDeltaEvent as ResponseReasoningSummaryTextDeltaEvent,\n type ResponseReasoningSummaryTextDoneEvent as ResponseReasoningSummaryTextDoneEvent,\n type ResponseRefusalDeltaEvent as ResponseRefusalDeltaEvent,\n type ResponseRefusalDoneEvent as ResponseRefusalDoneEvent,\n type ResponseStatus as ResponseStatus,\n type ResponseStreamEvent as ResponseStreamEvent,\n type ResponseTextConfig as ResponseTextConfig,\n type ResponseTextDeltaEvent as ResponseTextDeltaEvent,\n type ResponseTextDoneEvent as ResponseTextDoneEvent,\n type ResponseUsage as ResponseUsage,\n type ResponseWebSearchCallCompletedEvent as ResponseWebSearchCallCompletedEvent,\n type ResponseWebSearchCallInProgressEvent as ResponseWebSearchCallInProgressEvent,\n type ResponseWebSearchCallSearchingEvent as ResponseWebSearchCallSearchingEvent,\n type Tool as Tool,\n type ToolChoiceFunction as ToolChoiceFunction,\n type ToolChoiceOptions as ToolChoiceOptions,\n type ToolChoiceTypes as ToolChoiceTypes,\n type WebSearchTool as WebSearchTool,\n type ResponseCreateParams as ResponseCreateParams,\n type ResponseCreateParamsNonStreaming as ResponseCreateParamsNonStreaming,\n type ResponseCreateParamsStreaming as ResponseCreateParamsStreaming,\n type ResponseRetrieveParams as ResponseRetrieveParams,\n type ResponseRetrieveParamsNonStreaming as ResponseRetrieveParamsNonStreaming,\n type ResponseRetrieveParamsStreaming as ResponseRetrieveParamsStreaming,\n };\n\n export {\n InputItems as InputItems,\n type ResponseItemList as ResponseItemList,\n type InputItemListParams as InputItemListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as Core from '../../core';\n\nexport class Parts extends APIResource {\n /**\n * Adds a\n * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.\n * A Part represents a chunk of bytes from the file you are trying to upload.\n *\n * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload\n * maximum of 8 GB.\n *\n * It is possible to add multiple Parts in parallel. You can decide the intended\n * order of the Parts when you\n * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).\n */\n create(\n uploadId: string,\n body: PartCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<UploadPart> {\n return this._client.post(\n `/uploads/${uploadId}/parts`,\n Core.multipartFormRequestOptions({ body, ...options }),\n );\n }\n}\n\n/**\n * The upload Part represents a chunk of bytes we can add to an Upload object.\n */\nexport interface UploadPart {\n /**\n * The upload Part unique identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the Part was created.\n */\n created_at: number;\n\n /**\n * The object type, which is always `upload.part`.\n */\n object: 'upload.part';\n\n /**\n * The ID of the Upload object that this Part was added to.\n */\n upload_id: string;\n}\n\nexport interface PartCreateParams {\n /**\n * The chunk of bytes for this Part.\n */\n data: Core.Uploadable;\n}\n\nexport declare namespace Parts {\n export { type UploadPart as UploadPart, type PartCreateParams as PartCreateParams };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport * as Core from '../../core';\nimport * as FilesAPI from '../files';\nimport * as PartsAPI from './parts';\nimport { PartCreateParams, Parts, UploadPart } from './parts';\n\nexport class Uploads extends APIResource {\n parts: PartsAPI.Parts = new PartsAPI.Parts(this._client);\n\n /**\n * Creates an intermediate\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object\n * that you can add\n * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.\n * Currently, an Upload can accept at most 8 GB in total and expires after an hour\n * after you create it.\n *\n * Once you complete the Upload, we will create a\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * contains all the parts you uploaded. This File is usable in the rest of our\n * platform as a regular File object.\n *\n * For certain `purpose` values, the correct `mime_type` must be specified. Please\n * refer to documentation for the\n * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).\n *\n * For guidance on the proper filename extensions for each purpose, please follow\n * the documentation on\n * [creating a File](https://platform.openai.com/docs/api-reference/files/create).\n */\n create(body: UploadCreateParams, options?: Core.RequestOptions): Core.APIPromise<Upload> {\n return this._client.post('/uploads', { body, ...options });\n }\n\n /**\n * Cancels the Upload. No Parts may be added after an Upload is cancelled.\n */\n cancel(uploadId: string, options?: Core.RequestOptions): Core.APIPromise<Upload> {\n return this._client.post(`/uploads/${uploadId}/cancel`, options);\n }\n\n /**\n * Completes the\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).\n *\n * Within the returned Upload object, there is a nested\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * is ready to use in the rest of the platform.\n *\n * You can specify the order of the Parts by passing in an ordered list of the Part\n * IDs.\n *\n * The number of bytes uploaded upon completion must match the number of bytes\n * initially specified when creating the Upload object. No Parts may be added after\n * an Upload is completed.\n */\n complete(\n uploadId: string,\n body: UploadCompleteParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<Upload> {\n return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });\n }\n}\n\n/**\n * The Upload object can accept byte chunks in the form of Parts.\n */\nexport interface Upload {\n /**\n * The Upload unique identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The intended number of bytes to be uploaded.\n */\n bytes: number;\n\n /**\n * The Unix timestamp (in seconds) for when the Upload was created.\n */\n created_at: number;\n\n /**\n * The Unix timestamp (in seconds) for when the Upload will expire.\n */\n expires_at: number;\n\n /**\n * The name of the file to be uploaded.\n */\n filename: string;\n\n /**\n * The object type, which is always \"upload\".\n */\n object: 'upload';\n\n /**\n * The intended purpose of the file.\n * [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose)\n * for acceptable values.\n */\n purpose: string;\n\n /**\n * The status of the Upload.\n */\n status: 'pending' | 'completed' | 'cancelled' | 'expired';\n\n /**\n * The `File` object represents a document that has been uploaded to OpenAI.\n */\n file?: FilesAPI.FileObject | null;\n}\n\nexport interface UploadCreateParams {\n /**\n * The number of bytes in the file you are uploading.\n */\n bytes: number;\n\n /**\n * The name of the file to upload.\n */\n filename: string;\n\n /**\n * The MIME type of the file.\n *\n * This must fall within the supported MIME types for your file purpose. See the\n * supported MIME types for assistants and vision.\n */\n mime_type: string;\n\n /**\n * The intended purpose of the uploaded file.\n *\n * See the\n * [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose).\n */\n purpose: FilesAPI.FilePurpose;\n}\n\nexport interface UploadCompleteParams {\n /**\n * The ordered list of Part IDs.\n */\n part_ids: Array<string>;\n\n /**\n * The optional md5 checksum for the file contents to verify if the bytes uploaded\n * matches what you expect.\n */\n md5?: string;\n}\n\nUploads.Parts = Parts;\n\nexport declare namespace Uploads {\n export {\n type Upload as Upload,\n type UploadCreateParams as UploadCreateParams,\n type UploadCompleteParams as UploadCompleteParams,\n };\n\n export { Parts as Parts, type UploadPart as UploadPart, type PartCreateParams as PartCreateParams };\n}\n","/**\n * Like `Promise.allSettled()` but throws an error if any promises are rejected.\n */\nexport const allSettledWithThrow = async <R>(promises: Promise<R>[]): Promise<R[]> => {\n const results = await Promise.allSettled(promises);\n const rejected = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');\n if (rejected.length) {\n for (const result of rejected) {\n console.error(result.reason);\n }\n\n throw new Error(`${rejected.length} promise(s) failed - see the above errors`);\n }\n\n // Note: TS was complaining about using `.filter().map()` here for some reason\n const values: R[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n values.push(result.value);\n }\n }\n return values;\n};\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { sleep, Uploadable, isRequestOptions } from '../../core';\nimport * as Core from '../../core';\nimport * as VectorStoresAPI from './vector-stores';\nimport { CursorPage, type CursorPageParams, Page } from '../../pagination';\n\nexport class Files extends APIResource {\n /**\n * Create a vector store file by attaching a\n * [File](https://platform.openai.com/docs/api-reference/files) to a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).\n */\n create(\n vectorStoreId: string,\n body: FileCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFile> {\n return this._client.post(`/vector_stores/${vectorStoreId}/files`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Retrieves a vector store file.\n */\n retrieve(\n vectorStoreId: string,\n fileId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFile> {\n return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Update attributes on a vector store file.\n */\n update(\n vectorStoreId: string,\n fileId: string,\n body: FileUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFile> {\n return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Returns a list of vector store files.\n */\n list(\n vectorStoreId: string,\n query?: FileListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreFilesPage, VectorStoreFile>;\n list(\n vectorStoreId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreFilesPage, VectorStoreFile>;\n list(\n vectorStoreId: string,\n query: FileListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreFilesPage, VectorStoreFile> {\n if (isRequestOptions(query)) {\n return this.list(vectorStoreId, {}, query);\n }\n return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Delete a vector store file. This will remove the file from the vector store but\n * the file itself will not be deleted. To delete the file, use the\n * [delete file](https://platform.openai.com/docs/api-reference/files/delete)\n * endpoint.\n */\n del(\n vectorStoreId: string,\n fileId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFileDeleted> {\n return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Attach a file to the given vector store and wait for it to be processed.\n */\n async createAndPoll(\n vectorStoreId: string,\n body: FileCreateParams,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<VectorStoreFile> {\n const file = await this.create(vectorStoreId, body, options);\n return await this.poll(vectorStoreId, file.id, options);\n }\n\n /**\n * Wait for the vector store file to finish processing.\n *\n * Note: this will return even if the file failed to process, you need to check\n * file.last_error and file.status to handle these cases\n */\n async poll(\n vectorStoreId: string,\n fileId: string,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<VectorStoreFile> {\n const headers: { [key: string]: string } = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const fileResponse = await this.retrieve(vectorStoreId, fileId, {\n ...options,\n headers,\n }).withResponse();\n\n const file = fileResponse.data;\n\n switch (file.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n } else {\n const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'completed':\n return file;\n }\n }\n }\n\n /**\n * Upload a file to the `files` API and then attach it to the given vector store.\n *\n * Note the file will be asynchronously processed (you can use the alternative\n * polling helper method to wait for processing to complete).\n */\n async upload(\n vectorStoreId: string,\n file: Uploadable,\n options?: Core.RequestOptions,\n ): Promise<VectorStoreFile> {\n const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);\n return this.create(vectorStoreId, { file_id: fileInfo.id }, options);\n }\n\n /**\n * Add a file to a vector store and poll until processing is complete.\n */\n async uploadAndPoll(\n vectorStoreId: string,\n file: Uploadable,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<VectorStoreFile> {\n const fileInfo = await this.upload(vectorStoreId, file, options);\n return await this.poll(vectorStoreId, fileInfo.id, options);\n }\n\n /**\n * Retrieve the parsed contents of a vector store file.\n */\n content(\n vectorStoreId: string,\n fileId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<FileContentResponsesPage, FileContentResponse> {\n return this._client.getAPIList(\n `/vector_stores/${vectorStoreId}/files/${fileId}/content`,\n FileContentResponsesPage,\n { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } },\n );\n }\n}\n\nexport class VectorStoreFilesPage extends CursorPage<VectorStoreFile> {}\n\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class FileContentResponsesPage extends Page<FileContentResponse> {}\n\n/**\n * A list of files attached to a vector store.\n */\nexport interface VectorStoreFile {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the vector store file was created.\n */\n created_at: number;\n\n /**\n * The last error associated with this vector store file. Will be `null` if there\n * are no errors.\n */\n last_error: VectorStoreFile.LastError | null;\n\n /**\n * The object type, which is always `vector_store.file`.\n */\n object: 'vector_store.file';\n\n /**\n * The status of the vector store file, which can be either `in_progress`,\n * `completed`, `cancelled`, or `failed`. The status `completed` indicates that the\n * vector store file is ready for use.\n */\n status: 'in_progress' | 'completed' | 'cancelled' | 'failed';\n\n /**\n * The total vector store usage in bytes. Note that this may be different from the\n * original file size.\n */\n usage_bytes: number;\n\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * that the [File](https://platform.openai.com/docs/api-reference/files) is\n * attached to.\n */\n vector_store_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard. Keys are strings with a maximum\n * length of 64 characters. Values are strings with a maximum length of 512\n * characters, booleans, or numbers.\n */\n attributes?: Record<string, string | number | boolean> | null;\n\n /**\n * The strategy used to chunk the file.\n */\n chunking_strategy?: VectorStoresAPI.FileChunkingStrategy;\n}\n\nexport namespace VectorStoreFile {\n /**\n * The last error associated with this vector store file. Will be `null` if there\n * are no errors.\n */\n export interface LastError {\n /**\n * One of `server_error` or `rate_limit_exceeded`.\n */\n code: 'server_error' | 'unsupported_file' | 'invalid_file';\n\n /**\n * A human-readable description of the error.\n */\n message: string;\n }\n}\n\nexport interface VectorStoreFileDeleted {\n id: string;\n\n deleted: boolean;\n\n object: 'vector_store.file.deleted';\n}\n\nexport interface FileContentResponse {\n /**\n * The text content\n */\n text?: string;\n\n /**\n * The content type (currently only `\"text\"`)\n */\n type?: string;\n}\n\nexport interface FileCreateParams {\n /**\n * A [File](https://platform.openai.com/docs/api-reference/files) ID that the\n * vector store should use. Useful for tools like `file_search` that can access\n * files.\n */\n file_id: string;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard. Keys are strings with a maximum\n * length of 64 characters. Values are strings with a maximum length of 512\n * characters, booleans, or numbers.\n */\n attributes?: Record<string, string | number | boolean> | null;\n\n /**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy. Only applicable if `file_ids` is non-empty.\n */\n chunking_strategy?: VectorStoresAPI.FileChunkingStrategyParam;\n}\n\nexport interface FileUpdateParams {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard. Keys are strings with a maximum\n * length of 64 characters. Values are strings with a maximum length of 512\n * characters, booleans, or numbers.\n */\n attributes: Record<string, string | number | boolean> | null;\n}\n\nexport interface FileListParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.\n */\n filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled';\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nFiles.VectorStoreFilesPage = VectorStoreFilesPage;\nFiles.FileContentResponsesPage = FileContentResponsesPage;\n\nexport declare namespace Files {\n export {\n type VectorStoreFile as VectorStoreFile,\n type VectorStoreFileDeleted as VectorStoreFileDeleted,\n type FileContentResponse as FileContentResponse,\n VectorStoreFilesPage as VectorStoreFilesPage,\n FileContentResponsesPage as FileContentResponsesPage,\n type FileCreateParams as FileCreateParams,\n type FileUpdateParams as FileUpdateParams,\n type FileListParams as FileListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { isRequestOptions } from '../../core';\nimport { sleep } from '../../core';\nimport { Uploadable } from '../../core';\nimport { allSettledWithThrow } from '../../lib/Util';\nimport * as Core from '../../core';\nimport * as FilesAPI from './files';\nimport { VectorStoreFilesPage } from './files';\nimport * as VectorStoresAPI from './vector-stores';\nimport { type CursorPageParams } from '../../pagination';\n\nexport class FileBatches extends APIResource {\n /**\n * Create a vector store file batch.\n */\n create(\n vectorStoreId: string,\n body: FileBatchCreateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFileBatch> {\n return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Retrieves a vector store file batch.\n */\n retrieve(\n vectorStoreId: string,\n batchId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFileBatch> {\n return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Cancel a vector store file batch. This attempts to cancel the processing of\n * files in this batch as soon as possible.\n */\n cancel(\n vectorStoreId: string,\n batchId: string,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStoreFileBatch> {\n return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Create a vector store batch and poll until all files have been processed.\n */\n async createAndPoll(\n vectorStoreId: string,\n body: FileBatchCreateParams,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<VectorStoreFileBatch> {\n const batch = await this.create(vectorStoreId, body);\n return await this.poll(vectorStoreId, batch.id, options);\n }\n\n /**\n * Returns a list of vector store files in a batch.\n */\n listFiles(\n vectorStoreId: string,\n batchId: string,\n query?: FileBatchListFilesParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreFilesPage, FilesAPI.VectorStoreFile>;\n listFiles(\n vectorStoreId: string,\n batchId: string,\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreFilesPage, FilesAPI.VectorStoreFile>;\n listFiles(\n vectorStoreId: string,\n batchId: string,\n query: FileBatchListFilesParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreFilesPage, FilesAPI.VectorStoreFile> {\n if (isRequestOptions(query)) {\n return this.listFiles(vectorStoreId, batchId, {}, query);\n }\n return this._client.getAPIList(\n `/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`,\n VectorStoreFilesPage,\n { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } },\n );\n }\n\n /**\n * Wait for the given file batch to be processed.\n *\n * Note: this will return even if one of the files failed to process, you need to\n * check batch.file_counts.failed_count to handle this case.\n */\n async poll(\n vectorStoreId: string,\n batchId: string,\n options?: Core.RequestOptions & { pollIntervalMs?: number },\n ): Promise<VectorStoreFileBatch> {\n const headers: { [key: string]: string } = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n\n while (true) {\n const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {\n ...options,\n headers,\n }).withResponse();\n\n switch (batch.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n } else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'cancelled':\n case 'completed':\n return batch;\n }\n }\n }\n\n /**\n * Uploads the given files concurrently and then creates a vector store file batch.\n *\n * The concurrency limit is configurable using the `maxConcurrency` parameter.\n */\n async uploadAndPoll(\n vectorStoreId: string,\n { files, fileIds = [] }: { files: Uploadable[]; fileIds?: string[] },\n options?: Core.RequestOptions & { pollIntervalMs?: number; maxConcurrency?: number },\n ): Promise<VectorStoreFileBatch> {\n if (files == null || files.length == 0) {\n throw new Error(\n `No \\`files\\` provided to process. If you've already uploaded files you should use \\`.createAndPoll()\\` instead`,\n );\n }\n\n const configuredConcurrency = options?.maxConcurrency ?? 5;\n\n // We cap the number of workers at the number of files (so we don't start any unnecessary workers)\n const concurrencyLimit = Math.min(configuredConcurrency, files.length);\n\n const client = this._client;\n const fileIterator = files.values();\n const allFileIds: string[] = [...fileIds];\n\n // This code is based on this design. The libraries don't accommodate our environment limits.\n // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all\n async function processFiles(iterator: IterableIterator<Uploadable>) {\n for (let item of iterator) {\n const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);\n allFileIds.push(fileObj.id);\n }\n }\n\n // Start workers to process results\n const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);\n\n // Wait for all processing to complete.\n await allSettledWithThrow(workers);\n\n return await this.createAndPoll(vectorStoreId, {\n file_ids: allFileIds,\n });\n }\n}\n\n/**\n * A batch of files attached to a vector store.\n */\nexport interface VectorStoreFileBatch {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the vector store files batch was\n * created.\n */\n created_at: number;\n\n file_counts: VectorStoreFileBatch.FileCounts;\n\n /**\n * The object type, which is always `vector_store.file_batch`.\n */\n object: 'vector_store.files_batch';\n\n /**\n * The status of the vector store files batch, which can be either `in_progress`,\n * `completed`, `cancelled` or `failed`.\n */\n status: 'in_progress' | 'completed' | 'cancelled' | 'failed';\n\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * that the [File](https://platform.openai.com/docs/api-reference/files) is\n * attached to.\n */\n vector_store_id: string;\n}\n\nexport namespace VectorStoreFileBatch {\n export interface FileCounts {\n /**\n * The number of files that where cancelled.\n */\n cancelled: number;\n\n /**\n * The number of files that have been processed.\n */\n completed: number;\n\n /**\n * The number of files that have failed to process.\n */\n failed: number;\n\n /**\n * The number of files that are currently being processed.\n */\n in_progress: number;\n\n /**\n * The total number of files.\n */\n total: number;\n }\n}\n\nexport interface FileBatchCreateParams {\n /**\n * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that\n * the vector store should use. Useful for tools like `file_search` that can access\n * files.\n */\n file_ids: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard. Keys are strings with a maximum\n * length of 64 characters. Values are strings with a maximum length of 512\n * characters, booleans, or numbers.\n */\n attributes?: Record<string, string | number | boolean> | null;\n\n /**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy. Only applicable if `file_ids` is non-empty.\n */\n chunking_strategy?: VectorStoresAPI.FileChunkingStrategyParam;\n}\n\nexport interface FileBatchListFilesParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.\n */\n filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled';\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nexport declare namespace FileBatches {\n export {\n type VectorStoreFileBatch as VectorStoreFileBatch,\n type FileBatchCreateParams as FileBatchCreateParams,\n type FileBatchListFilesParams as FileBatchListFilesParams,\n };\n}\n\nexport { VectorStoreFilesPage };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../resource';\nimport { isRequestOptions } from '../../core';\nimport * as Core from '../../core';\nimport * as Shared from '../shared';\nimport * as FileBatchesAPI from './file-batches';\nimport {\n FileBatchCreateParams,\n FileBatchListFilesParams,\n FileBatches,\n VectorStoreFileBatch,\n} from './file-batches';\nimport * as FilesAPI from './files';\nimport {\n FileContentResponse,\n FileContentResponsesPage,\n FileCreateParams,\n FileListParams,\n FileUpdateParams,\n Files,\n VectorStoreFile,\n VectorStoreFileDeleted,\n VectorStoreFilesPage,\n} from './files';\nimport { CursorPage, type CursorPageParams, Page } from '../../pagination';\n\nexport class VectorStores extends APIResource {\n files: FilesAPI.Files = new FilesAPI.Files(this._client);\n fileBatches: FileBatchesAPI.FileBatches = new FileBatchesAPI.FileBatches(this._client);\n\n /**\n * Create a vector store.\n */\n create(body: VectorStoreCreateParams, options?: Core.RequestOptions): Core.APIPromise<VectorStore> {\n return this._client.post('/vector_stores', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Retrieves a vector store.\n */\n retrieve(vectorStoreId: string, options?: Core.RequestOptions): Core.APIPromise<VectorStore> {\n return this._client.get(`/vector_stores/${vectorStoreId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Modifies a vector store.\n */\n update(\n vectorStoreId: string,\n body: VectorStoreUpdateParams,\n options?: Core.RequestOptions,\n ): Core.APIPromise<VectorStore> {\n return this._client.post(`/vector_stores/${vectorStoreId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Returns a list of vector stores.\n */\n list(\n query?: VectorStoreListParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoresPage, VectorStore>;\n list(options?: Core.RequestOptions): Core.PagePromise<VectorStoresPage, VectorStore>;\n list(\n query: VectorStoreListParams | Core.RequestOptions = {},\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoresPage, VectorStore> {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/vector_stores', VectorStoresPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Delete a vector store.\n */\n del(vectorStoreId: string, options?: Core.RequestOptions): Core.APIPromise<VectorStoreDeleted> {\n return this._client.delete(`/vector_stores/${vectorStoreId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n\n /**\n * Search a vector store for relevant chunks based on a query and file attributes\n * filter.\n */\n search(\n vectorStoreId: string,\n body: VectorStoreSearchParams,\n options?: Core.RequestOptions,\n ): Core.PagePromise<VectorStoreSearchResponsesPage, VectorStoreSearchResponse> {\n return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`, VectorStoreSearchResponsesPage, {\n body,\n method: 'post',\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n\nexport class VectorStoresPage extends CursorPage<VectorStore> {}\n\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class VectorStoreSearchResponsesPage extends Page<VectorStoreSearchResponse> {}\n\n/**\n * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of\n * `800` and `chunk_overlap_tokens` of `400`.\n */\nexport interface AutoFileChunkingStrategyParam {\n /**\n * Always `auto`.\n */\n type: 'auto';\n}\n\n/**\n * The strategy used to chunk the file.\n */\nexport type FileChunkingStrategy = StaticFileChunkingStrategyObject | OtherFileChunkingStrategyObject;\n\n/**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy. Only applicable if `file_ids` is non-empty.\n */\nexport type FileChunkingStrategyParam = AutoFileChunkingStrategyParam | StaticFileChunkingStrategyObjectParam;\n\n/**\n * This is returned when the chunking strategy is unknown. Typically, this is\n * because the file was indexed before the `chunking_strategy` concept was\n * introduced in the API.\n */\nexport interface OtherFileChunkingStrategyObject {\n /**\n * Always `other`.\n */\n type: 'other';\n}\n\nexport interface StaticFileChunkingStrategy {\n /**\n * The number of tokens that overlap between chunks. The default value is `400`.\n *\n * Note that the overlap must not exceed half of `max_chunk_size_tokens`.\n */\n chunk_overlap_tokens: number;\n\n /**\n * The maximum number of tokens in each chunk. The default value is `800`. The\n * minimum value is `100` and the maximum value is `4096`.\n */\n max_chunk_size_tokens: number;\n}\n\nexport interface StaticFileChunkingStrategyObject {\n static: StaticFileChunkingStrategy;\n\n /**\n * Always `static`.\n */\n type: 'static';\n}\n\n/**\n * Customize your own chunking strategy by setting chunk size and chunk overlap.\n */\nexport interface StaticFileChunkingStrategyObjectParam {\n static: StaticFileChunkingStrategy;\n\n /**\n * Always `static`.\n */\n type: 'static';\n}\n\n/**\n * A vector store is a collection of processed files can be used by the\n * `file_search` tool.\n */\nexport interface VectorStore {\n /**\n * The identifier, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The Unix timestamp (in seconds) for when the vector store was created.\n */\n created_at: number;\n\n file_counts: VectorStore.FileCounts;\n\n /**\n * The Unix timestamp (in seconds) for when the vector store was last active.\n */\n last_active_at: number | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata: Shared.Metadata | null;\n\n /**\n * The name of the vector store.\n */\n name: string;\n\n /**\n * The object type, which is always `vector_store`.\n */\n object: 'vector_store';\n\n /**\n * The status of the vector store, which can be either `expired`, `in_progress`, or\n * `completed`. A status of `completed` indicates that the vector store is ready\n * for use.\n */\n status: 'expired' | 'in_progress' | 'completed';\n\n /**\n * The total number of bytes used by the files in the vector store.\n */\n usage_bytes: number;\n\n /**\n * The expiration policy for a vector store.\n */\n expires_after?: VectorStore.ExpiresAfter;\n\n /**\n * The Unix timestamp (in seconds) for when the vector store will expire.\n */\n expires_at?: number | null;\n}\n\nexport namespace VectorStore {\n export interface FileCounts {\n /**\n * The number of files that were cancelled.\n */\n cancelled: number;\n\n /**\n * The number of files that have been successfully processed.\n */\n completed: number;\n\n /**\n * The number of files that have failed to process.\n */\n failed: number;\n\n /**\n * The number of files that are currently being processed.\n */\n in_progress: number;\n\n /**\n * The total number of files.\n */\n total: number;\n }\n\n /**\n * The expiration policy for a vector store.\n */\n export interface ExpiresAfter {\n /**\n * Anchor timestamp after which the expiration policy applies. Supported anchors:\n * `last_active_at`.\n */\n anchor: 'last_active_at';\n\n /**\n * The number of days after the anchor time that the vector store will expire.\n */\n days: number;\n }\n}\n\nexport interface VectorStoreDeleted {\n id: string;\n\n deleted: boolean;\n\n object: 'vector_store.deleted';\n}\n\nexport interface VectorStoreSearchResponse {\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard. Keys are strings with a maximum\n * length of 64 characters. Values are strings with a maximum length of 512\n * characters, booleans, or numbers.\n */\n attributes: Record<string, string | number | boolean> | null;\n\n /**\n * Content chunks from the file.\n */\n content: Array<VectorStoreSearchResponse.Content>;\n\n /**\n * The ID of the vector store file.\n */\n file_id: string;\n\n /**\n * The name of the vector store file.\n */\n filename: string;\n\n /**\n * The similarity score for the result.\n */\n score: number;\n}\n\nexport namespace VectorStoreSearchResponse {\n export interface Content {\n /**\n * The text content returned from search.\n */\n text: string;\n\n /**\n * The type of content.\n */\n type: 'text';\n }\n}\n\nexport interface VectorStoreCreateParams {\n /**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto`\n * strategy. Only applicable if `file_ids` is non-empty.\n */\n chunking_strategy?: FileChunkingStrategyParam;\n\n /**\n * The expiration policy for a vector store.\n */\n expires_after?: VectorStoreCreateParams.ExpiresAfter;\n\n /**\n * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that\n * the vector store should use. Useful for tools like `file_search` that can access\n * files.\n */\n file_ids?: Array<string>;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The name of the vector store.\n */\n name?: string;\n}\n\nexport namespace VectorStoreCreateParams {\n /**\n * The expiration policy for a vector store.\n */\n export interface ExpiresAfter {\n /**\n * Anchor timestamp after which the expiration policy applies. Supported anchors:\n * `last_active_at`.\n */\n anchor: 'last_active_at';\n\n /**\n * The number of days after the anchor time that the vector store will expire.\n */\n days: number;\n }\n}\n\nexport interface VectorStoreUpdateParams {\n /**\n * The expiration policy for a vector store.\n */\n expires_after?: VectorStoreUpdateParams.ExpiresAfter | null;\n\n /**\n * Set of 16 key-value pairs that can be attached to an object. This can be useful\n * for storing additional information about the object in a structured format, and\n * querying for objects via API or the dashboard.\n *\n * Keys are strings with a maximum length of 64 characters. Values are strings with\n * a maximum length of 512 characters.\n */\n metadata?: Shared.Metadata | null;\n\n /**\n * The name of the vector store.\n */\n name?: string | null;\n}\n\nexport namespace VectorStoreUpdateParams {\n /**\n * The expiration policy for a vector store.\n */\n export interface ExpiresAfter {\n /**\n * Anchor timestamp after which the expiration policy applies. Supported anchors:\n * `last_active_at`.\n */\n anchor: 'last_active_at';\n\n /**\n * The number of days after the anchor time that the vector store will expire.\n */\n days: number;\n }\n}\n\nexport interface VectorStoreListParams extends CursorPageParams {\n /**\n * A cursor for use in pagination. `before` is an object ID that defines your place\n * in the list. For instance, if you make a list request and receive 100 objects,\n * starting with obj_foo, your subsequent call can include before=obj_foo in order\n * to fetch the previous page of the list.\n */\n before?: string;\n\n /**\n * Sort order by the `created_at` timestamp of the objects. `asc` for ascending\n * order and `desc` for descending order.\n */\n order?: 'asc' | 'desc';\n}\n\nexport interface VectorStoreSearchParams {\n /**\n * A query string for a search\n */\n query: string | Array<string>;\n\n /**\n * A filter to apply based on file attributes.\n */\n filters?: Shared.ComparisonFilter | Shared.CompoundFilter;\n\n /**\n * The maximum number of results to return. This number should be between 1 and 50\n * inclusive.\n */\n max_num_results?: number;\n\n /**\n * Ranking options for search.\n */\n ranking_options?: VectorStoreSearchParams.RankingOptions;\n\n /**\n * Whether to rewrite the natural language query for vector search.\n */\n rewrite_query?: boolean;\n}\n\nexport namespace VectorStoreSearchParams {\n /**\n * Ranking options for search.\n */\n export interface RankingOptions {\n ranker?: 'auto' | 'default-2024-11-15';\n\n score_threshold?: number;\n }\n}\n\nVectorStores.VectorStoresPage = VectorStoresPage;\nVectorStores.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage;\nVectorStores.Files = Files;\nVectorStores.VectorStoreFilesPage = VectorStoreFilesPage;\nVectorStores.FileContentResponsesPage = FileContentResponsesPage;\nVectorStores.FileBatches = FileBatches;\n\nexport declare namespace VectorStores {\n export {\n type AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam,\n type FileChunkingStrategy as FileChunkingStrategy,\n type FileChunkingStrategyParam as FileChunkingStrategyParam,\n type OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject,\n type StaticFileChunkingStrategy as StaticFileChunkingStrategy,\n type StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject,\n type StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam,\n type VectorStore as VectorStore,\n type VectorStoreDeleted as VectorStoreDeleted,\n type VectorStoreSearchResponse as VectorStoreSearchResponse,\n VectorStoresPage as VectorStoresPage,\n VectorStoreSearchResponsesPage as VectorStoreSearchResponsesPage,\n type VectorStoreCreateParams as VectorStoreCreateParams,\n type VectorStoreUpdateParams as VectorStoreUpdateParams,\n type VectorStoreListParams as VectorStoreListParams,\n type VectorStoreSearchParams as VectorStoreSearchParams,\n };\n\n export {\n Files as Files,\n type VectorStoreFile as VectorStoreFile,\n type VectorStoreFileDeleted as VectorStoreFileDeleted,\n type FileContentResponse as FileContentResponse,\n VectorStoreFilesPage as VectorStoreFilesPage,\n FileContentResponsesPage as FileContentResponsesPage,\n type FileCreateParams as FileCreateParams,\n type FileUpdateParams as FileUpdateParams,\n type FileListParams as FileListParams,\n };\n\n export {\n FileBatches as FileBatches,\n type VectorStoreFileBatch as VectorStoreFileBatch,\n type FileBatchCreateParams as FileBatchCreateParams,\n type FileBatchListFilesParams as FileBatchListFilesParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { type Agent, type RequestInit } from './_shims/index';\nimport * as qs from './internal/qs';\nimport * as Core from './core';\nimport * as Errors from './error';\nimport * as Pagination from './pagination';\nimport { type CursorPageParams, CursorPageResponse, PageResponse } from './pagination';\nimport * as Uploads from './uploads';\nimport * as API from './resources/index';\nimport {\n Batch,\n BatchCreateParams,\n BatchError,\n BatchListParams,\n BatchRequestCounts,\n Batches,\n BatchesPage,\n} from './resources/batches';\nimport {\n Completion,\n CompletionChoice,\n CompletionCreateParams,\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n CompletionUsage,\n Completions,\n} from './resources/completions';\nimport {\n CreateEmbeddingResponse,\n Embedding,\n EmbeddingCreateParams,\n EmbeddingModel,\n Embeddings,\n} from './resources/embeddings';\nimport {\n FileContent,\n FileCreateParams,\n FileDeleted,\n FileListParams,\n FileObject,\n FileObjectsPage,\n FilePurpose,\n Files,\n} from './resources/files';\nimport {\n Image,\n ImageCreateVariationParams,\n ImageEditParams,\n ImageGenerateParams,\n ImageModel,\n Images,\n ImagesResponse,\n} from './resources/images';\nimport { Model, ModelDeleted, Models, ModelsPage } from './resources/models';\nimport {\n Moderation,\n ModerationCreateParams,\n ModerationCreateResponse,\n ModerationImageURLInput,\n ModerationModel,\n ModerationMultiModalInput,\n ModerationTextInput,\n Moderations,\n} from './resources/moderations';\nimport { Audio, AudioModel, AudioResponseFormat } from './resources/audio/audio';\nimport { Beta } from './resources/beta/beta';\nimport { Chat } from './resources/chat/chat';\nimport {\n ContainerCreateParams,\n ContainerCreateResponse,\n ContainerListParams,\n ContainerListResponse,\n ContainerListResponsesPage,\n ContainerRetrieveResponse,\n Containers,\n} from './resources/containers/containers';\nimport {\n EvalCreateParams,\n EvalCreateResponse,\n EvalCustomDataSourceConfig,\n EvalDeleteResponse,\n EvalListParams,\n EvalListResponse,\n EvalListResponsesPage,\n EvalRetrieveResponse,\n EvalStoredCompletionsDataSourceConfig,\n EvalUpdateParams,\n EvalUpdateResponse,\n Evals,\n} from './resources/evals/evals';\nimport { FineTuning } from './resources/fine-tuning/fine-tuning';\nimport { Graders } from './resources/graders/graders';\nimport { Responses } from './resources/responses/responses';\nimport {\n Upload,\n UploadCompleteParams,\n UploadCreateParams,\n Uploads as UploadsAPIUploads,\n} from './resources/uploads/uploads';\nimport {\n AutoFileChunkingStrategyParam,\n FileChunkingStrategy,\n FileChunkingStrategyParam,\n OtherFileChunkingStrategyObject,\n StaticFileChunkingStrategy,\n StaticFileChunkingStrategyObject,\n StaticFileChunkingStrategyObjectParam,\n VectorStore,\n VectorStoreCreateParams,\n VectorStoreDeleted,\n VectorStoreListParams,\n VectorStoreSearchParams,\n VectorStoreSearchResponse,\n VectorStoreSearchResponsesPage,\n VectorStoreUpdateParams,\n VectorStores,\n VectorStoresPage,\n} from './resources/vector-stores/vector-stores';\nimport {\n ChatCompletion,\n ChatCompletionAssistantMessageParam,\n ChatCompletionAudio,\n ChatCompletionAudioParam,\n ChatCompletionChunk,\n ChatCompletionContentPart,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPartRefusal,\n ChatCompletionContentPartText,\n ChatCompletionCreateParams,\n ChatCompletionCreateParamsNonStreaming,\n ChatCompletionCreateParamsStreaming,\n ChatCompletionDeleted,\n ChatCompletionDeveloperMessageParam,\n ChatCompletionFunctionCallOption,\n ChatCompletionFunctionMessageParam,\n ChatCompletionListParams,\n ChatCompletionMessage,\n ChatCompletionMessageParam,\n ChatCompletionMessageToolCall,\n ChatCompletionModality,\n ChatCompletionNamedToolChoice,\n ChatCompletionPredictionContent,\n ChatCompletionReasoningEffort,\n ChatCompletionRole,\n ChatCompletionStoreMessage,\n ChatCompletionStreamOptions,\n ChatCompletionSystemMessageParam,\n ChatCompletionTokenLogprob,\n ChatCompletionTool,\n ChatCompletionToolChoiceOption,\n ChatCompletionToolMessageParam,\n ChatCompletionUpdateParams,\n ChatCompletionUserMessageParam,\n ChatCompletionsPage,\n CreateChatCompletionRequestMessage,\n} from './resources/chat/completions/completions';\n\nexport interface ClientOptions {\n /**\n * Defaults to process.env['OPENAI_API_KEY'].\n */\n apiKey?: string | undefined;\n\n /**\n * Defaults to process.env['OPENAI_ORG_ID'].\n */\n organization?: string | null | undefined;\n\n /**\n * Defaults to process.env['OPENAI_PROJECT_ID'].\n */\n project?: string | null | undefined;\n\n /**\n * Override the default base URL for the API, e.g., \"https://api.example.com/v2/\"\n *\n * Defaults to process.env['OPENAI_BASE_URL'].\n */\n baseURL?: string | null | undefined;\n\n /**\n * The maximum amount of time (in milliseconds) that the client should wait for a response\n * from the server before timing out a single request.\n *\n * Note that request timeouts are retried by default, so in a worst-case scenario you may wait\n * much longer than this timeout before the promise succeeds or fails.\n */\n timeout?: number | undefined;\n\n /**\n * An HTTP agent used to manage HTTP(S) connections.\n *\n * If not provided, an agent will be constructed by default in the Node.js environment,\n * otherwise no agent is used.\n */\n httpAgent?: Agent | undefined;\n\n /**\n * Specify a custom `fetch` function implementation.\n *\n * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is\n * defined globally.\n */\n fetch?: Core.Fetch | undefined;\n\n /**\n * The maximum number of times that the client will retry a request in case of a\n * temporary failure, like a network error or a 5XX error from the server.\n *\n * @default 2\n */\n maxRetries?: number | undefined;\n\n /**\n * Default headers to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * header to `undefined` or `null` in request options.\n */\n defaultHeaders?: Core.Headers | undefined;\n\n /**\n * Default query parameters to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * param to `undefined` in request options.\n */\n defaultQuery?: Core.DefaultQuery | undefined;\n\n /**\n * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n * Only set this option to `true` if you understand the risks and have appropriate mitigations in place.\n */\n dangerouslyAllowBrowser?: boolean | undefined;\n}\n\n/**\n * API Client for interfacing with the OpenAI API.\n */\nexport class OpenAI extends Core.APIClient {\n apiKey: string;\n organization: string | null;\n project: string | null;\n\n private _options: ClientOptions;\n\n /**\n * API Client for interfacing with the OpenAI API.\n *\n * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({\n baseURL = Core.readEnv('OPENAI_BASE_URL'),\n apiKey = Core.readEnv('OPENAI_API_KEY'),\n organization = Core.readEnv('OPENAI_ORG_ID') ?? null,\n project = Core.readEnv('OPENAI_PROJECT_ID') ?? null,\n ...opts\n }: ClientOptions = {}) {\n if (apiKey === undefined) {\n throw new Errors.OpenAIError(\n \"The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).\",\n );\n }\n\n const options: ClientOptions = {\n apiKey,\n organization,\n project,\n ...opts,\n baseURL: baseURL || `https://api.openai.com/v1`,\n };\n\n if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {\n throw new Errors.OpenAIError(\n \"It looks like you're running in a browser-like environment.\\n\\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\\nIf you understand the risks and have appropriate mitigations in place,\\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\\n\\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\\n\\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\\n\",\n );\n }\n\n super({\n baseURL: options.baseURL!,\n timeout: options.timeout ?? 600000 /* 10 minutes */,\n httpAgent: options.httpAgent,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n });\n\n this._options = options;\n\n this.apiKey = apiKey;\n this.organization = organization;\n this.project = project;\n }\n\n completions: API.Completions = new API.Completions(this);\n chat: API.Chat = new API.Chat(this);\n embeddings: API.Embeddings = new API.Embeddings(this);\n files: API.Files = new API.Files(this);\n images: API.Images = new API.Images(this);\n audio: API.Audio = new API.Audio(this);\n moderations: API.Moderations = new API.Moderations(this);\n models: API.Models = new API.Models(this);\n fineTuning: API.FineTuning = new API.FineTuning(this);\n graders: API.Graders = new API.Graders(this);\n vectorStores: API.VectorStores = new API.VectorStores(this);\n beta: API.Beta = new API.Beta(this);\n batches: API.Batches = new API.Batches(this);\n uploads: API.Uploads = new API.Uploads(this);\n responses: API.Responses = new API.Responses(this);\n evals: API.Evals = new API.Evals(this);\n containers: API.Containers = new API.Containers(this);\n\n protected override defaultQuery(): Core.DefaultQuery | undefined {\n return this._options.defaultQuery;\n }\n\n protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n return {\n ...super.defaultHeaders(opts),\n 'OpenAI-Organization': this.organization,\n 'OpenAI-Project': this.project,\n ...this._options.defaultHeaders,\n };\n }\n\n protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n return { Authorization: `Bearer ${this.apiKey}` };\n }\n\n protected override stringifyQuery(query: Record<string, unknown>): string {\n return qs.stringify(query, { arrayFormat: 'brackets' });\n }\n\n static OpenAI = this;\n static DEFAULT_TIMEOUT = 600000; // 10 minutes\n\n static OpenAIError = Errors.OpenAIError;\n static APIError = Errors.APIError;\n static APIConnectionError = Errors.APIConnectionError;\n static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\n static APIUserAbortError = Errors.APIUserAbortError;\n static NotFoundError = Errors.NotFoundError;\n static ConflictError = Errors.ConflictError;\n static RateLimitError = Errors.RateLimitError;\n static BadRequestError = Errors.BadRequestError;\n static AuthenticationError = Errors.AuthenticationError;\n static InternalServerError = Errors.InternalServerError;\n static PermissionDeniedError = Errors.PermissionDeniedError;\n static UnprocessableEntityError = Errors.UnprocessableEntityError;\n\n static toFile = Uploads.toFile;\n static fileFromPath = Uploads.fileFromPath;\n}\n\nOpenAI.Completions = Completions;\nOpenAI.Chat = Chat;\nOpenAI.ChatCompletionsPage = ChatCompletionsPage;\nOpenAI.Embeddings = Embeddings;\nOpenAI.Files = Files;\nOpenAI.FileObjectsPage = FileObjectsPage;\nOpenAI.Images = Images;\nOpenAI.Audio = Audio;\nOpenAI.Moderations = Moderations;\nOpenAI.Models = Models;\nOpenAI.ModelsPage = ModelsPage;\nOpenAI.FineTuning = FineTuning;\nOpenAI.Graders = Graders;\nOpenAI.VectorStores = VectorStores;\nOpenAI.VectorStoresPage = VectorStoresPage;\nOpenAI.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage;\nOpenAI.Beta = Beta;\nOpenAI.Batches = Batches;\nOpenAI.BatchesPage = BatchesPage;\nOpenAI.Uploads = UploadsAPIUploads;\nOpenAI.Responses = Responses;\nOpenAI.Evals = Evals;\nOpenAI.EvalListResponsesPage = EvalListResponsesPage;\nOpenAI.Containers = Containers;\nOpenAI.ContainerListResponsesPage = ContainerListResponsesPage;\nexport declare namespace OpenAI {\n export type RequestOptions = Core.RequestOptions;\n\n export import Page = Pagination.Page;\n export { type PageResponse as PageResponse };\n\n export import CursorPage = Pagination.CursorPage;\n export { type CursorPageParams as CursorPageParams, type CursorPageResponse as CursorPageResponse };\n\n export {\n Completions as Completions,\n type Completion as Completion,\n type CompletionChoice as CompletionChoice,\n type CompletionUsage as CompletionUsage,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n\n export {\n Chat as Chat,\n type ChatCompletion as ChatCompletion,\n type ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam,\n type ChatCompletionAudio as ChatCompletionAudio,\n type ChatCompletionAudioParam as ChatCompletionAudioParam,\n type ChatCompletionChunk as ChatCompletionChunk,\n type ChatCompletionContentPart as ChatCompletionContentPart,\n type ChatCompletionContentPartImage as ChatCompletionContentPartImage,\n type ChatCompletionContentPartInputAudio as ChatCompletionContentPartInputAudio,\n type ChatCompletionContentPartRefusal as ChatCompletionContentPartRefusal,\n type ChatCompletionContentPartText as ChatCompletionContentPartText,\n type ChatCompletionDeleted as ChatCompletionDeleted,\n type ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam,\n type ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOption,\n type ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam,\n type ChatCompletionMessage as ChatCompletionMessage,\n type ChatCompletionMessageParam as ChatCompletionMessageParam,\n type ChatCompletionMessageToolCall as ChatCompletionMessageToolCall,\n type ChatCompletionModality as ChatCompletionModality,\n type ChatCompletionNamedToolChoice as ChatCompletionNamedToolChoice,\n type ChatCompletionPredictionContent as ChatCompletionPredictionContent,\n type ChatCompletionRole as ChatCompletionRole,\n type ChatCompletionStoreMessage as ChatCompletionStoreMessage,\n type ChatCompletionStreamOptions as ChatCompletionStreamOptions,\n type ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam,\n type ChatCompletionTokenLogprob as ChatCompletionTokenLogprob,\n type ChatCompletionTool as ChatCompletionTool,\n type ChatCompletionToolChoiceOption as ChatCompletionToolChoiceOption,\n type ChatCompletionToolMessageParam as ChatCompletionToolMessageParam,\n type ChatCompletionUserMessageParam as ChatCompletionUserMessageParam,\n type CreateChatCompletionRequestMessage as CreateChatCompletionRequestMessage,\n type ChatCompletionReasoningEffort as ChatCompletionReasoningEffort,\n ChatCompletionsPage as ChatCompletionsPage,\n type ChatCompletionCreateParams as ChatCompletionCreateParams,\n type ChatCompletionCreateParamsNonStreaming as ChatCompletionCreateParamsNonStreaming,\n type ChatCompletionCreateParamsStreaming as ChatCompletionCreateParamsStreaming,\n type ChatCompletionUpdateParams as ChatCompletionUpdateParams,\n type ChatCompletionListParams as ChatCompletionListParams,\n };\n\n export {\n Embeddings as Embeddings,\n type CreateEmbeddingResponse as CreateEmbeddingResponse,\n type Embedding as Embedding,\n type EmbeddingModel as EmbeddingModel,\n type EmbeddingCreateParams as EmbeddingCreateParams,\n };\n\n export {\n Files as Files,\n type FileContent as FileContent,\n type FileDeleted as FileDeleted,\n type FileObject as FileObject,\n type FilePurpose as FilePurpose,\n FileObjectsPage as FileObjectsPage,\n type FileCreateParams as FileCreateParams,\n type FileListParams as FileListParams,\n };\n\n export {\n Images as Images,\n type Image as Image,\n type ImageModel as ImageModel,\n type ImagesResponse as ImagesResponse,\n type ImageCreateVariationParams as ImageCreateVariationParams,\n type ImageEditParams as ImageEditParams,\n type ImageGenerateParams as ImageGenerateParams,\n };\n\n export { Audio as Audio, type AudioModel as AudioModel, type AudioResponseFormat as AudioResponseFormat };\n\n export {\n Moderations as Moderations,\n type Moderation as Moderation,\n type ModerationImageURLInput as ModerationImageURLInput,\n type ModerationModel as ModerationModel,\n type ModerationMultiModalInput as ModerationMultiModalInput,\n type ModerationTextInput as ModerationTextInput,\n type ModerationCreateResponse as ModerationCreateResponse,\n type ModerationCreateParams as ModerationCreateParams,\n };\n\n export {\n Models as Models,\n type Model as Model,\n type ModelDeleted as ModelDeleted,\n ModelsPage as ModelsPage,\n };\n\n export { FineTuning as FineTuning };\n\n export { Graders as Graders };\n\n export {\n VectorStores as VectorStores,\n type AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam,\n type FileChunkingStrategy as FileChunkingStrategy,\n type FileChunkingStrategyParam as FileChunkingStrategyParam,\n type OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject,\n type StaticFileChunkingStrategy as StaticFileChunkingStrategy,\n type StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject,\n type StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam,\n type VectorStore as VectorStore,\n type VectorStoreDeleted as VectorStoreDeleted,\n type VectorStoreSearchResponse as VectorStoreSearchResponse,\n VectorStoresPage as VectorStoresPage,\n VectorStoreSearchResponsesPage as VectorStoreSearchResponsesPage,\n type VectorStoreCreateParams as VectorStoreCreateParams,\n type VectorStoreUpdateParams as VectorStoreUpdateParams,\n type VectorStoreListParams as VectorStoreListParams,\n type VectorStoreSearchParams as VectorStoreSearchParams,\n };\n\n export { Beta as Beta };\n\n export {\n Batches as Batches,\n type Batch as Batch,\n type BatchError as BatchError,\n type BatchRequestCounts as BatchRequestCounts,\n BatchesPage as BatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n\n export {\n UploadsAPIUploads as Uploads,\n type Upload as Upload,\n type UploadCreateParams as UploadCreateParams,\n type UploadCompleteParams as UploadCompleteParams,\n };\n\n export { Responses as Responses };\n\n export {\n Evals as Evals,\n type EvalCustomDataSourceConfig as EvalCustomDataSourceConfig,\n type EvalStoredCompletionsDataSourceConfig as EvalStoredCompletionsDataSourceConfig,\n type EvalCreateResponse as EvalCreateResponse,\n type EvalRetrieveResponse as EvalRetrieveResponse,\n type EvalUpdateResponse as EvalUpdateResponse,\n type EvalListResponse as EvalListResponse,\n type EvalDeleteResponse as EvalDeleteResponse,\n EvalListResponsesPage as EvalListResponsesPage,\n type EvalCreateParams as EvalCreateParams,\n type EvalUpdateParams as EvalUpdateParams,\n type EvalListParams as EvalListParams,\n };\n\n export {\n Containers as Containers,\n type ContainerCreateResponse as ContainerCreateResponse,\n type ContainerRetrieveResponse as ContainerRetrieveResponse,\n type ContainerListResponse as ContainerListResponse,\n ContainerListResponsesPage as ContainerListResponsesPage,\n type ContainerCreateParams as ContainerCreateParams,\n type ContainerListParams as ContainerListParams,\n };\n\n export type AllModels = API.AllModels;\n export type ChatModel = API.ChatModel;\n export type ComparisonFilter = API.ComparisonFilter;\n export type CompoundFilter = API.CompoundFilter;\n export type ErrorObject = API.ErrorObject;\n export type FunctionDefinition = API.FunctionDefinition;\n export type FunctionParameters = API.FunctionParameters;\n export type Metadata = API.Metadata;\n export type Reasoning = API.Reasoning;\n export type ReasoningEffort = API.ReasoningEffort;\n export type ResponseFormatJSONObject = API.ResponseFormatJSONObject;\n export type ResponseFormatJSONSchema = API.ResponseFormatJSONSchema;\n export type ResponseFormatText = API.ResponseFormatText;\n export type ResponsesModel = API.ResponsesModel;\n}\n\n// ---------------------- Azure ----------------------\n\n/** API Client for interfacing with the Azure OpenAI API. */\nexport interface AzureClientOptions extends ClientOptions {\n /**\n * Defaults to process.env['OPENAI_API_VERSION'].\n */\n apiVersion?: string | undefined;\n\n /**\n * Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`\n */\n endpoint?: string | undefined;\n\n /**\n * A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.\n * Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs.\n */\n deployment?: string | undefined;\n\n /**\n * Defaults to process.env['AZURE_OPENAI_API_KEY'].\n */\n apiKey?: string | undefined;\n\n /**\n * A function that returns an access token for Microsoft Entra (formerly known as Azure Active Directory),\n * which will be invoked on every request.\n */\n azureADTokenProvider?: (() => Promise<string>) | undefined;\n}\n\n/** API Client for interfacing with the Azure OpenAI API. */\nexport class AzureOpenAI extends OpenAI {\n private _azureADTokenProvider: (() => Promise<string>) | undefined;\n deploymentName: string | undefined;\n apiVersion: string = '';\n /**\n * API Client for interfacing with the Azure OpenAI API.\n *\n * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]\n * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`\n * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]\n * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({\n baseURL = Core.readEnv('OPENAI_BASE_URL'),\n apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'),\n apiVersion = Core.readEnv('OPENAI_API_VERSION'),\n endpoint,\n deployment,\n azureADTokenProvider,\n dangerouslyAllowBrowser,\n ...opts\n }: AzureClientOptions = {}) {\n if (!apiVersion) {\n throw new Errors.OpenAIError(\n \"The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).\",\n );\n }\n\n if (typeof azureADTokenProvider === 'function') {\n dangerouslyAllowBrowser = true;\n }\n\n if (!azureADTokenProvider && !apiKey) {\n throw new Errors.OpenAIError(\n 'Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.',\n );\n }\n\n if (azureADTokenProvider && apiKey) {\n throw new Errors.OpenAIError(\n 'The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.',\n );\n }\n\n // define a sentinel value to avoid any typing issues\n apiKey ??= API_KEY_SENTINEL;\n\n opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };\n\n if (!baseURL) {\n if (!endpoint) {\n endpoint = process.env['AZURE_OPENAI_ENDPOINT'];\n }\n\n if (!endpoint) {\n throw new Errors.OpenAIError(\n 'Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable',\n );\n }\n\n baseURL = `${endpoint}/openai`;\n } else {\n if (endpoint) {\n throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');\n }\n }\n\n super({\n apiKey,\n baseURL,\n ...opts,\n ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),\n });\n\n this._azureADTokenProvider = azureADTokenProvider;\n this.apiVersion = apiVersion;\n this.deploymentName = deployment;\n }\n\n override buildRequest(\n options: Core.FinalRequestOptions<unknown>,\n props: { retryCount?: number } = {},\n ): {\n req: RequestInit;\n url: string;\n timeout: number;\n } {\n if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {\n if (!Core.isObj(options.body)) {\n throw new Error('Expected request body to be an object');\n }\n const model = this.deploymentName || options.body['model'] || options.__metadata?.['model'];\n if (model !== undefined && !this.baseURL.includes('/deployments')) {\n options.path = `/deployments/${model}${options.path}`;\n }\n }\n return super.buildRequest(options, props);\n }\n\n async _getAzureADToken(): Promise<string | undefined> {\n if (typeof this._azureADTokenProvider === 'function') {\n const token = await this._azureADTokenProvider();\n if (!token || typeof token !== 'string') {\n throw new Errors.OpenAIError(\n `Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`,\n );\n }\n return token;\n }\n return undefined;\n }\n\n protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {\n return {};\n }\n\n protected override async prepareOptions(opts: Core.FinalRequestOptions<unknown>): Promise<void> {\n /**\n * The user should provide a bearer token provider if they want\n * to use Azure AD authentication. The user shouldn't set the\n * Authorization header manually because the header is overwritten\n * with the Azure AD token if a bearer token provider is provided.\n */\n if (opts.headers?.['api-key']) {\n return super.prepareOptions(opts);\n }\n const token = await this._getAzureADToken();\n opts.headers ??= {};\n if (token) {\n opts.headers['Authorization'] = `Bearer ${token}`;\n } else if (this.apiKey !== API_KEY_SENTINEL) {\n opts.headers['api-key'] = this.apiKey;\n } else {\n throw new Errors.OpenAIError('Unable to handle auth');\n }\n return super.prepareOptions(opts);\n }\n}\n\nconst _deployments_endpoints = new Set([\n '/completions',\n '/chat/completions',\n '/embeddings',\n '/audio/transcriptions',\n '/audio/translations',\n '/audio/speech',\n '/images/generations',\n '/images/edits',\n]);\n\nconst API_KEY_SENTINEL = '<Missing Key>';\n\n// ---------------------- End Azure ----------------------\n\nexport { toFile, fileFromPath } from './uploads';\nexport {\n OpenAIError,\n APIError,\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n NotFoundError,\n ConflictError,\n RateLimitError,\n BadRequestError,\n AuthenticationError,\n InternalServerError,\n PermissionDeniedError,\n UnprocessableEntityError,\n} from './error';\n\nexport default OpenAI;\n","import { mkdir } from \"node:fs/promises\";\nimport { loadConfig } from \"../config.js\";\nimport { logInfo, logWarn } from \"../commands/io.js\";\n\nexport const CHUNK_SIZE: number = 1000;\nexport const CHUNK_OVERLAP: number = 100;\nexport const SEPARATORS = [\"\\n\\n\", \"\\n\", \". \", \" \", \"\"] as const;\n\nexport const SUMMARY_MAX_TOKENS = 30000;\nexport const SUMMARY_CONCURRENCY = 3;\nexport const SUMMARY_TARGET_WORDS = 250;\n\nexport type ResolvedPaths = {\n dataDir: string;\n booksDir: string;\n vectorsDir: string;\n ingestDir: string;\n dbPath: string;\n};\n\nexport const resolvePaths = async (): Promise<ResolvedPaths> => {\n const config = await loadConfig();\n const dataDir = config.dataDir;\n return {\n dataDir,\n booksDir: `${dataDir}/books`,\n vectorsDir: `${dataDir}/vectors`,\n ingestDir: `${dataDir}/ingest`,\n dbPath: `${dataDir}/metadata.db`,\n };\n};\n\nexport const ensureDataDirs = async () => {\n const paths = await resolvePaths();\n await mkdir(paths.dataDir, { recursive: true });\n await mkdir(paths.booksDir, { recursive: true });\n await mkdir(paths.vectorsDir, { recursive: true });\n await mkdir(paths.ingestDir, { recursive: true });\n return paths;\n};\n\nexport const getModels = async () => {\n const config = await loadConfig();\n return config.models;\n};\n\nexport const isAskEnabled = async () => {\n const config = await loadConfig();\n return config.askEnabled;\n};\n\nexport const requireOpenAIKey = () => {\n if (!process.env.OPENAI_API_KEY) {\n throw new Error(\"OPENAI_API_KEY is not set. Export it to use embeddings and chat.\");\n }\n};\n\nexport { logInfo, logWarn };\n","import { mkdir, readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\n\nexport type ConfigModels = {\n embedding: string;\n summary: string;\n chat: string;\n};\n\nexport type AppConfig = {\n dataDir: string;\n askEnabled: boolean;\n models: ConfigModels;\n};\n\nconst DEFAULT_CONFIG: AppConfig = {\n dataDir: \"~/.local/share/mycroft\",\n askEnabled: true,\n models: {\n embedding: \"text-embedding-3-small\",\n summary: \"gpt-5-nano\",\n chat: \"gpt-5.1\",\n },\n};\n\nconst expandHome = (input: string): string => {\n if (!input.startsWith(\"~\")) return input;\n return join(homedir(), input.slice(1));\n};\n\nconst resolvePath = (input: string): string => resolve(expandHome(input));\n\nconst getConfigPath = (): string => {\n const override = process.env.MYCROFT_CONFIG;\n if (override) return resolvePath(override);\n return resolvePath(\"~/.config/mycroft/config.json\");\n};\n\nconst normalizeModels = (models?: Partial<ConfigModels>): ConfigModels => ({\n embedding: models?.embedding || DEFAULT_CONFIG.models.embedding,\n summary: models?.summary || DEFAULT_CONFIG.models.summary,\n chat: models?.chat || DEFAULT_CONFIG.models.chat,\n});\n\ntype ConfigOverrides = {\n dataDir?: string;\n};\n\nlet overrides: ConfigOverrides = {};\n\nexport const setConfigOverrides = (next: ConfigOverrides) => {\n overrides = { ...overrides, ...next };\n};\n\nconst normalizeConfig = (input: Partial<AppConfig> | null): AppConfig => {\n const dataDirEnv = process.env.MYCROFT_DATA_DIR;\n const dataDir = overrides.dataDir || dataDirEnv || input?.dataDir || DEFAULT_CONFIG.dataDir;\n return {\n dataDir,\n askEnabled: input?.askEnabled ?? DEFAULT_CONFIG.askEnabled,\n models: normalizeModels(input?.models),\n };\n};\n\nconst readConfigFile = async (path: string): Promise<Partial<AppConfig> | null> => {\n try {\n const contents = await readFile(path, \"utf-8\");\n return JSON.parse(contents) as Partial<AppConfig>;\n } catch {\n return null;\n }\n};\n\nexport const loadConfig = async (): Promise<AppConfig> => {\n const configPath = getConfigPath();\n const data = await readConfigFile(configPath);\n const normalized = normalizeConfig(data);\n return {\n ...normalized,\n dataDir: resolvePath(normalized.dataDir),\n };\n};\n\nexport const ensureConfigDirs = async (configPath?: string) => {\n const path = configPath || getConfigPath();\n await mkdir(dirname(path), { recursive: true });\n};\n\nexport const configPath = () => getConfigPath();\n","import chalk from \"chalk\";\n\nconst isTTY = () => Boolean(process.stdout.isTTY);\nexport const isInteractive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);\n\nexport const formatDim = (text: string) => (isTTY() ? chalk.dim(text) : text);\nexport const formatError = (text: string) => (isTTY() ? chalk.red(text) : text);\nexport const formatBold = (text: string) => (isTTY() ? chalk.bold(text) : text);\nexport const formatWarn = (text: string) => (isTTY() ? chalk.yellow(text) : text);\n\nexport const stdout = (message: string) => {\n process.stdout.write(message.endsWith(\"\\n\") ? message : `${message}\\n`);\n};\n\nexport const stderr = (message: string) => {\n process.stderr.write(message.endsWith(\"\\n\") ? message : `${message}\\n`);\n};\n\nexport const printError = (message: string) => {\n stderr(formatError(`Error: ${message}`));\n};\n\nexport const logInfo = (message: string) => {\n stderr(message);\n};\n\nexport const logWarn = (message: string) => {\n stderr(formatWarn(message));\n};\n\nexport const handleSigint = (onCancel?: () => void) => {\n const handler = () => {\n if (onCancel) onCancel();\n stderr(\"\\nCancelled.\");\n process.exit(130);\n };\n process.once(\"SIGINT\", handler);\n return () => process.off(\"SIGINT\", handler);\n};\n","import OpenAI from \"openai\";\nimport type { BookChunk } from \"../shared/types.js\";\nimport type { EmbeddedChunk } from \"./embedder.js\";\nimport { getModels, logInfo, logWarn } from \"./constants.js\";\n\ntype BatchRequestLine = {\n custom_id: string;\n method: \"POST\";\n url: \"/v1/embeddings\";\n body: { model: string; input: string };\n};\n\nconst buildJsonl = (chunks: BookChunk[], model: string): string =>\n chunks\n .map(\n (chunk, i): BatchRequestLine => ({\n custom_id: String(i),\n method: \"POST\",\n url: \"/v1/embeddings\",\n body: { model, input: chunk.content },\n })\n )\n .map((line) => JSON.stringify(line))\n .join(\"\\n\");\n\nexport type BatchSubmitResult = {\n batchId: string;\n inputFileId: string;\n};\n\nexport const submitBatchEmbeddings = async (chunks: BookChunk[]): Promise<BatchSubmitResult> => {\n const models = await getModels();\n const client = new OpenAI();\n\n logInfo(`[BatchEmbedder] Preparing batch request for ${chunks.length} chunks`);\n\n const jsonl = buildJsonl(chunks, models.embedding);\n const blob = new Blob([jsonl], { type: \"application/jsonl\" });\n const file = await client.files.create({\n file: new File([blob], \"embeddings.jsonl\", { type: \"application/jsonl\" }),\n purpose: \"batch\",\n });\n logInfo(`[BatchEmbedder] Uploaded input file ${file.id}`);\n\n const batch = await client.batches.create({\n input_file_id: file.id,\n endpoint: \"/v1/embeddings\",\n completion_window: \"24h\",\n });\n logInfo(`[BatchEmbedder] Created batch ${batch.id} — status: ${batch.status}`);\n\n return { batchId: batch.id, inputFileId: file.id };\n};\n\nexport type BatchStatus = {\n status: string;\n completed: number;\n total: number;\n outputFileId: string | null;\n};\n\nexport const checkBatchStatus = async (batchId: string): Promise<BatchStatus> => {\n const client = new OpenAI();\n const batch = await client.batches.retrieve(batchId);\n return {\n status: batch.status,\n completed: batch.request_counts?.completed ?? 0,\n total: batch.request_counts?.total ?? 0,\n outputFileId: batch.output_file_id ?? null,\n };\n};\n\nexport const downloadBatchResults = async (\n outputFileId: string,\n chunks: BookChunk[],\n): Promise<EmbeddedChunk[]> => {\n const client = new OpenAI();\n\n logInfo(`[BatchEmbedder] Downloading results from ${outputFileId}`);\n const response = await client.files.content(outputFileId);\n const text = await response.text();\n const lines = text.trim().split(\"\\n\");\n\n const vectors = new Map<number, number[]>();\n for (const line of lines) {\n const result = JSON.parse(line);\n const idx = Number(result.custom_id);\n if (result.response?.status_code === 200) {\n const embedding = result.response.body?.data?.[0]?.embedding;\n if (embedding) {\n vectors.set(idx, embedding);\n }\n } else {\n logWarn(\n `[BatchEmbedder] Request ${idx} failed: ${JSON.stringify(result.response?.body?.error ?? result.error)}`\n );\n }\n }\n\n const embedded: EmbeddedChunk[] = chunks.map((chunk, i) => ({\n ...chunk,\n vector: vectors.get(i) ?? [],\n }));\n\n const missing = embedded.filter((e) => e.vector.length === 0).length;\n if (missing > 0) {\n logWarn(`[BatchEmbedder] ${missing} chunk(s) have empty embeddings due to batch errors`);\n }\n\n logInfo(`[BatchEmbedder] Successfully processed ${embedded.length} chunks via batch API`);\n return embedded;\n};\n\nexport const cleanupBatchFiles = async (inputFileId: string, outputFileId?: string | null) => {\n const client = new OpenAI();\n await client.files.del(inputFileId).catch(() => undefined);\n if (outputFileId) {\n await client.files.del(outputFileId).catch(() => undefined);\n }\n};\n"],"mappings":";;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AAgBZ,WAAO,UAAU,SAAU,KAAK,SAAS;AACvC,gBAAU,WAAW,CAAC;AACtB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,YAAY,IAAI,SAAS,GAAG;AACvC,eAAO,MAAM,GAAG;AAAA,MAClB,WAAW,SAAS,YAAY,SAAS,GAAG,GAAG;AAC7C,eAAO,QAAQ,OAAO,QAAQ,GAAG,IAAI,SAAS,GAAG;AAAA,MACnD;AACA,YAAM,IAAI;AAAA,QACR,0DACE,KAAK,UAAU,GAAG;AAAA,MACtB;AAAA,IACF;AAUA,aAAS,MAAMA,MAAK;AACl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Controller","str","is_array","Blob","File","Blob","kind","FormData","_FormData_setEntry","File","str","isFunction","kind","__classPrivateFieldGet","_FormDataEncoder_getFieldHeader","ReadableStream","fileFromPath","KeepAliveAgent","getMultipartRequestOptions","AbortControllerPolyfill","FormData","Blob","File","__classPrivateFieldSet","__classPrivateFieldGet","str","isFileLike","File","parseResponse","resolve","opts","Page","retryMessage","init","__classPrivateFieldSet","__classPrivateFieldGet","modifiedArg","__classPrivateFieldSet","resolve","__classPrivateFieldGet","resolve","chunk","__classPrivateFieldGet","__classPrivateFieldSet","_AssistantStream_endRequest","_AssistantStream_handleMessage","_AssistantStream_handleRunStep","_AssistantStream_handleEvent","_AssistantStream_accumulateRunStep","_AssistantStream_accumulateMessage","_AssistantStream_accumulateContent","_AssistantStream_handleRun","inputTool","__classPrivateFieldGet","content","name","_AbstractChatCompletionRunner_getFinalMessage","_AbstractChatCompletionRunner_getFinalFunctionCall","_AbstractChatCompletionRunner_getFinalFunctionCallResult","_AbstractChatCompletionRunner_calculateTotalUsage","_AbstractChatCompletionRunner_validateParams","_AbstractChatCompletionRunner_stringifyFunctionCallResult","escape","e","__classPrivateFieldSet","__classPrivateFieldGet","_ChatCompletionStream_beginRequest","_ChatCompletionStream_getChoiceEventState","_ChatCompletionStream_addChunk","assertNever","_ChatCompletionStream_emitToolCallDoneEvent","_ChatCompletionStream_emitContentDoneEvents","_ChatCompletionStream_endRequest","_ChatCompletionStream_getAutoParseableResponseFormat","_ChatCompletionStream_accumulateChatCompletion","content","refusal","rest","_a","index","resolve","chunk","id","Completions","Chat","Completions","Messages","Messages","Chat","Completions","response","Runs","Runs","Files","Checkpoints","Checkpoints","Graders","hasAutoParseableInput","parseToolCall","content","output","isAutoParsableTool","parseToolCall","__classPrivateFieldSet","__classPrivateFieldGet","_ResponseStream_beginRequest","_ResponseStream_addEvent","event","_ResponseStream_endRequest","_ResponseStream_accumulateResponse","resolve","Files","Files","Completions","Files","Graders","mkdir","configPath","mkdir"]}
|