drizzle-cube 0.5.0 → 0.5.3

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.
Files changed (118) hide show
  1. package/README.md +4 -0
  2. package/dist/adapters/express/index.cjs +2 -2
  3. package/dist/adapters/express/index.js +106 -102
  4. package/dist/adapters/fastify/index.cjs +2 -2
  5. package/dist/adapters/fastify/index.js +109 -105
  6. package/dist/adapters/{handler-3LGcjLtr.js → handler-BC3nFNxV.js} +2 -2
  7. package/dist/adapters/{handler-BzzbVpcl.cjs → handler-Cqf-CqAS.cjs} +2 -2
  8. package/dist/adapters/hono/index.cjs +1 -1
  9. package/dist/adapters/hono/index.js +41 -45
  10. package/dist/adapters/locale-BoiA6WiV.cjs +198 -0
  11. package/dist/adapters/{locale-DTnJrxm1.js → locale-D9VQkLXt.js} +442 -404
  12. package/dist/adapters/mcp-tools.cjs +1 -1
  13. package/dist/adapters/mcp-tools.d.ts +7 -3
  14. package/dist/adapters/mcp-tools.js +28 -28
  15. package/dist/adapters/mcp-transport-B0mgxRnJ.js +579 -0
  16. package/dist/adapters/mcp-transport-irsahKmD.cjs +39 -0
  17. package/dist/adapters/mcp-transport.d.ts +14 -2
  18. package/dist/adapters/nextjs/index.cjs +1 -1
  19. package/dist/adapters/nextjs/index.js +140 -136
  20. package/dist/adapters/{openai-C4BD8xnN.cjs → openai-B4N3KfTG.cjs} +1 -1
  21. package/dist/adapters/{openai-CaSQEduB.js → openai-BWdm0JvG.js} +1 -1
  22. package/dist/adapters/openai-CoqT_FM5.cjs +16 -0
  23. package/dist/{server/openai-CqZg6zYL.js → adapters/openai-D0Nsvc9L.js} +824 -720
  24. package/dist/adapters/{utils-DOg9oGdt.js → utils-CTYvfZ3I.js} +711 -713
  25. package/dist/adapters/{utils-DNrj-ryp.cjs → utils-XPOzzMdY.cjs} +5 -5
  26. package/dist/adapters/utils.cjs +1 -1
  27. package/dist/adapters/utils.d.ts +38 -2
  28. package/dist/adapters/utils.js +1 -1
  29. package/dist/cli/index.cjs +2 -2
  30. package/dist/client/charts.js +10 -10
  31. package/dist/client/chunks/{DashboardEditModal-cSSIAZGy.js → DashboardEditModal-IU_0dgfC.js} +12 -12
  32. package/dist/client/chunks/{DashboardEditModal-cSSIAZGy.js.map → DashboardEditModal-IU_0dgfC.js.map} +1 -1
  33. package/dist/client/chunks/{FieldSearchModal-CZNo4pNK.js → FieldSearchModal-BCWanpPX.js} +3 -3
  34. package/dist/client/chunks/{FieldSearchModal-CZNo4pNK.js.map → FieldSearchModal-BCWanpPX.js.map} +1 -1
  35. package/dist/client/chunks/KpiDelta-_igN6cJa.js +2 -0
  36. package/dist/client/chunks/KpiNumber-t5n8PtRU.js +2 -0
  37. package/dist/client/chunks/KpiText-BCZJJ6a0.js +2 -0
  38. package/dist/client/chunks/{RetentionCombinedChart-BD8tGeM_.js → RetentionCombinedChart-CQMBODsK.js} +2 -2
  39. package/dist/client/chunks/{RetentionCombinedChart-BD8tGeM_.js.map → RetentionCombinedChart-CQMBODsK.js.map} +1 -1
  40. package/dist/client/chunks/SchemaVisualization-BUUhlOvG.js +2 -0
  41. package/dist/client/chunks/SchemaVisualizationLazy-CwaPCUL0.js +2 -0
  42. package/dist/client/chunks/{analysis-builder-BeVZhiQ5.js → analysis-builder-Dm6eD_AX.js} +6 -6
  43. package/dist/client/chunks/{analysis-builder-BeVZhiQ5.js.map → analysis-builder-Dm6eD_AX.js.map} +1 -1
  44. package/dist/client/chunks/{analysis-builder-shared-BWc7ZZnG.js → analysis-builder-shared-DT5bXwCA.js} +6 -6
  45. package/dist/client/chunks/{analysis-builder-shared-BWc7ZZnG.js.map → analysis-builder-shared-DT5bXwCA.js.map} +1 -1
  46. package/dist/client/chunks/{chart-area-D63kG8OT.js → chart-area-DDti9Qtp.js} +2 -2
  47. package/dist/client/chunks/{chart-area-D63kG8OT.js.map → chart-area-DDti9Qtp.js.map} +1 -1
  48. package/dist/client/chunks/{chart-bar-BEfsCLjl.js → chart-bar-B3s9qDlh.js} +2 -2
  49. package/dist/client/chunks/{chart-bar-BEfsCLjl.js.map → chart-bar-B3s9qDlh.js.map} +1 -1
  50. package/dist/client/chunks/{chart-data-table-C3Xh9jwL.js → chart-data-table-Qrt6EAno.js} +17 -17
  51. package/dist/client/chunks/{chart-data-table-C3Xh9jwL.js.map → chart-data-table-Qrt6EAno.js.map} +1 -1
  52. package/dist/client/chunks/{chart-kpi-delta-CYE0S1x_.js → chart-kpi-delta-CgldZ7zO.js} +3 -3
  53. package/dist/client/chunks/{chart-kpi-delta-CYE0S1x_.js.map → chart-kpi-delta-CgldZ7zO.js.map} +1 -1
  54. package/dist/client/chunks/{chart-kpi-number-BlZ79xHW.js → chart-kpi-number-ByfuX1ki.js} +5 -5
  55. package/dist/client/chunks/{chart-kpi-number-BlZ79xHW.js.map → chart-kpi-number-ByfuX1ki.js.map} +1 -1
  56. package/dist/client/chunks/{chart-kpi-text-DY1BnxPe.js → chart-kpi-text-DeNuDraJ.js} +2 -2
  57. package/dist/client/chunks/{chart-kpi-text-DY1BnxPe.js.map → chart-kpi-text-DeNuDraJ.js.map} +1 -1
  58. package/dist/client/chunks/{chart-line-CBsTThTv.js → chart-line-RdZwtk27.js} +2 -2
  59. package/dist/client/chunks/{chart-line-CBsTThTv.js.map → chart-line-RdZwtk27.js.map} +1 -1
  60. package/dist/client/chunks/{chart-markdown-BWaWVkuz.js → chart-markdown-CiGRZdJj.js} +1203 -1139
  61. package/dist/client/chunks/chart-markdown-CiGRZdJj.js.map +1 -0
  62. package/dist/client/chunks/{chart-measure-profile-B41qCTBG.js → chart-measure-profile-Ckjw9bX6.js} +2 -2
  63. package/dist/client/chunks/{chart-measure-profile-B41qCTBG.js.map → chart-measure-profile-Ckjw9bX6.js.map} +1 -1
  64. package/dist/client/chunks/{chart-pie-Djbu8x2v.js → chart-pie-BvY4FY__.js} +2 -2
  65. package/dist/client/chunks/{chart-pie-Djbu8x2v.js.map → chart-pie-BvY4FY__.js.map} +1 -1
  66. package/dist/client/chunks/{chart-radar-BsTcKV0K.js → chart-radar-DjiiEAmc.js} +2 -2
  67. package/dist/client/chunks/{chart-radar-BsTcKV0K.js.map → chart-radar-DjiiEAmc.js.map} +1 -1
  68. package/dist/client/chunks/{chart-radial-bar-Du7XNnwE.js → chart-radial-bar-lla_JEYu.js} +2 -2
  69. package/dist/client/chunks/{chart-radial-bar-Du7XNnwE.js.map → chart-radial-bar-lla_JEYu.js.map} +1 -1
  70. package/dist/client/chunks/{chart-scatter-D8krEYsA.js → chart-scatter-DwXnI0rr.js} +2 -2
  71. package/dist/client/chunks/{chart-scatter-D8krEYsA.js.map → chart-scatter-DwXnI0rr.js.map} +1 -1
  72. package/dist/client/chunks/{chart-tree-map-C5C2iaWM.js → chart-tree-map-DJHoA26f.js} +2 -2
  73. package/dist/client/chunks/{chart-tree-map-C5C2iaWM.js.map → chart-tree-map-DJHoA26f.js.map} +1 -1
  74. package/dist/client/chunks/{chart-waterfall-BGdPrJ5Y.js → chart-waterfall-Y7c8csO5.js} +2 -2
  75. package/dist/client/chunks/{chart-waterfall-BGdPrJ5Y.js.map → chart-waterfall-Y7c8csO5.js.map} +1 -1
  76. package/dist/client/chunks/{core-DcfMGTVa.js → core-Dk6z6kC0.js} +2 -2
  77. package/dist/client/chunks/{core-DcfMGTVa.js.map → core-Dk6z6kC0.js.map} +1 -1
  78. package/dist/client/chunks/{exceljs.min-CcjgM-qg.js → exceljs.min-DaJsLlWM.js} +24 -24
  79. package/dist/client/chunks/{exceljs.min-CcjgM-qg.js.map → exceljs.min-DaJsLlWM.js.map} +1 -1
  80. package/dist/client/chunks/{schema-visualization-Xp60Ff2W.js → schema-visualization-DWwJukK7.js} +8 -8
  81. package/dist/client/chunks/{schema-visualization-Xp60Ff2W.js.map → schema-visualization-DWwJukK7.js.map} +1 -1
  82. package/dist/client/chunks/{syntaxHighlighting-CnDujqwg.js → syntaxHighlighting-D8J6Yt9j.js} +2 -2
  83. package/dist/client/chunks/{syntaxHighlighting-CnDujqwg.js.map → syntaxHighlighting-D8J6Yt9j.js.map} +1 -1
  84. package/dist/client/chunks/{useDebounce-CfmUMFau.js → useDebounce-DyJVREop.js} +2 -2
  85. package/dist/client/chunks/{useDebounce-CfmUMFau.js.map → useDebounce-DyJVREop.js.map} +1 -1
  86. package/dist/client/chunks/{useExplainAI-BKGmejIj.js → useExplainAI-CxSkjocM.js} +4 -4
  87. package/dist/client/chunks/{useExplainAI-BKGmejIj.js.map → useExplainAI-CxSkjocM.js.map} +1 -1
  88. package/dist/client/chunks/{utils-BldkcRHv.js → utils-BHZdKxua.js} +2 -2
  89. package/dist/client/chunks/{utils-BldkcRHv.js.map → utils-BHZdKxua.js.map} +1 -1
  90. package/dist/client/chunks/{vendor-ClXpIiea.js → vendor-CBD_Olr0.js} +8 -8
  91. package/dist/client/chunks/{vendor-ClXpIiea.js.map → vendor-CBD_Olr0.js.map} +1 -1
  92. package/dist/client/components.js +3 -3
  93. package/dist/client/hooks.js +3 -3
  94. package/dist/client/icons.js +1 -1
  95. package/dist/client/index.js +11 -11
  96. package/dist/client/providers.js +1 -1
  97. package/dist/client/schema.js +1 -1
  98. package/dist/client/utils.js +5 -5
  99. package/dist/client-bundle-stats.html +1 -1
  100. package/dist/mcp-app/mcp-app.html +39 -37
  101. package/dist/server/index.cjs +42 -42
  102. package/dist/server/index.js +1009 -971
  103. package/dist/server/{openai-D9Zjuby1.cjs → openai-BfiZU0rG.cjs} +1 -1
  104. package/dist/server/openai-BwsBio1K.cjs +16 -0
  105. package/dist/server/{openai-rwauPzCT.js → openai-CLWSwD-D.js} +1 -1
  106. package/dist/{adapters/openai-BAnEZgKZ.js → server/openai-zpXlGbbF.js} +824 -720
  107. package/package.json +2 -2
  108. package/dist/adapters/locale-DueXjqMh.cjs +0 -198
  109. package/dist/adapters/mcp-transport-45SiFcCH.cjs +0 -39
  110. package/dist/adapters/mcp-transport-Bxpc4mRy.js +0 -553
  111. package/dist/adapters/openai-4JP2B6pB.cjs +0 -16
  112. package/dist/client/chunks/KpiDelta-Dll_eCV1.js +0 -2
  113. package/dist/client/chunks/KpiNumber-BPlR92hI.js +0 -2
  114. package/dist/client/chunks/KpiText-BIxq7Jso.js +0 -2
  115. package/dist/client/chunks/SchemaVisualization-CCICjhvv.js +0 -2
  116. package/dist/client/chunks/SchemaVisualizationLazy-DraGsMx6.js +0 -2
  117. package/dist/client/chunks/chart-markdown-BWaWVkuz.js.map +0 -1
  118. package/dist/server/openai-DmuEbFd6.cjs +0 -16
@@ -1 +1 @@
1
- var e=class{client;apiKey;baseURL;initialized=!1;constructor(e,t){this.apiKey=e,this.baseURL=t?.baseURL}async ensureClient(){if(this.initialized)return;let e;try{let t=await Promise.resolve().then(()=>require(`./openai-DmuEbFd6.cjs`));e=t.default||t.OpenAI||t}catch{throw Error(`openai is required for the OpenAI provider. Install it with: npm install openai`)}let t={apiKey:this.apiKey};this.baseURL&&(t.baseURL=this.baseURL),this.client=new e(t),this.initialized=!0}async createStream(e){await this.ensureClient();let{messages:t}=this.formatMessages(e.messages,e.system);return this.client.chat.completions.create({model:e.model,max_completion_tokens:e.maxTokens,tools:this.formatTools(e.tools),messages:t,stream:!0,stream_options:{include_usage:!0}})}async*parseStreamEvents(e){let t=new Map;for await(let n of e){let e=n;e.usage&&(yield{type:`message_meta`,inputTokens:e.usage.prompt_tokens,outputTokens:e.usage.completion_tokens,stopReason:``});let r=e.choices?.[0];if(!r)continue;let i=r.delta;if(i){if(i.content&&(yield{type:`text_delta`,text:i.content}),i.tool_calls)for(let e of i.tool_calls){let n=e.index??0;if(e.id&&(t.set(n,{id:e.id,name:e.function?.name||``,arguments:``}),yield{type:`tool_use_start`,id:e.id,name:e.function?.name||``}),e.function?.name&&t.has(n)){let r=t.get(n);r.name||=e.function.name}if(e.function?.arguments){let r=t.get(n);r&&(r.arguments+=e.function.arguments,yield{type:`tool_input_delta`,json:e.function.arguments})}}if(r.finish_reason){for(let[e,n]of t){let r={};try{n.arguments&&(r=JSON.parse(n.arguments))}catch{}yield{type:`tool_use_end`,id:n.id,input:r},t.delete(e)}yield{type:`message_meta`,stopReason:r.finish_reason}}}}}formatTools(e){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}formatMessages(e,t){let n=[{role:`system`,content:t}];for(let t of e)if(t.role===`user`)n.push({role:`user`,content:typeof t.content==`string`?t.content:JSON.stringify(t.content)});else if(t.role===`assistant`)if(typeof t.content==`string`)n.push({role:`assistant`,content:t.content});else{let e=t.content,r=e.filter(e=>e.type===`text`).map(e=>e.text).join(``),i=e.filter(e=>e.type===`tool_use`).map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input||{})}})),a={role:`assistant`};r&&(a.content=r),i.length>0&&(a.tool_calls=i),n.push(a)}else t.role===`tool`?n.push(t):t.role===`tool_result`&&n.push({role:`user`,content:typeof t.content==`string`?t.content:JSON.stringify(t.content)});return{messages:n}}formatToolResults(e){return e.map(e=>({role:`tool`,tool_call_id:e.toolUseId,content:e.content}))}shouldContinue(e){return e===`tool_calls`}formatError(e){if(!e||!(e instanceof Error))return`Something went wrong. Please try again.`;let t=e.message||``,n=e;return n.status===429?`Too many requests. Please wait a moment and try again.`:n.status===401?`Authentication failed. Please check your API key configuration.`:n.status===503||n.status===502?`The AI service is temporarily unavailable. Please try again in a moment.`:n.status===400?`There was a problem with the request. Please try again.`:t.startsWith(`{`)||t.startsWith(`Error: {`)?`The AI service encountered an error. Please try again.`:t}};exports.OpenAIProvider=e;
1
+ var e=class{client;apiKey;baseURL;initialized=!1;constructor(e,t){this.apiKey=e,this.baseURL=t?.baseURL}async ensureClient(){if(this.initialized)return;let e;try{let t=await Promise.resolve().then(()=>require(`./openai-BwsBio1K.cjs`));e=t.default||t.OpenAI||t}catch{throw Error(`openai is required for the OpenAI provider. Install it with: npm install openai`)}let t={apiKey:this.apiKey};this.baseURL&&(t.baseURL=this.baseURL),this.client=new e(t),this.initialized=!0}async createStream(e){await this.ensureClient();let{messages:t}=this.formatMessages(e.messages,e.system);return this.client.chat.completions.create({model:e.model,max_completion_tokens:e.maxTokens,tools:this.formatTools(e.tools),messages:t,stream:!0,stream_options:{include_usage:!0}})}async*parseStreamEvents(e){let t=new Map;for await(let n of e){let e=n;e.usage&&(yield{type:`message_meta`,inputTokens:e.usage.prompt_tokens,outputTokens:e.usage.completion_tokens,stopReason:``});let r=e.choices?.[0];if(!r)continue;let i=r.delta;if(i){if(i.content&&(yield{type:`text_delta`,text:i.content}),i.tool_calls)for(let e of i.tool_calls){let n=e.index??0;if(e.id&&(t.set(n,{id:e.id,name:e.function?.name||``,arguments:``}),yield{type:`tool_use_start`,id:e.id,name:e.function?.name||``}),e.function?.name&&t.has(n)){let r=t.get(n);r.name||=e.function.name}if(e.function?.arguments){let r=t.get(n);r&&(r.arguments+=e.function.arguments,yield{type:`tool_input_delta`,json:e.function.arguments})}}if(r.finish_reason){for(let[e,n]of t){let r={};try{n.arguments&&(r=JSON.parse(n.arguments))}catch{}yield{type:`tool_use_end`,id:n.id,input:r},t.delete(e)}yield{type:`message_meta`,stopReason:r.finish_reason}}}}}formatTools(e){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}formatMessages(e,t){let n=[{role:`system`,content:t}];for(let t of e)if(t.role===`user`)n.push({role:`user`,content:typeof t.content==`string`?t.content:JSON.stringify(t.content)});else if(t.role===`assistant`)if(typeof t.content==`string`)n.push({role:`assistant`,content:t.content});else{let e=t.content,r=e.filter(e=>e.type===`text`).map(e=>e.text).join(``),i=e.filter(e=>e.type===`tool_use`).map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input||{})}})),a={role:`assistant`};r&&(a.content=r),i.length>0&&(a.tool_calls=i),n.push(a)}else t.role===`tool`?n.push(t):t.role===`tool_result`&&n.push({role:`user`,content:typeof t.content==`string`?t.content:JSON.stringify(t.content)});return{messages:n}}formatToolResults(e){return e.map(e=>({role:`tool`,tool_call_id:e.toolUseId,content:e.content}))}shouldContinue(e){return e===`tool_calls`}formatError(e){if(!e||!(e instanceof Error))return`Something went wrong. Please try again.`;let t=e.message||``,n=e;return n.status===429?`Too many requests. Please wait a moment and try again.`:n.status===401?`Authentication failed. Please check your API key configuration.`:n.status===503||n.status===502?`The AI service is temporarily unavailable. Please try again in a moment.`:n.status===400?`There was a problem with the request. Please try again.`:t.startsWith(`{`)||t.startsWith(`Error: {`)?`The AI service encountered an error. Please try again.`:t}};exports.OpenAIProvider=e;
@@ -0,0 +1,16 @@
1
+ function e(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function t(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var n=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return n=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function r(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var i=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},a=class extends Error{},o=class e extends a{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,a){if(!t||!a)return new c({message:r,cause:i(n)});let o=n?.error;return t===400?new u(t,o,r,a):t===401?new d(t,o,r,a):t===403?new f(t,o,r,a):t===404?new p(t,o,r,a):t===409?new m(t,o,r,a):t===422?new h(t,o,r,a):t===429?new g(t,o,r,a):t>=500?new _(t,o,r,a):new e(t,o,r,a)}},s=class extends o{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},c=class extends o{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},l=class extends c{constructor({message:e}={}){super({message:e??`Request timed out.`})}},u=class extends o{},d=class extends o{},f=class extends o{},p=class extends o{},m=class extends o{},h=class extends o{},g=class extends o{},_=class extends o{},v=class extends a{constructor(){super(`Could not parse response content as the length limit was reached`)}},y=class extends a{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},b=class extends Error{constructor(e){super(e)}},x=class extends o{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},ee=class extends a{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},S=/^[a-z][a-z0-9+.-]*:/i,C=e=>S.test(e),w=e=>(w=Array.isArray,w(e)),T=w;function te(e){return typeof e==`object`?e??{}:{}}function ne(e){if(!e)return!0;for(let t in e)return!1;return!0}function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ae=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},oe=e=>{try{return JSON.parse(e)}catch{return}},se=e=>new Promise(t=>setTimeout(t,e)),ce=`6.34.0`,le=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function ue(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var de=()=>{let e=ue();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ce,"X-Stainless-OS":me(Deno.build.os),"X-Stainless-Arch":pe(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ce,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ce,"X-Stainless-OS":me(globalThis.process.platform??`unknown`),"X-Stainless-Arch":pe(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=fe();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ce,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ce,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function fe(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var pe=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,me=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),he,ge=()=>he??=de();function _e(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ve(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ye(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ve({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function be(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function xe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Se=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Ce=`RFC3986`,we=e=>String(e),Te={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:we},Ee=(e,t)=>(Ee=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ee(e,t)),E=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),De=1024,Oe=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=De){let t=a.length>=De?a.slice(e,e+De):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=E[r];continue}if(r<2048){n[n.length]=E[192|r>>6]+E[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=E[224|r>>12]+E[128|r>>6&63]+E[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=E[240|r>>18]+E[128|r>>12&63]+E[128|r>>6&63]+E[128|r&63]}o+=n.join(``)}return o};function ke(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Ae(e,t){if(w(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var je={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Me=function(e,t){Array.prototype.push.apply(e,w(t)?t:[t])},Ne,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Oe,encodeValuesOnly:!1,format:Ce,formatter:we,indices:!1,serializeDate(e){return(Ne??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Pe(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Fe={};function Ie(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(Fe))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(Fe)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&w(v)&&(v=Ae(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,D.encoder,g,`key`,p):t;v=``}if(Pe(v)||ke(v)){if(c){let e=h?t:c(t,D.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,D.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let S;if(n===`comma`&&w(v))h&&c&&(v=Ae(v,c)),S=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(w(l))S=l;else{let e=Object.keys(v);S=u?e.sort(u):e}let C=s?String(t).replace(/\./g,`%2E`):String(t),T=r&&w(v)&&v.length===1?C+`[]`:C;if(i&&w(v)&&v.length===0)return T+`[]`;for(let t=0;t<S.length;++t){let y=S[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let C=d&&s?y.replace(/\./g,`%2E`):y,te=w(v)?typeof n==`function`?n(T,C):T:T+(d?`.`+C:`[`+C+`]`);_.set(e,b);let ne=new WeakMap;ne.set(Fe,_),Me(ee,Ie(x,te,n,r,i,a,o,s,n===`comma`&&h&&w(v)?null:c,l,u,d,f,p,m,h,g,ne))}return ee}function Le(e=D){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||D.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Ce;if(e.format!==void 0){if(!Ee(Te,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Te[n],i=D.filter;(typeof e.filter==`function`||w(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in je?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:D.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:D.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:D.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?D.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:D.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:D.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:D.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:D.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:D.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:D.strictNullHandling}}function Re(e,t={}){let n=e,r=Le(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):w(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=je[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||Me(o,Ie(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function ze(e){return Re(e,{arrayFormat:`brackets`})}function Be(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Ve;function He(e){let t;return(Ve??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Ue;function We(e){let t;return(Ue??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var O,k,Ge=class{constructor(){O.set(this,void 0),k.set(this,void 0),e(this,O,new Uint8Array,`f`),e(this,k,null,`f`)}decode(n){if(n==null)return[];let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?He(n):n;e(this,O,Be([t(this,O,`f`),r]),`f`);let i=[],a;for(;(a=Ke(t(this,O,`f`),t(this,k,`f`)))!=null;){if(a.carriage&&t(this,k,`f`)==null){e(this,k,a.index,`f`);continue}if(t(this,k,`f`)!=null&&(a.index!==t(this,k,`f`)+1||a.carriage)){i.push(We(t(this,O,`f`).subarray(0,t(this,k,`f`)-1))),e(this,O,t(this,O,`f`).subarray(t(this,k,`f`)),`f`),e(this,k,null,`f`);continue}let n=t(this,k,`f`)===null?a.preceding:a.preceding-1,r=We(t(this,O,`f`).subarray(0,n));i.push(r),e(this,O,t(this,O,`f`).subarray(a.index),`f`),e(this,k,null,`f`)}return i}flush(){return t(this,O,`f`).length?this.decode(`
2
+ `):[]}};O=new WeakMap,k=new WeakMap,Ge.NEWLINE_CHARS=new Set([`
3
+ `,`\r`]),Ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ke(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function qe(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Je={off:0,error:200,warn:300,info:400,debug:500},Ye=(e,t,n)=>{if(e){if(re(Je,e))return e;A(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Je))}`)}};function Xe(){}function Ze(e,t,n){return!t||Je[e]>Je[n]?Xe:t[e].bind(t)}var Qe={error:Xe,warn:Xe,info:Xe,debug:Xe},$e=new WeakMap;function A(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Qe;let r=$e.get(t);if(r&&r[0]===n)return r[1];let i={error:Ze(`error`,t,n),warn:Ze(`warn`,t,n),info:Ze(`info`,t,n),debug:Ze(`debug`,t,n)};return $e.set(t,[n,i]),i}var j=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),et,tt=class n{constructor(t,n,r){this.iterator=t,et.set(this,void 0),this.controller=n,e(this,et,r,`f`)}static fromSSEResponse(e,t,i,s){let c=!1,l=i?A(i):console;async function*u(){if(c)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let n=!1;try{for await(let r of nt(e,t))if(!n){if(r.data.startsWith(`[DONE]`)){n=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let t;try{t=JSON.parse(r.data)}catch(e){throw l.error(`Could not parse message into JSON:`,r.data),l.error(`From chunk:`,r.raw),e}if(t&&t.error)throw new o(void 0,t.error,void 0,e.headers);yield s?{event:r.event,data:t}:t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new o(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(r(e))return;throw e}finally{n||t.abort()}}return new n(u,t,i)}static fromReadableStream(e,t,i){let o=!1;async function*s(){let t=new Ge,n=be(e);for await(let e of n)for(let n of t.decode(e))yield n;for(let e of t.flush())yield e}async function*c(){if(o)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let e=!1;try{for await(let t of s())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(r(e))return;throw e}finally{e||t.abort()}}return new n(c,t,i)}[(et=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],i=this.iterator(),a=t=>({next:()=>{if(t.length===0){let t=i.next();e.push(t),r.push(t)}return t.shift()}});return[new n(()=>a(e),this.controller,t(this,et,`f`)),new n(()=>a(r),this.controller,t(this,et,`f`))]}toReadableStream(){let e=this,t;return ve({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=He(JSON.stringify(n)+`
4
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*nt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);let n=new it,r=new Ge,i=be(e.body);for await(let e of rt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*rt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?He(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=qe(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var it=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=at(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function at(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function ot(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return A(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):tt.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:st(await n.json(),n):await n.text()})();return A(e).debug(`[${r}] response parsed`,j({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function st(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`x-request-id`),enumerable:!1})}var ct,lt=class n extends Promise{constructor(t,n,r=ot){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,ct.set(this,void 0),e(this,ct,t,`f`)}_thenUnwrap(e){return new n(t(this,ct,`f`),this.responsePromise,async(t,n)=>st(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(t(this,ct,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ct=new WeakMap;var ut,dt=class{constructor(t,n,r,i){ut.set(this,void 0),e(this,ut,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,ut,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ut=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ft=class extends lt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await ot(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},pt=class extends dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},M=class extends dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...te(this.options.query),after:t}}:null}},mt=class extends dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...te(this.options.query),after:e}}:null}},ht={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},gt=`urn:ietf:params:oauth:grant-type:token-exchange`,_t=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??_e()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({grant_type:gt,client_id:this.config.clientId,subject_token:e,subject_token_type:ht[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new x(t.status,n,t.headers):o.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json(),r=n.expires_in||3600,i=Date.now()+r*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},vt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function yt(e,t,n){return vt(),new File(e,t??`unknown_file`,n)}function bt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var xt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,St=async(e,t)=>Ot(e.body)?{...e,body:await Tt(e.body,t)}:e,N=async(e,t)=>({...e,body:await Tt(e.body,t)}),Ct=new WeakMap;function wt(e){let t=typeof e==`function`?e:e.fetch,n=Ct.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Ct.set(t,r),r}var Tt=async(e,t)=>{if(!await wt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>kt(n,e,t))),n},Et=e=>e instanceof Blob&&`name`in e,Dt=e=>typeof e==`object`&&!!e&&(e instanceof Response||xt(e)||Et(e)),Ot=e=>{if(Dt(e))return!0;if(Array.isArray(e))return e.some(Ot);if(e&&typeof e==`object`){for(let t in e)if(Ot(e[t]))return!0}return!1},kt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,yt([await n.blob()],bt(n)));else if(xt(n))e.append(t,yt([await new Response(ye(n)).blob()],bt(n)));else if(Et(n))e.append(t,n,bt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>kt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>kt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},At=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,jt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&At(e),Mt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Nt(e,t,n){if(vt(),e=await e,jt(e))return e instanceof File?e:yt([await e.arrayBuffer()],e.name);if(Mt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),yt(await Pt(r),t,n)}let r=await Pt(e);if(t||=bt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return yt(r,t,n)}async function Pt(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(At(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(xt(e))for await(let n of e)t.push(...await Pt(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Ft(e)}`)}return t}function Ft(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var P=class{constructor(e){this._client=e}};function It(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Lt=Object.freeze(Object.create(null)),F=((e=It)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Lt)??Lt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
+ `)}\n${o}\n${t}`)}return o})(It),Rt=class extends P{list(e,t={},n){return this._client.getAPIList(F`/chat/completions/${e}/messages`,M,{query:t,...n})}};function zt(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Bt(e){return e?.$brand===`auto-parseable-response-format`}function Vt(e){return e?.$brand===`auto-parseable-tool`}function Ht(e,t){return!t||!qt(t)?{...e,choices:e.choices.map(e=>(Jt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Ut(e,t)}function Ut(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Jt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Gt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Wt(t,e.message.content):null}}});return{...e,choices:n}}function Wt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Gt(e,t){let n=e.tools?.find(e=>zt(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Vt(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Kt(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>zt(e)&&e.function?.name===t.function.name);return zt(n)&&(Vt(n)||n?.function.strict||!1)}function qt(e){return Bt(e.response_format)?!0:e.tools?.some(e=>Vt(e)||e.type===`function`&&e.function.strict===!0)??!1}function Jt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Yt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Xt=e=>e?.role===`assistant`,Zt=e=>e?.role===`tool`,Qt,$t,en,tn,nn,rn,an,I,on,sn,cn,L,ln,un=class{constructor(){Qt.add(this),this.controller=new AbortController,$t.set(this,void 0),en.set(this,()=>{}),tn.set(this,()=>{}),nn.set(this,void 0),rn.set(this,()=>{}),an.set(this,()=>{}),I.set(this,{}),on.set(this,!1),sn.set(this,!1),cn.set(this,!1),L.set(this,!1),e(this,$t,new Promise((t,n)=>{e(this,en,t,`f`),e(this,tn,n,`f`)}),`f`),e(this,nn,new Promise((t,n)=>{e(this,rn,t,`f`),e(this,an,n,`f`)}),`f`),t(this,$t,`f`).catch(()=>{}),t(this,nn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,Qt,`m`,ln).bind(this))},0)}_connected(){this.ended||(t(this,en,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,on,`f`)}get errored(){return t(this,sn,`f`)}get aborted(){return t(this,cn,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,I,`f`)[e]||(t(this,I,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,I,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,I,`f`)[e]||(t(this,I,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,L,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,L,!0,`f`),await t(this,nn,`f`)}_emit(n,...r){if(t(this,on,`f`))return;n===`end`&&(e(this,on,!0,`f`),t(this,rn,`f`).call(this));let i=t(this,I,`f`)[n];if(i&&(t(this,I,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,L,`f`)&&!i?.length&&Promise.reject(e),t(this,tn,`f`).call(this,e),t(this,an,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,L,`f`)&&!i?.length&&Promise.reject(e),t(this,tn,`f`).call(this,e),t(this,an,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};$t=new WeakMap,en=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,I=new WeakMap,on=new WeakMap,sn=new WeakMap,cn=new WeakMap,L=new WeakMap,Qt=new WeakSet,ln=function(t){if(e(this,sn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,cn,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function dn(e){return typeof e.parse==`function`}var R,fn,pn,mn,hn,gn,_n,vn,yn=10,bn=class extends un{constructor(){super(...arguments),R.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Zt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Xt(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,R,`m`,fn).call(this)}async finalMessage(){return await this.done(),t(this,R,`m`,pn).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,R,`m`,mn).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,R,`m`,hn).call(this)}async totalUsage(){return await this.done(),t(this,R,`m`,gn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,R,`m`,pn).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,R,`m`,fn).call(this);r&&this._emit(`finalContent`,r);let i=t(this,R,`m`,mn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,R,`m`,hn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,R,`m`,gn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,_n).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ut(a,n))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=yn}=r||{},d=n.tools.map(e=>{if(Vt(e)){if(!e.$callback)throw new a("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}else if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=dn(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,R,`m`,vn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};R=new WeakSet,fn=function(){return t(this,R,`m`,pn).call(this).content??null},pn=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Xt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},mn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Xt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},hn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Zt(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},gn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},_n=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},vn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var xn=class e extends bn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Xt(e)&&e.content&&this._emit(`content`,e.content)}},Sn=1,Cn=2,wn=4,Tn=8,En=16,Dn=32,On=64,kn=128,An=256,jn=kn|An,Mn=496,Nn=Cn|497,Pn=wn|Tn,z={STR:Sn,NUM:Cn,ARR:wn,OBJ:Tn,NULL:En,BOOL:Dn,NAN:On,INFINITY:kn,MINUS_INFINITY:An,INF:jn,SPECIAL:Mn,ATOM:Nn,COLLECTION:Pn,ALL:Nn|Pn},Fn=class extends Error{},In=class extends Error{};function Ln(e,t=z.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Rn(e.trim(),t)}var Rn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new Fn(`${e} at position ${r}`)},a=e=>{throw new In(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||z.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||z.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||z.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||z.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||z.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||z.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(z.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&z.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(z.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(z.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(z.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(z.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(z.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
7
+ \r `.includes(e[r]);)r++};return o()},zn=e=>Ln(e,z.ALL^z.NUM),B,V,Bn,H,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn=class n extends bn{constructor(t){super(),B.add(this),V.set(this,void 0),Bn.set(this,void 0),H.set(this,void 0),e(this,V,t,`f`),e(this,Bn,[],`f`)}get currentChatCompletionSnapshot(){return t(this,H,`f`)}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let i=new n(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,B,`m`,Vn).call(this);let a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)t(this,B,`m`,Un).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,B,`m`,Kn).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),t(this,B,`m`,Vn).call(this),this._connected();let i=tt.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(t(this,B,`m`,Kn).call(this)),t(this,B,`m`,Un).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,B,`m`,Kn).call(this))}[(V=new WeakMap,Bn=new WeakMap,H=new WeakMap,B=new WeakSet,Vn=function(){this.ended||e(this,H,void 0,`f`)},Hn=function(e){let n=t(this,Bn,`f`)[e.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},t(this,Bn,`f`)[e.index]=n,n)},Un=function(e){if(this.ended)return;let n=t(this,B,`m`,Jn).call(this,e);this._emit(`chunk`,e,n);for(let r of e.choices){let e=n.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=t(this,B,`m`,Hn).call(this,e);e.finish_reason&&(t(this,B,`m`,Gn).call(this,e),i.current_tool_call_index!=null&&t(this,B,`m`,Wn).call(this,e,i.current_tool_call_index));for(let n of r.delta.tool_calls??[])i.current_tool_call_index!==n.index&&(t(this,B,`m`,Gn).call(this,e),i.current_tool_call_index!=null&&t(this,B,`m`,Wn).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=n.index;for(let t of r.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},Wn=function(e,n){if(t(this,B,`m`,Hn).call(this,e).done_tool_calls.has(n))return;let r=e.message.tool_calls?.[n];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=t(this,V,`f`)?.tools?.find(e=>zt(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:n,arguments:r.function.arguments,parsed_arguments:Vt(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Gn=function(e){let n=t(this,B,`m`,Hn).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,B,`m`,qn).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},Kn=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,H,`f`);if(!n)throw new a(`request ended without sending any chunks`);return e(this,H,void 0,`f`),e(this,Bn,[],`f`),Xn(n,t(this,V,`f`))},qn=function(){let e=t(this,V,`f`)?.response_format;return Bt(e)?e:null},Jn=function(n){var r,i,a,o;let s=t(this,H,`f`),{choices:c,...l}=n;s?Object.assign(s,l):s=e(this,H,{...l,choices:[]},`f`);for(let{delta:e,finish_reason:c,index:l,logprobs:u=null,...d}of n.choices){let n=s.choices[l];if(n||=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d},u)if(!n.logprobs)n.logprobs=Object.assign({},u);else{let{content:e,refusal:t,...a}=u;Object.assign(n.logprobs,a),e&&((r=n.logprobs).content??(r.content=[]),n.logprobs.content.push(...e)),t&&((i=n.logprobs).refusal??(i.refusal=[]),n.logprobs.refusal.push(...t))}if(c&&(n.finish_reason=c,t(this,V,`f`)&&qt(t(this,V,`f`)))){if(c===`length`)throw new v;if(c===`content_filter`)throw new y}if(Object.assign(n,d),!e)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=e;if(Object.assign(n.message,_),p&&(n.message.refusal=(n.message.refusal||``)+p),h&&(n.message.role=h),m&&(n.message.function_call?(m.name&&(n.message.function_call.name=m.name),m.arguments&&((a=n.message.function_call).arguments??(a.arguments=``),n.message.function_call.arguments+=m.arguments)):n.message.function_call=m),f&&(n.message.content=(n.message.content||``)+f,!n.message.refusal&&t(this,B,`m`,qn).call(this)&&(n.message.parsed=zn(n.message.content))),g){n.message.tool_calls||(n.message.tool_calls=[]);for(let{index:e,id:r,type:i,function:a,...s}of g){let c=(o=n.message.tool_calls)[e]??(o[e]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??={name:a.name??``,arguments:``}),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Kt(t(this,V,`f`),c)&&(c.function.parsed_arguments=zn(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Xn(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Ht({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...o})=>{if(!n)throw new a(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:l,...u}=t,d=t.role;if(!d)throw new a(`missing role for choice ${r}`);if(c){let{arguments:e,name:l}=c;if(e==null)throw new a(`missing function_call.arguments for choice ${r}`);if(!l)throw new a(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:l},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...o,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:o,id:s,...c}=t,{arguments:l,name:u,...d}=i||{};if(s==null)throw new a(`missing choices[${r}].tool_calls[${n}].id\n${Zn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${Zn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${Zn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Zn(e)}`);return{...c,id:s,type:o,function:{...d,name:u,arguments:l}}})}}:{...o,message:{...u,content:s,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Zn(e){return JSON.stringify(e)}var Qn=class e extends Yn{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},$n=class extends P{constructor(){super(...arguments),this.messages=new Rt(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(F`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(F`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,M,{query:e,...t})}delete(e,t){return this._client.delete(F`/chat/completions/${e}`,t)}parse(e,t){return Yt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>Ut(t,e))}runTools(e,t){return e.stream?Qn.runTools(this._client,e,t):xn.runTools(this._client,e,t)}stream(e,t){return Yn.createChatCompletion(this._client,e,t)}};$n.Messages=Rt;var er=class extends P{constructor(){super(...arguments),this.completions=new $n(this._client)}};er.Completions=$n;var tr=Symbol(`brand.privateNullableHeaders`);function*nr(e){if(!e)return;if(tr in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():T(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=T(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var U=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of nr(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[tr]:!0,values:t,nulls:n}},rr=class extends P{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:U([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},ir=class extends P{create(e,t){return this._client.post(`/audio/transcriptions`,N({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},ar=class extends P{create(e,t){return this._client.post(`/audio/translations`,N({body:e,...t,__metadata:{model:e.model}},this._client))}},or=class extends P{constructor(){super(...arguments),this.transcriptions=new ir(this._client),this.translations=new ar(this._client),this.speech=new rr(this._client)}};or.Transcriptions=ir,or.Translations=ar,or.Speech=rr;var sr=class extends P{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,M,{query:e,...t})}cancel(e,t){return this._client.post(F`/batches/${e}/cancel`,t)}},cr=class extends P{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(F`/assistants/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(F`/assistants/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,M,{query:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(F`/assistants/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},lr=class extends P{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},ur=class extends P{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},dr=class extends P{constructor(){super(...arguments),this.sessions=new lr(this._client),this.transcriptionSessions=new ur(this._client)}};dr.Sessions=lr,dr.TranscriptionSessions=ur;var fr=class extends P{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(F`/chatkit/sessions/${e}/cancel`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},pr=class extends P{retrieve(e,t){return this._client.get(F`/chatkit/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,mt,{query:e,...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(F`/chatkit/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(F`/chatkit/threads/${e}/items`,mt,{query:t,...n,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},mr=class extends P{constructor(){super(...arguments),this.sessions=new fr(this._client),this.threads=new pr(this._client)}};mr.Sessions=fr,mr.Threads=pr;var hr=class extends P{create(e,t,n){return this._client.post(F`/threads/${e}/messages`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(F`/threads/${r}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/messages/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(F`/threads/${e}/messages`,M,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(F`/threads/${r}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},gr=class extends P{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(F`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(F`/threads/${r}/runs/${e}/steps`,M,{query:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},_r=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},W=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()},G,K,vr,q,yr,J,Y,br,X,xr,Z,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr=class extends un{constructor(){super(...arguments),G.add(this),vr.set(this,[]),q.set(this,{}),yr.set(this,{}),J.set(this,void 0),Y.set(this,void 0),br.set(this,void 0),X.set(this,void 0),xr.set(this,void 0),Z.set(this,void 0),Sr.set(this,void 0),Cr.set(this,void 0),wr.set(this,void 0)}[(vr=new WeakMap,q=new WeakMap,yr=new WeakMap,J=new WeakMap,Y=new WeakMap,br=new WeakMap,X=new WeakMap,xr=new WeakMap,Z=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,wr=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new K;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=tt.fromReadableStream(e,this.controller);for await(let e of i)t(this,G,`m`,Tr).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Er).call(this))}toReadableStream(){return new tt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new K;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.submitToolOutputs(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,G,`m`,Tr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Er).call(this))}static createThreadAssistantStream(e,t,n){let r=new K;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new K;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return t(this,Sr,`f`)}currentRun(){return t(this,Cr,`f`)}currentMessageSnapshot(){return t(this,J,`f`)}currentRunStepSnapshot(){return t(this,wr,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,yr,`f`))}async finalRun(){if(await this.done(),!t(this,Y,`f`))throw Error(`Final run was not received.`);return t(this,Y,`f`)}async _createThreadAssistantStream(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)t(this,G,`m`,Tr).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Er).call(this))}async _createAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.create(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,G,`m`,Tr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,Er).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ie(t)&&ie(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ie(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};K=Pr,Tr=function(n){if(!this.ended)switch(e(this,Sr,n,`f`),t(this,G,`m`,kr).call(this,n),n.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:t(this,G,`m`,Nr).call(this,n);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,G,`m`,Or).call(this,n);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:t(this,G,`m`,Dr).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},Er=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);if(!t(this,Y,`f`))throw Error(`Final run has not been received`);return t(this,Y,`f`)},Dr=function(n){let[r,i]=t(this,G,`m`,jr).call(this,n,t(this,J,`f`));e(this,J,r,`f`),t(this,yr,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.text)}switch(n.event){case`thread.message.created`:this._emit(`messageCreated`,n.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,n.data.delta,r),n.data.delta.content)for(let i of n.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=t(this,br,`f`)){if(t(this,X,`f`))switch(t(this,X,`f`).type){case`text`:this._emit(`textDone`,t(this,X,`f`).text,t(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,t(this,X,`f`).image_file,t(this,J,`f`));break}e(this,br,i.index,`f`)}e(this,X,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,br,`f`)!==void 0){let e=n.data.content[t(this,br,`f`)];if(e)switch(e.type){case`image_file`:this._emit(`imageFileDone`,e.image_file,t(this,J,`f`));break;case`text`:this._emit(`textDone`,e.text,t(this,J,`f`));break}}t(this,J,`f`)&&this._emit(`messageDone`,n.data),e(this,J,void 0,`f`)}},Or=function(n){let r=t(this,G,`m`,Ar).call(this,n);switch(e(this,wr,r,`f`),n.event){case`thread.run.step.created`:this._emit(`runStepCreated`,n.data);break;case`thread.run.step.delta`:let i=n.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let n of i.step_details.tool_calls)n.index==t(this,xr,`f`)?this._emit(`toolCallDelta`,n,r.step_details.tool_calls[n.index]):(t(this,Z,`f`)&&this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,xr,n.index,`f`),e(this,Z,r.step_details.tool_calls[n.index],`f`),t(this,Z,`f`)&&this._emit(`toolCallCreated`,t(this,Z,`f`)));this._emit(`runStepDelta`,n.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:e(this,wr,void 0,`f`),n.data.step_details.type==`tool_calls`&&t(this,Z,`f`)&&(this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Z,void 0,`f`)),this._emit(`runStepDone`,n.data,r);break;case`thread.run.step.in_progress`:break}},kr=function(e){t(this,vr,`f`).push(e),this._emit(`event`,e)},Ar=function(e){switch(e.event){case`thread.run.step.created`:return t(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let n=t(this,q,`f`)[e.data.id];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=K.accumulateDelta(n,r.delta);t(this,q,`f`)[e.data.id]=i}return t(this,q,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:t(this,q,`f`)[e.data.id]=e.data;break}if(t(this,q,`f`)[e.data.id])return t(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},jr=function(e,n){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!n)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in n.content){let r=n.content[e.index];n.content[e.index]=t(this,G,`m`,Mr).call(this,e,r)}else n.content[e.index]=e,r.push(e);return[n,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(n)return[n,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Mr=function(e,t){return K.accumulateDelta(t,e)},Nr=function(n){switch(e(this,Cr,n.data,`f`),n.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:e(this,Y,n.data,`f`),t(this,Z,`f`)&&(this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Z,void 0,`f`));break;case`thread.run.cancelling`:break}};var Fr=class extends P{constructor(){super(...arguments),this.steps=new gr(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(F`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(F`/threads/${r}/runs/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/runs/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(F`/threads/${e}/runs`,M,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(F`/threads/${r}/runs/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Pr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=U([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Pr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Pr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Fr.Steps=gr;var Ir=class extends P{constructor(){super(...arguments),this.runs=new Fr(this._client),this.messages=new hr(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(F`/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(F`/threads/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(F`/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Pr.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ir.Runs=Fr,Ir.Messages=hr;var Lr=class extends P{constructor(){super(...arguments),this.realtime=new dr(this._client),this.chatkit=new mr(this._client),this.assistants=new cr(this._client),this.threads=new Ir(this._client)}};Lr.Realtime=dr,Lr.ChatKit=mr,Lr.Assistants=cr,Lr.Threads=Ir;var Rr=class extends P{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},zr=class extends P{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(F`/containers/${r}/files/${e}/content`,{...n,headers:U([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},Br=class extends P{constructor(){super(...arguments),this.content=new zr(this._client)}create(e,t,n){return this._client.post(F`/containers/${e}/files`,St({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(F`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(F`/containers/${e}/files`,M,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(F`/containers/${r}/files/${e}`,{...n,headers:U([{Accept:`*/*`},n?.headers])})}};Br.Content=zr;var Vr=class extends P{constructor(){super(...arguments),this.files=new Br(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,M,{query:e,...t})}delete(e,t){return this._client.delete(F`/containers/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}};Vr.Files=Br;var Hr=class extends P{create(e,t,n){let{include:r,...i}=t;return this._client.post(F`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(F`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(F`/conversations/${e}/items`,mt,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(F`/conversations/${r}/items/${e}`,n)}},Ur=class extends P{constructor(){super(...arguments),this.items=new Hr(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/conversations/${e}`,t)}update(e,t,n){return this._client.post(F`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(F`/conversations/${e}`,t)}};Ur.Items=Hr;var Wr=class extends P{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&A(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(A(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=_r(t)}),e)))}},Gr=class extends P{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(F`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(F`/evals/${r}/runs/${e}/output_items`,M,{query:i,...n})}},Kr=class extends P{constructor(){super(...arguments),this.outputItems=new Gr(this._client)}create(e,t,n){return this._client.post(F`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(F`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(F`/evals/${e}/runs`,M,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(F`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(F`/evals/${r}/runs/${e}`,n)}};Kr.OutputItems=Gr;var qr=class extends P{constructor(){super(...arguments),this.runs=new Kr(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/evals/${e}`,t)}update(e,t,n){return this._client.post(F`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,M,{query:e,...t})}delete(e,t){return this._client.delete(F`/evals/${e}`,t)}};qr.Runs=Kr;var Jr=class extends P{create(e,t){return this._client.post(`/files`,N({body:e,...t},this._client))}retrieve(e,t){return this._client.get(F`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,M,{query:e,...t})}delete(e,t){return this._client.delete(F`/files/${e}`,t)}content(e,t){return this._client.get(F`/files/${e}/content`,{...t,headers:U([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await se(t),a=await this.retrieve(e),Date.now()-i>n)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Yr=class extends P{},Xr=class extends P{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},Zr=class extends P{constructor(){super(...arguments),this.graders=new Xr(this._client)}};Zr.Graders=Xr;var Qr=class extends P{create(e,t,n){return this._client.getAPIList(F`/fine_tuning/checkpoints/${e}/permissions`,pt,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(F`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(F`/fine_tuning/checkpoints/${e}/permissions`,mt,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(F`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},$r=class extends P{constructor(){super(...arguments),this.permissions=new Qr(this._client)}};$r.Permissions=Qr;var ei=class extends P{list(e,t={},n){return this._client.getAPIList(F`/fine_tuning/jobs/${e}/checkpoints`,M,{query:t,...n})}},ti=class extends P{constructor(){super(...arguments),this.checkpoints=new ei(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,M,{query:e,...t})}cancel(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(F`/fine_tuning/jobs/${e}/events`,M,{query:t,...n})}pause(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/resume`,t)}};ti.Checkpoints=ei;var ni=class extends P{constructor(){super(...arguments),this.methods=new Yr(this._client),this.jobs=new ti(this._client),this.checkpoints=new $r(this._client),this.alpha=new Zr(this._client)}};ni.Methods=Yr,ni.Jobs=ti,ni.Checkpoints=$r,ni.Alpha=Zr;var ri=class extends P{},ii=class extends P{constructor(){super(...arguments),this.graderModels=new ri(this._client)}};ii.GraderModels=ri;var ai=class extends P{createVariation(e,t){return this._client.post(`/images/variations`,N({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,N({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},oi=class extends P{retrieve(e,t){return this._client.get(F`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,pt,e)}delete(e,t){return this._client.delete(F`/models/${e}`,t)}},si=class extends P{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},ci=class extends P{accept(e,t,n){return this._client.post(F`/realtime/calls/${e}/accept`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(F`/realtime/calls/${e}/hangup`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(F`/realtime/calls/${e}/refer`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(F`/realtime/calls/${e}/reject`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers])})}},li=class extends P{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},ui=class extends P{constructor(){super(...arguments),this.clientSecrets=new li(this._client),this.calls=new ci(this._client)}};ui.ClientSecrets=li,ui.Calls=ci;function di(e,t){return!t||!mi(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:fi(e,t)}function fi(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:_i(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:pi(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||vi(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function pi(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function mi(e){return!!Bt(e.text?.format)}function hi(e){return e?.$brand===`auto-parseable-tool`}function gi(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function _i(e,t){let n=gi(e.tools??[],t.name);return{...t,...t,parsed_arguments:hi(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function vi(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var yi,bi,Q,xi,Si,Ci,wi,Ti,Ei=class n extends un{constructor(t){super(),yi.add(this),bi.set(this,void 0),Q.set(this,void 0),xi.set(this,void 0),e(this,bi,t,`f`)}static createResponse(e,t,r){let i=new n(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,yi,`m`,Si).call(this);let a,o=null;`response_id`in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)t(this,yi,`m`,Ci).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,yi,`m`,wi).call(this)}[(bi=new WeakMap,Q=new WeakMap,xi=new WeakMap,yi=new WeakSet,Si=function(){this.ended||e(this,Q,void 0,`f`)},Ci=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,yi,`m`,Ti).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new a(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${n.type}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e);break}},wi=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,Q,`f`);if(!n)throw new a(`request ended without sending any events`);e(this,Q,void 0,`f`);let r=Di(n,t(this,bi,`f`));return e(this,xi,r,`f`),r},Ti=function(n){let r=t(this,Q,`f`);if(!r){if(n.type!==`response.created`)throw new a(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=e(this,Q,n.response,`f`),r}switch(n.type){case`response.output_item.added`:r.output.push(n.item);break;case`response.content_part.added`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);let t=e.type,i=n.part;t===`message`&&i.type!==`reasoning_text`?e.content.push(i):t===`reasoning`&&i.type===`reasoning_text`&&(e.content||=[],e.content.push(i));break}case`response.output_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`message`){let t=e.content[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${t.type}`);t.text+=n.delta}break}case`response.function_call_arguments.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);e.type===`function_call`&&(e.arguments+=n.delta);break}case`response.reasoning_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`reasoning`){let t=e.content?.[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`reasoning_text`)throw new a(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=n.delta}break}case`response.completed`:e(this,Q,n.response,`f`);break}return r},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=t(this,xi,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function Di(e,t){return di(e,t)}var Oi=class extends P{list(e,t={},n){return this._client.getAPIList(F`/responses/${e}/input_items`,M,{query:t,...n})}},ki=class extends P{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},Ai=class extends P{constructor(){super(...arguments),this.inputItems=new Oi(this._client),this.inputTokens=new ki(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&vi(e),e))}retrieve(e,t={},n){return this._client.get(F`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&vi(e),e))}delete(e,t){return this._client.delete(F`/responses/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>fi(t,e))}stream(e,t){return Ei.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(F`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};Ai.InputItems=Oi,Ai.InputTokens=ki;var ji=class extends P{retrieve(e,t){return this._client.get(F`/skills/${e}/content`,{...t,headers:U([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},Mi=class extends P{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(F`/skills/${r}/versions/${e}/content`,{...n,headers:U([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},Ni=class extends P{constructor(){super(...arguments),this.content=new Mi(this._client)}create(e,t={},n){return this._client.post(F`/skills/${e}/versions`,St({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(F`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(F`/skills/${e}/versions`,M,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(F`/skills/${r}/versions/${e}`,n)}};Ni.Content=Mi;var Pi=class extends P{constructor(){super(...arguments),this.content=new ji(this._client),this.versions=new Ni(this._client)}create(e={},t){return this._client.post(`/skills`,St({body:e,...t},this._client))}retrieve(e,t){return this._client.get(F`/skills/${e}`,t)}update(e,t,n){return this._client.post(F`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,M,{query:e,...t})}delete(e,t){return this._client.delete(F`/skills/${e}`,t)}};Pi.Content=ji,Pi.Versions=Ni;var Fi=class extends P{create(e,t,n){return this._client.post(F`/uploads/${e}/parts`,N({body:t,...n},this._client))}},Ii=class extends P{constructor(){super(...arguments),this.parts=new Fi(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(F`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(F`/uploads/${e}/complete`,{body:t,...n})}};Ii.Parts=Fi;var Li=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},Ri=class extends P{create(e,t,n){return this._client.post(F`/vector_stores/${e}/file_batches`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(F`/vector_stores/${r}/file_batches/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(F`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(F`/vector_stores/${r}/file_batches/${e}/files`,M,{query:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=U([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await Li(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},zi=class extends P{create(e,t,n){return this._client.post(F`/vector_stores/${e}/files`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(F`/vector_stores/${r}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(F`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(F`/vector_stores/${e}/files`,M,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(F`/vector_stores/${r}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=U([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(F`/vector_stores/${r}/files/${e}/content`,pt,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Bi=class extends P{constructor(){super(...arguments),this.files=new zi(this._client),this.fileBatches=new Ri(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(F`/vector_stores/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(F`/vector_stores/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,M,{query:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(F`/vector_stores/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(F`/vector_stores/${e}/search`,pt,{body:t,method:`post`,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};Bi.Files=zi,Bi.FileBatches=Ri;var Vi=class extends P{create(e,t){return this._client.post(`/videos`,N({body:e,...t},this._client))}retrieve(e,t){return this._client.get(F`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,mt,{query:e,...t})}delete(e,t){return this._client.delete(F`/videos/${e}`,t)}createCharacter(e,t){return this._client.post(`/videos/characters`,N({body:e,...t},this._client))}downloadContent(e,t={},n){return this._client.get(F`/videos/${e}/content`,{query:t,...n,headers:U([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,N({body:e,...t},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,N({body:e,...t},this._client))}getCharacter(e,t){return this._client.get(F`/videos/characters/${e}`,t)}remix(e,t,n){return this._client.post(F`/videos/${e}/remix`,St({body:t,...n},this._client))}},Hi,Ui,Wi,Gi=class extends P{constructor(){super(...arguments),Hi.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");t(this,Hi,`m`,Ui).call(this,r);let a=U([n]).values,o=t(this,Hi,`m`,Wi).call(this,a,`webhook-signature`),s=t(this,Hi,`m`,Wi).call(this,a,`webhook-timestamp`),c=t(this,Hi,`m`,Wi).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new b(`The given webhook signature does not match the expected signature`)}};Hi=new WeakSet,Ui=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},Wi=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Ki,qi,Ji,Yi,Xi=`workload-identity-auth`,$=class{constructor({baseURL:t=W(`OPENAI_BASE_URL`),apiKey:n=W(`OPENAI_API_KEY`),organization:r=W(`OPENAI_ORG_ID`)??null,project:i=W(`OPENAI_PROJECT_ID`)??null,webhookSecret:o=W(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:s,...c}={}){if(Ki.add(this),Ji.set(this,void 0),this.completions=new Rr(this),this.chat=new er(this),this.embeddings=new Wr(this),this.files=new Jr(this),this.images=new ai(this),this.audio=new or(this),this.moderations=new si(this),this.models=new oi(this),this.fineTuning=new ni(this),this.graders=new ii(this),this.vectorStores=new Bi(this),this.webhooks=new Gi(this),this.beta=new Lr(this),this.batches=new sr(this),this.uploads=new Ii(this),this.responses=new Ai(this),this.realtime=new ui(this),this.conversations=new Ur(this),this.evals=new qr(this),this.containers=new Vr(this),this.skills=new Pi(this),this.videos=new Vi(this),s){if(n&&n!==Xi)throw new a("The `apiKey` and `workloadIdentity` arguments are mutually exclusive; only one can be passed at a time.");n=Xi}else if(n===void 0)throw new a("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, or set the `OPENAI_API_KEY` environment variable.");let l={apiKey:n,organization:r,project:i,webhookSecret:o,workloadIdentity:s,...c,baseURL:t||`https://api.openai.com/v1`};if(!l.dangerouslyAllowBrowser&&le())throw new a(`It looks like you're running in a browser-like environment.
8
+
9
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
+ If you understand the risks and have appropriate mitigations in place,
11
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
+
13
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
14
+
15
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
16
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??qi.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u=`warn`;this.logLevel=u,this.logLevel=Ye(l.logLevel,`ClientOptions.logLevel`,this)??Ye(W(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??_e(),e(this,Ji,Se,`f`),this._options=l,s&&(this._workloadIdentityAuth=new _t(s,this.fetch)),this.apiKey=typeof n==`string`?n:`Missing Key`,this.organization=r,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ze(e)}getUserAgent(){return`${this.constructor.name}/JS ${ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${n()}`}makeStatusError(e,t,n,r){return o.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof a?e:new a(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new a(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,n,r){let i=!t(this,Ki,`m`,Yi).call(this)&&r||this.baseURL,a=C(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(a.searchParams);return(!ne(o)||!ne(s))&&(n={...s,...o,...n}),typeof n==`object`&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new lt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let a=await e,o=a.maxRetries??this.maxRetries;t??=o,await this.prepareOptions(a);let{req:u,url:d,timeout:f}=await this.buildRequest(a,{retryCount:o-t});await this.prepareRequest(u,{url:d,options:a});let p=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(A(this).debug(`[${p}] sending request`,j({retryOfRequestLogID:n,method:a.method,url:d,options:a,headers:u.headers})),a.signal?.aborted)throw new s;let g=new AbortController,_=await this.fetchWithAuth(d,u,f,g).catch(i),v=Date.now();if(_ instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(a.signal?.aborted)throw new s;let i=r(_)||/timed? ?out/i.test(String(_)+(`cause`in _?String(_.cause):``));if(t)return A(this).info(`[${p}] connection ${i?`timed out`:`failed`} - ${e}`),A(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (${e})`,j({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),this.retryRequest(a,t,n??p);throw A(this).info(`[${p}] connection ${i?`timed out`:`failed`} - error; no more retries left`),A(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,j({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),_ instanceof x||_ instanceof ee?_:i?new l:new c({cause:_})}let y=`[${p}${m}${[..._.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${u.method} ${d} ${_.ok?`succeeded`:`failed`} with status ${_.status} in ${v-h}ms`;if(!_.ok){if(_.status===401&&this._workloadIdentityAuth&&!a.__metadata?.hasStreamingBody&&!a.__metadata?.workloadIdentityTokenRefreshed)return await xe(_.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...a,__metadata:{...a.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??p);let e=await this.shouldRetry(_);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await xe(_.body),A(this).info(`${y} - ${e}`),A(this).debug(`[${p}] response error (${e})`,j({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),this.retryRequest(a,t,n??p,_.headers)}let r=e?`error; no more retries left`:`error; not retryable`;A(this).info(`${y} - ${r}`);let o=await _.text().catch(e=>i(e).message),s=oe(o),c=s?void 0:o;throw A(this).debug(`[${p}] response error (${r})`,j({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(_.status,s,c,_.headers)}return A(this).info(y),A(this).debug(`[${p}] response start`,j({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),{response:_,options:a,controller:g,requestLogID:p,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new ft(this,n,e)}async fetchWithAuth(e,t,n,r){if(this._workloadIdentityAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${Xi}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ae(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=U([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ge(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=U([n]),i=globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream,a=!i&&(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||globalThis.Blob!==void 0&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&r.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||i?{bodyHeaders:void 0,body:e,isStreamingBody:!a}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:ye(e),isStreamingBody:!0}:typeof e==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e),isStreamingBody:!1}:{...t(this,Ji,`f`).call(this,{body:e,headers:r}),isStreamingBody:!1}}};qi=$,Ji=new WeakMap,Ki=new WeakSet,Yi=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=qi,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=a,$.APIError=o,$.APIConnectionError=c,$.APIConnectionTimeoutError=l,$.APIUserAbortError=s,$.NotFoundError=p,$.ConflictError=m,$.RateLimitError=g,$.BadRequestError=u,$.AuthenticationError=d,$.InternalServerError=_,$.PermissionDeniedError=f,$.UnprocessableEntityError=h,$.InvalidWebhookSignatureError=b,$.toFile=Nt,$.Completions=Rr,$.Chat=er,$.Embeddings=Wr,$.Files=Jr,$.Images=ai,$.Audio=or,$.Moderations=si,$.Models=oi,$.FineTuning=ni,$.Graders=ii,$.VectorStores=Bi,$.Webhooks=Gi,$.Beta=Lr,$.Batches=sr,$.Uploads=Ii,$.Responses=Ai,$.Realtime=ui,$.Conversations=Ur,$.Evals=qr,$.Containers=Vr,$.Skills=Pi,$.Videos=Vi;var Zi=class extends ${constructor({baseURL:e=W(`OPENAI_BASE_URL`),apiKey:t=W(`AZURE_OPENAI_API_KEY`),apiVersion:n=W(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:o,dangerouslyAllowBrowser:s,...c}={}){if(!n)throw new a(`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' }).`);if(typeof o==`function`&&(s=!0),!o&&!t)throw new a("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new a("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":n},!e){if(r||=process.env.AZURE_OPENAI_ENDPOINT,!r)throw new a("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new a(`baseURL and endpoint are mutually exclusive`);super({apiKey:o??t,baseURL:e,...c,...s===void 0?{}:{dangerouslyAllowBrowser:s}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(Qi.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!ie(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return typeof this._options.apiKey==`string`?U([{"api-key":this.apiKey}]):super.authHeaders(e)}},Qi=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);exports.APIConnectionError=c,exports.APIConnectionTimeoutError=l,exports.APIError=o,exports.APIPromise=lt,exports.APIUserAbortError=s,exports.AuthenticationError=d,exports.AzureOpenAI=Zi,exports.BadRequestError=u,exports.ConflictError=m,exports.InternalServerError=_,exports.InvalidWebhookSignatureError=b,exports.NotFoundError=p,exports.OAuthError=x,exports.OpenAI=$,exports.default=$,exports.OpenAIError=a,exports.PagePromise=ft,exports.PermissionDeniedError=f,exports.RateLimitError=g,exports.SubjectTokenProviderError=ee,exports.UnprocessableEntityError=h,exports.toFile=Nt;
@@ -13,7 +13,7 @@ var e = class {
13
13
  try {
14
14
  let t = await import(
15
15
  /* webpackIgnore: true */
16
- "./openai-CqZg6zYL.js"
16
+ "./openai-zpXlGbbF.js"
17
17
  );
18
18
  e = t.default || t.OpenAI || t;
19
19
  } catch {