@shumai-one/shumai 0.6.3 → 0.6.4

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 (188) hide show
  1. package/bin/{chunk-y3haqtr8.js → chunk-01vx2chc.js} +2 -2
  2. package/bin/chunk-0epkrexd.js +2 -0
  3. package/bin/chunk-0h5239kt.js +2 -0
  4. package/bin/{chunk-tfrevef9.js → chunk-0jnstdgf.js} +1 -1
  5. package/bin/{chunk-w6g84d59.js → chunk-0njsjy6x.js} +4 -4
  6. package/bin/{chunk-f8hgy69t.js → chunk-13rq2gtr.js} +2 -2
  7. package/bin/chunk-1aqs9sdh.js +3 -0
  8. package/bin/{chunk-09mj32d7.js → chunk-22jbsrka.js} +1 -1
  9. package/bin/chunk-2qknebmd.js +1 -0
  10. package/bin/{chunk-bd3v8mp1.js → chunk-2qzmh3ae.js} +4 -4
  11. package/bin/{chunk-p2vsdnd1.js → chunk-2tt0b8ym.js} +2 -2
  12. package/bin/{chunk-3s2ga6mt.js → chunk-2zm7czk6.js} +1 -1
  13. package/bin/{chunk-vmwys2ch.js → chunk-396tfwdx.js} +1 -1
  14. package/bin/chunk-3mx4trvh.js +10 -0
  15. package/bin/{chunk-j2txsbxz.js → chunk-45pb3kzz.js} +2 -2
  16. package/bin/{chunk-dkhdn92k.js → chunk-47fmhzwv.js} +2 -2
  17. package/bin/chunk-4awk4xhq.js +2 -0
  18. package/bin/{chunk-5ddg5ezb.js → chunk-4b2x2qba.js} +21 -21
  19. package/bin/{chunk-9x42vgeq.js → chunk-4rjy7ybr.js} +8 -8
  20. package/bin/{chunk-enax4303.js → chunk-598x693h.js} +2 -2
  21. package/bin/chunk-5c7ztqs7.js +1 -0
  22. package/bin/{chunk-4p31kxjh.js → chunk-65dh7x4c.js} +2 -2
  23. package/bin/{chunk-s74g9vsk.js → chunk-66e2vrky.js} +1 -1
  24. package/bin/{chunk-q8xr1a8j.js → chunk-6j3beg6n.js} +2 -2
  25. package/bin/{chunk-95b4mwyq.js → chunk-6ke13k69.js} +1 -1
  26. package/bin/{chunk-a859y4e1.js → chunk-6rqakmg0.js} +2 -2
  27. package/bin/{chunk-yb4mzqrd.js → chunk-6ty4tfmf.js} +3 -3
  28. package/bin/chunk-7e9ws6dh.js +129 -0
  29. package/bin/chunk-7mdddkfc.js +1 -0
  30. package/bin/{chunk-qvp24w0q.js → chunk-7q4mgd5x.js} +2 -2
  31. package/bin/chunk-7yv7shad.js +1 -0
  32. package/bin/{chunk-25npafhz.js → chunk-81b8rfv7.js} +2 -2
  33. package/bin/{chunk-etrm28sy.js → chunk-8a7ymmd4.js} +2 -2
  34. package/bin/chunk-8ac9at5y.js +2 -0
  35. package/bin/{chunk-sz19nn1x.js → chunk-8zcfgz9c.js} +1 -1
  36. package/bin/{chunk-te484xtb.js → chunk-955kf5kc.js} +3 -3
  37. package/bin/{chunk-h2bphev9.js → chunk-978rm9a9.js} +2 -2
  38. package/bin/{chunk-jt02kpfc.js → chunk-9qzbrp4d.js} +2 -2
  39. package/bin/{chunk-20bamhwa.js → chunk-a283dh05.js} +2 -2
  40. package/bin/chunk-aa2a06cc.js +1 -0
  41. package/bin/{chunk-esj0kwe5.js → chunk-ajr1w3vq.js} +6 -6
  42. package/bin/chunk-akafypge.js +218 -0
  43. package/bin/chunk-amk373q2.js +2 -0
  44. package/bin/{chunk-mn71dffh.js → chunk-apq2gvvp.js} +2 -2
  45. package/bin/chunk-av2w1sez.js +2 -0
  46. package/bin/{chunk-atpt99h4.js → chunk-b6kmj34z.js} +12 -12
  47. package/bin/chunk-bkzaw9p8.js +1 -0
  48. package/bin/{chunk-pq6kdp83.js → chunk-bssb9tar.js} +3 -3
  49. package/bin/chunk-bwvj1aqc.js +1 -0
  50. package/bin/chunk-by9esjn7.js +3 -0
  51. package/bin/chunk-bywk8mbc.js +2 -0
  52. package/bin/{chunk-r6t0j0jx.js → chunk-c61g9hfa.js} +4 -4
  53. package/bin/{chunk-mn0kt3p6.js → chunk-cdcgjh8k.js} +1 -1
  54. package/bin/{chunk-atdfqdkj.js → chunk-d277evce.js} +4 -4
  55. package/bin/{chunk-9405hzv2.js → chunk-d3brvxh7.js} +2 -2
  56. package/bin/{chunk-4vjgdj0h.js → chunk-dcb1nzf1.js} +1 -1
  57. package/bin/{chunk-q5x0yywj.js → chunk-dfbzatq9.js} +2 -2
  58. package/bin/chunk-e0bckx12.js +2 -0
  59. package/bin/{chunk-wgvgtttc.js → chunk-e2p4s2pj.js} +3 -3
  60. package/bin/chunk-e8zzg57c.js +2 -0
  61. package/bin/{chunk-npeapp7e.js → chunk-edfaqwaq.js} +2 -2
  62. package/bin/{chunk-6nqqe7w9.js → chunk-ehgrp0f9.js} +1 -1
  63. package/bin/chunk-evs2aaav.js +12 -0
  64. package/bin/{chunk-cp96e9pq.js → chunk-f5bhcjhw.js} +1 -1
  65. package/bin/{chunk-34f64q0q.js → chunk-fb9dedm2.js} +2 -2
  66. package/bin/{chunk-zx1c4vm5.js → chunk-ff0mh9p3.js} +31 -31
  67. package/bin/chunk-fpfby5tz.js +1 -0
  68. package/bin/{chunk-eyjfhdp9.js → chunk-gd3b5akr.js} +2 -2
  69. package/bin/{chunk-3hgrw1m0.js → chunk-gm1fy3hm.js} +5 -5
  70. package/bin/{chunk-ezjxx44x.js → chunk-gqkjx7rz.js} +3 -3
  71. package/bin/{chunk-1y6h4vge.js → chunk-h7f5370s.js} +1 -1
  72. package/bin/chunk-hcyhsn8e.js +2 -0
  73. package/bin/{chunk-erfkd3z9.js → chunk-jxm0gzmf.js} +2 -2
  74. package/bin/{chunk-09mpcg9x.js → chunk-k3ggy3xk.js} +2 -2
  75. package/bin/{chunk-0a298n62.js → chunk-k9vjs21p.js} +2 -2
  76. package/bin/chunk-ka40gv72.js +1 -0
  77. package/bin/chunk-km70p970.js +2 -0
  78. package/bin/{chunk-vnmggrd6.js → chunk-m6v8rb39.js} +8 -8
  79. package/bin/{chunk-bbxwyhz3.js → chunk-m8spagwp.js} +3 -3
  80. package/bin/{chunk-addssm8d.js → chunk-mfh7mg5b.js} +1 -1
  81. package/bin/chunk-n0cn0218.js +2 -0
  82. package/bin/chunk-n54ftsdx.js +2 -0
  83. package/bin/{chunk-v0yevesp.js → chunk-n7cvj15k.js} +5 -5
  84. package/bin/chunk-na5fh7er.js +2 -0
  85. package/bin/chunk-neazdbxy.js +1 -0
  86. package/bin/chunk-nk24qw3m.js +1 -0
  87. package/bin/{chunk-7mawxsk3.js → chunk-nsbbseff.js} +2 -2
  88. package/bin/chunk-nseef85h.js +1 -0
  89. package/bin/chunk-p35ztj2z.js +3 -0
  90. package/bin/chunk-pcjc9ygv.js +2 -0
  91. package/bin/{chunk-brgns7hv.js → chunk-pemmtd8q.js} +1 -1
  92. package/bin/{chunk-7jz3cmq6.js → chunk-pzrqnnpg.js} +1 -1
  93. package/bin/{chunk-a74g6h8a.js → chunk-q43m934j.js} +2 -2
  94. package/bin/{chunk-6f3zhq64.js → chunk-q57m34h0.js} +3 -3
  95. package/bin/chunk-q5k72jz9.js +3 -0
  96. package/bin/chunk-q9fsxakd.js +2 -0
  97. package/bin/chunk-qadpe0ct.js +2 -0
  98. package/bin/chunk-qeypjv4f.css +1 -0
  99. package/bin/chunk-qw92z3wf.js +2 -0
  100. package/bin/chunk-r0byfq1t.js +1 -0
  101. package/bin/chunk-r0q88qw3.js +2 -0
  102. package/bin/chunk-rjhczkh3.js +2 -0
  103. package/bin/{chunk-19zbh4fr.js → chunk-s0wxbybf.js} +1 -1
  104. package/bin/{chunk-d55138xx.js → chunk-s4hkcw24.js} +2 -2
  105. package/bin/chunk-szta50g1.js +1 -0
  106. package/bin/chunk-t6cb99gp.js +2 -0
  107. package/bin/chunk-tcr080b9.js +1 -0
  108. package/bin/{chunk-s6pk2zyg.js → chunk-v4nqx084.js} +5 -5
  109. package/bin/{chunk-gyv3yrhj.js → chunk-v7jzc3ye.js} +1 -1
  110. package/bin/{chunk-hsyfrzdd.js → chunk-vbe8wred.js} +1 -1
  111. package/bin/{chunk-sz5zawfw.js → chunk-vf9s8b5t.js} +2 -2
  112. package/bin/{chunk-e55sgg8t.js → chunk-vk3eqr65.js} +1 -1
  113. package/bin/{chunk-vv0m0m2f.js → chunk-vm9bbk97.js} +4 -4
  114. package/bin/{chunk-1e1q1hyg.js → chunk-w4gqg27w.js} +2 -2
  115. package/bin/{chunk-z0de127n.js → chunk-w6ym7tsd.js} +4 -4
  116. package/bin/{chunk-3vpz5nat.js → chunk-ways29d1.js} +1 -1
  117. package/bin/chunk-wesg7tg9.js +1 -0
  118. package/bin/chunk-wmrrapwv.js +2 -0
  119. package/bin/chunk-wnwsjgj8.js +2 -0
  120. package/bin/{chunk-zkvezz89.js → chunk-wrb4xq9v.js} +1 -1
  121. package/bin/{chunk-7kah3zb5.js → chunk-wzrzc07t.js} +2 -2
  122. package/bin/chunk-xd1axsdv.js +2 -0
  123. package/bin/{chunk-k7vbk8v4.js → chunk-xk0jmx4s.js} +2 -2
  124. package/bin/{chunk-jc7dycy6.js → chunk-y545vfn0.js} +1 -1
  125. package/bin/{chunk-1ja2zw4w.js → chunk-y6h885fs.js} +1 -1
  126. package/bin/{chunk-0rgbxp24.js → chunk-yncmfr39.js} +2 -2
  127. package/bin/{chunk-7546ptwg.js → chunk-yxnz4ypt.js} +8 -8
  128. package/bin/chunk-zc1asygg.js +2 -0
  129. package/bin/{chunk-hg3rkp41.js → chunk-zc7wzcvh.js} +7 -7
  130. package/bin/chunk-zdvhh8mk.js +2 -0
  131. package/bin/{chunk-femnbfkj.js → chunk-zg0b902x.js} +2 -2
  132. package/bin/{chunk-ddmf9gqv.js → chunk-zhq7a7hs.js} +2 -2
  133. package/bin/{chunk-dygj751y.js → chunk-zmnvskn7.js} +11 -11
  134. package/bin/shumai-app.html +1 -1
  135. package/bin/shumai-app.js +470 -389
  136. package/package.json +7 -7
  137. package/prisma/migrations/20261102032402_add_archive_storage/migration.sql +25 -0
  138. package/prisma/schema.prisma +12 -6
  139. package/bin/chunk-02b5bcmc.js +0 -1
  140. package/bin/chunk-1tar0x8s.js +0 -7
  141. package/bin/chunk-20w1w9x7.js +0 -2
  142. package/bin/chunk-2qgagdb7.js +0 -1
  143. package/bin/chunk-2t6g3pny.js +0 -3
  144. package/bin/chunk-50pfmxt1.js +0 -2
  145. package/bin/chunk-5ngftxjb.js +0 -218
  146. package/bin/chunk-6t525bmg.js +0 -1
  147. package/bin/chunk-88jg9dq5.js +0 -2
  148. package/bin/chunk-8qdtvfx3.css +0 -1
  149. package/bin/chunk-8ww98y1m.js +0 -2
  150. package/bin/chunk-9vxmgvc8.js +0 -2
  151. package/bin/chunk-ajq9sxg0.js +0 -129
  152. package/bin/chunk-amp9h878.js +0 -2
  153. package/bin/chunk-awshe30f.js +0 -1
  154. package/bin/chunk-b3t7gbhm.js +0 -2
  155. package/bin/chunk-c02727j9.js +0 -2
  156. package/bin/chunk-c1wvs81k.js +0 -2
  157. package/bin/chunk-c8frmqsk.js +0 -2
  158. package/bin/chunk-cagzye3j.js +0 -2
  159. package/bin/chunk-djb65frk.js +0 -1
  160. package/bin/chunk-dx9f5wab.js +0 -1
  161. package/bin/chunk-ex3174e3.js +0 -2
  162. package/bin/chunk-f4xnx4n6.js +0 -1
  163. package/bin/chunk-fakph5jp.js +0 -1
  164. package/bin/chunk-ffjdkdcv.js +0 -2
  165. package/bin/chunk-gd016e9p.js +0 -2
  166. package/bin/chunk-h3atwgx2.js +0 -1
  167. package/bin/chunk-h7xny3de.js +0 -2
  168. package/bin/chunk-hpzk9k55.js +0 -1
  169. package/bin/chunk-hvyy8vct.js +0 -3
  170. package/bin/chunk-j2s311yc.js +0 -3
  171. package/bin/chunk-j6x53e33.js +0 -1
  172. package/bin/chunk-jacanzp7.js +0 -1
  173. package/bin/chunk-pdw77q09.js +0 -2
  174. package/bin/chunk-ptcz4ed3.js +0 -2
  175. package/bin/chunk-q1fzgqsv.js +0 -2
  176. package/bin/chunk-q4ny4hpt.js +0 -2
  177. package/bin/chunk-q8ysc5ex.js +0 -1
  178. package/bin/chunk-qm50g4n5.js +0 -10
  179. package/bin/chunk-s1j4v33x.js +0 -2
  180. package/bin/chunk-t68y25gf.js +0 -1
  181. package/bin/chunk-thpw6tcj.js +0 -2
  182. package/bin/chunk-vj4gamdn.js +0 -2
  183. package/bin/chunk-xy9qpn6b.js +0 -1
  184. package/bin/chunk-y5dv67mg.js +0 -2
  185. package/bin/chunk-z8t6e0ee.js +0 -1
  186. package/bin/chunk-zfg4yy3c.js +0 -2
  187. package/bin/chunk-zrrnvdxq.js +0 -3
  188. package/bin/chunk-zzqse5qc.js +0 -2
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Pr,ra,ad,e,I,E,N,J,A,l,D,k,v,y}from"./chunk-5ddg5ezb.js";function hl(t){return{ok:!0,value:t}}function Fs(t){return{ok:!1,error:t}}async function V(t){let n=await t;if(!n.ok)throw n.error;return n.value}class C extends Error{rawValue;rawMessage;static[Symbol.hasInstance](t){if(!(t instanceof Error))return!1;if(!("rawValue"in t))return!1;if(!("rawMessage"in t))return!1;if(!("pretty"in t))return!1;if(typeof t.pretty!=="function")return!1;return!0}constructor(t,n,o){super(`${t}: ${n}`);this.name="SDKValidationError",this.cause=n,this.rawValue=o,this.rawMessage=t}pretty(){if(this.cause instanceof ra)return`${this.rawMessage}
3
- ${im(this.cause)}`;else return this.toString()}}function im(t){return ad(t)}function b(t,n){let o={};if(!Object.keys(n).length)return o=t,o;for(let[i,r]of Object.entries(t)){let a=n[i];if(a===null)continue;o[a??i]=r}return o}function O(t){let n={};for(let[o,i]of Object.entries(t))if(typeof i<"u")n[o]=i;return n}function P(t,n,o){try{return hl(n(t))}catch(i){return Fs(new C(o,i,t))}}function _(t){return d++,t}var d=0,T=0;function h(){T++;let t=d;return{end:(n)=>{let o=d-t;if(d=t+(n??o),--T===0)d=0;return o}}}function me(t){let n=Object.values(t);return D([...n.map((o)=>v(o)),e().transform((o)=>_(o))])}function oc(t){let n=Object.values(t).filter((o)=>typeof o==="number");return D([...n.map((o)=>v(o)),I().transform((o)=>_(o))])}function Lt(t){return e()}function Lg(t){return I()}var j=Symbol("UNKNOWN");function w(t){return typeof t==="object"&&t!==null&&j in t}function xt(t,n,o={}){let{unknownValue:i="UNKNOWN",outputPropertyName:r}=o;return J().transform((a)=>{let s=Object.defineProperties({raw:a,[r??t]:i,isUnknown:!0},{[j]:{value:!0,enumerable:!1,configurable:!1}});if(!(typeof a==="object"&&a!==null))return s;let m=a[t];if(typeof m!=="string")return s;if(!(m in n))return s;let g=n[m];if(!g)return s;let p=h(),f=g.safeParse(a);if(!f.success)return p.end(0),s;if(p.end(),r)f.data[r]=m;return f.data})}var L=/^\d{4}-\d{2}-\d{2}$/;class x{serialized;static today(){return new x(new Date)}constructor(t){if(typeof t==="string"&&!L.test(t))throw RangeError("RFCDate: date strings must be in the format YYYY-MM-DD: "+t);let n=new Date(t);if(isNaN(+n))throw RangeError("RFCDate: invalid date provided: "+t);if(this.serialized=n.toISOString().slice(0,10),!L.test(this.serialized))throw TypeError(`RFCDate: failed to build valid date with given value: ${t} serialized to ${this.serialized}`)}toJSON(){return this.toString()}toString(){return this.serialized}}function H(t){return J().transform((n,o)=>{let i=[],r=t.map(()=>[]),a=h();for(let[c,m]of t.entries()){let g=h(),p=m.safeParse(n),f=g.end(),re=0;if(p.success){i.push({data:p.data,inexactCount:f,zeroDefaultCount:0,fieldCount:-1});continue}r[c].push(...p.error.issues)}if(i.length===0)return a.end(0),o.addIssue({input:n,code:"invalid_union",errors:r}),Pr;let s=i[0];for(let c of i){if(i.length>1)c.fieldCount=te(c.data);s=ee(c,s)}return a.end(s.inexactCount),s.data})}function ee(t,n){let o=t.inexactCount===0,i=n.inexactCount===0;if(o!==i)return o?t:n;let r=t.fieldCount-t.zeroDefaultCount,a=n.fieldCount-n.zeroDefaultCount;if(r!==a)return r>a?t:n;return t.inexactCount<n.inexactCount?t:n}function te(t){let n=0,o=[t],i=0;while(i<o.length){let r=o[i++];if(r===void 0||w(r))continue;let a=typeof r;if(r===null||a==="number"||a==="string"||a==="boolean"||a==="bigint"||r instanceof Date||r instanceof x){n++;continue}if(Array.isArray(r)){o.push(...r);continue}if(a==="object")o.push(...Object.values(r))}return n}var M=l({type:v("input_audio"),input_audio:e()}).transform((t)=>b(t,{input_audio:"inputAudio"})),K=l({type:v("input_audio"),inputAudio:e()}).transform((t)=>b(t,{inputAudio:"input_audio"}));var ka=l({type:v("document_url").default("document_url"),document_url:e(),document_name:y(e()).optional()}).transform((t)=>b(t,{document_url:"documentUrl",document_name:"documentName"})),Ui=l({type:v("document_url").default("document_url"),documentUrl:e(),documentName:y(e()).optional()}).transform((t)=>b(t,{documentUrl:"document_url",documentName:"document_name"}));var Y=l({type:v("file").default("file"),file_id:e()}).transform((t)=>b(t,{file_id:"fileId"})),Ru=l({type:v("file").default("file"),fileId:e()}).transform((t)=>b(t,{fileId:"file_id"}));var B={Low:"low",Auto:"auto",High:"high"},W=me(B),Z=Lt(B);var F=l({url:e(),detail:y(W).optional()}),U=l({url:e(),detail:y(Z).optional()});var Ie=H([F,e()]),we=H([U,e()]);var Ra=l({type:v("image_url").default("image_url"),image_url:H([F,e()])}).transform((t)=>b(t,{image_url:"imageUrl"})),zi=l({type:v("image_url").default("image_url"),imageUrl:H([U,e()])}).transform((t)=>b(t,{imageUrl:"image_url"}));var Ae=H([I(),e()]),ve=H([I(),e()]);var z=l({type:v("reference").default("reference"),reference_ids:A(H([I(),e()]))}).transform((t)=>b(t,{reference_ids:"referenceIds"})),S=l({type:v("reference").default("reference"),referenceIds:A(H([I(),e()]))}).transform((t)=>b(t,{referenceIds:"reference_ids"}));var Ls=l({type:v("text").default("text"),text:e()}),Zs=l({type:v("text").default("text"),text:e()});var q={WebSearch:"web_search",WebSearchPremium:"web_search_premium",CodeInterpreter:"code_interpreter",ImageGeneration:"image_generation",DocumentLibrary:"document_library"},Hn=me(q),ji=Lt(q);var Ve=H([Hn,e()]),We=H([ji,e()]);var gl=l({type:v("tool_reference").default("tool_reference"),tool:H([Hn,e()]),title:e(),url:y(e()).optional(),favicon:y(e()).optional(),description:y(e()).optional()}),Mu=l({type:v("tool_reference").default("tool_reference"),tool:H([ji,e()]),title:e(),url:y(e()).optional(),favicon:y(e()).optional(),description:y(e()).optional()});var Xe=H([gl,Ls,z]),et=H([Mu,Zs,S]);var Ma=l({type:v("thinking").default("thinking"),thinking:A(H([gl,Ls,z])),signature:y(e()).optional(),closed:E().optional()}),Oa=l({type:v("thinking").default("thinking"),thinking:A(H([Mu,Zs,S])),signature:y(e()).optional(),closed:E().optional()});var sc=xt("type",{image_url:Ra.and(l({type:v("image_url")})),document_url:ka.and(l({type:v("document_url")})),text:Ls.and(l({type:v("text")})),reference:z.and(l({type:v("reference")})),file:Y.and(l({type:v("file")})),thinking:Ma.and(l({type:v("thinking")})),input_audio:M}),qi=D([zi.and(l({type:v("image_url")})),Ui.and(l({type:v("document_url")})),Zs.and(l({type:v("text")})),S.and(l({type:v("reference")})),Ru.and(l({type:v("file")})),Oa.and(l({type:v("thinking")})),K]);var pt=H([k(e(),N()),e()]),ft=H([k(e(),N()),e()]);var G=l({name:e(),arguments:H([k(e(),N()),e()])}),Q=l({name:e(),arguments:H([k(e(),N()),e()])});var Jd=l({id:e().default("null"),type:e().optional(),function:G,index:I().default(0)}),Zg=l({id:e().default("null"),type:e().optional(),function:Q,index:I().default(0)});var kt=H([e(),A(sc)]);var Yd=l({role:y(e()).optional(),content:y(H([e(),A(sc)])).optional(),tool_calls:y(A(Jd)).optional(),tool_call_id:y(e()).optional(),index:y(I()).optional(),metadata:y(k(e(),N())).optional()}).transform((t)=>b(t,{tool_calls:"toolCalls",tool_call_id:"toolCallId"}));var ys=l({prompt_tokens:I().default(0),completion_tokens:I().default(0),total_tokens:I().default(0),prompt_audio_seconds:y(I()).optional()}).catchall(N()).transform((t)=>b(t,{prompt_tokens:"promptTokens",completion_tokens:"completionTokens",total_tokens:"totalTokens",prompt_audio_seconds:"promptAudioSeconds"})),Ou=l({promptTokens:I().default(0),completionTokens:I().default(0),totalTokens:I().default(0),promptAudioSeconds:y(I()).optional()}).catchall(N()).transform((t)=>({...b(t,{promptTokens:"prompt_tokens",completionTokens:"completion_tokens",totalTokens:"total_tokens",promptAudioSeconds:"prompt_audio_seconds"})}));var ne={Stop:"stop",Length:"length",Error:"error",ToolCalls:"tool_calls"},oe=me(ne),X=l({index:I(),delta:Yd,finish_reason:y(oe)}).transform((t)=>b(t,{finish_reason:"finishReason"}));var am=l({id:e(),object:e().optional(),created:I().optional(),model:e(),usage:ys.optional(),choices:A(X)});function Bg(t){return P(t,(n)=>am.parse(JSON.parse(n)),"Failed to parse 'CompletionChunk' from JSON")}
4
- export{im,hl,Fs,V,P,b,O,me,oc,Lt,Lg,xt,H,ka,Ui,Ru,Ra,zi,Ls,Zs,Hn,ji,gl,Mu,Ma,Oa,sc,qi,Jd,Zg,Yd,ys,Ou,am,Bg};
2
+ import{Fr,ca,wd,e,I,E,F,J,A,l,D,k,v,y}from"./chunk-4b2x2qba.js";function Tl(t){return{ok:!0,value:t}}function qs(t){return{ok:!1,error:t}}async function K(t){let n=await t;if(!n.ok)throw n.error;return n.value}class C extends Error{rawValue;rawMessage;static[Symbol.hasInstance](t){if(!(t instanceof Error))return!1;if(!("rawValue"in t))return!1;if(!("rawMessage"in t))return!1;if(!("pretty"in t))return!1;if(typeof t.pretty!=="function")return!1;return!0}constructor(t,n,o){super(`${t}: ${n}`);this.name="SDKValidationError",this.cause=n,this.rawValue=o,this.rawMessage=t}pretty(){if(this.cause instanceof ca)return`${this.rawMessage}
3
+ ${Rm(this.cause)}`;else return this.toString()}}function Rm(t){return wd(t)}function b(t,n){let o={};if(!Object.keys(n).length)return o=t,o;for(let[i,r]of Object.entries(t)){let a=n[i];if(a===null)continue;o[a??i]=r}return o}function O(t){let n={};for(let[o,i]of Object.entries(t))if(typeof i<"u")n[o]=i;return n}function P(t,n,o){try{return Tl(n(t))}catch(i){return qs(new C(o,i,t))}}function N(t){return d++,t}var d=0,T=0;function h(){T++;let t=d;return{end:(n)=>{let o=d-t;if(d=t+(n??o),--T===0)d=0;return o}}}function he(t){let n=Object.values(t);return D([...n.map((o)=>v(o)),e().transform((o)=>N(o))])}function _c(t){let n=Object.values(t).filter((o)=>typeof o==="number");return D([...n.map((o)=>v(o)),I().transform((o)=>N(o))])}function Bt(t){return e()}function iA(t){return I()}var j=Symbol("UNKNOWN");function w(t){return typeof t==="object"&&t!==null&&j in t}function It(t,n,o={}){let{unknownValue:i="UNKNOWN",outputPropertyName:r}=o;return J().transform((a)=>{let s=Object.defineProperties({raw:a,[r??t]:i,isUnknown:!0},{[j]:{value:!0,enumerable:!1,configurable:!1}});if(!(typeof a==="object"&&a!==null))return s;let m=a[t];if(typeof m!=="string")return s;if(!(m in n))return s;let g=n[m];if(!g)return s;let p=h(),f=g.safeParse(a);if(!f.success)return p.end(0),s;if(p.end(),r)f.data[r]=m;return f.data})}var L=/^\d{4}-\d{2}-\d{2}$/;class x{serialized;static today(){return new x(new Date)}constructor(t){if(typeof t==="string"&&!L.test(t))throw RangeError("RFCDate: date strings must be in the format YYYY-MM-DD: "+t);let n=new Date(t);if(isNaN(+n))throw RangeError("RFCDate: invalid date provided: "+t);if(this.serialized=n.toISOString().slice(0,10),!L.test(this.serialized))throw TypeError(`RFCDate: failed to build valid date with given value: ${t} serialized to ${this.serialized}`)}toJSON(){return this.toString()}toString(){return this.serialized}}function H(t){return J().transform((n,o)=>{let i=[],r=t.map(()=>[]),a=h();for(let[c,m]of t.entries()){let g=h(),p=m.safeParse(n),f=g.end(),re=0;if(p.success){i.push({data:p.data,inexactCount:f,zeroDefaultCount:0,fieldCount:-1});continue}r[c].push(...p.error.issues)}if(i.length===0)return a.end(0),o.addIssue({input:n,code:"invalid_union",errors:r}),Fr;let s=i[0];for(let c of i){if(i.length>1)c.fieldCount=te(c.data);s=ee(c,s)}return a.end(s.inexactCount),s.data})}function ee(t,n){let o=t.inexactCount===0,i=n.inexactCount===0;if(o!==i)return o?t:n;let r=t.fieldCount-t.zeroDefaultCount,a=n.fieldCount-n.zeroDefaultCount;if(r!==a)return r>a?t:n;return t.inexactCount<n.inexactCount?t:n}function te(t){let n=0,o=[t],i=0;while(i<o.length){let r=o[i++];if(r===void 0||w(r))continue;let a=typeof r;if(r===null||a==="number"||a==="string"||a==="boolean"||a==="bigint"||r instanceof Date||r instanceof x){n++;continue}if(Array.isArray(r)){o.push(...r);continue}if(a==="object")o.push(...Object.values(r))}return n}var M=l({type:v("input_audio"),input_audio:e()}).transform((t)=>b(t,{input_audio:"inputAudio"})),Y=l({type:v("input_audio"),inputAudio:e()}).transform((t)=>b(t,{inputAudio:"input_audio"}));var Ua=l({type:v("document_url").default("document_url"),document_url:e(),document_name:y(e()).optional()}).transform((t)=>b(t,{document_url:"documentUrl",document_name:"documentName"})),Gi=l({type:v("document_url").default("document_url"),documentUrl:e(),documentName:y(e()).optional()}).transform((t)=>b(t,{documentUrl:"document_url",documentName:"document_name"}));var B=l({type:v("file").default("file"),file_id:e()}).transform((t)=>b(t,{file_id:"fileId"})),Hu=l({type:v("file").default("file"),fileId:e()}).transform((t)=>b(t,{fileId:"file_id"}));var V={Low:"low",Auto:"auto",High:"high"},W=he(V),Z=Bt(V);var R=l({url:e(),detail:y(W).optional()}),U=l({url:e(),detail:y(Z).optional()});var Ie=H([R,e()]),we=H([U,e()]);var za=l({type:v("image_url").default("image_url"),image_url:H([R,e()])}).transform((t)=>b(t,{image_url:"imageUrl"})),Vi=l({type:v("image_url").default("image_url"),imageUrl:H([U,e()])}).transform((t)=>b(t,{imageUrl:"image_url"}));var Ae=H([I(),e()]),ve=H([I(),e()]);var z=l({type:v("reference").default("reference"),reference_ids:A(H([I(),e()]))}).transform((t)=>b(t,{reference_ids:"referenceIds"})),S=l({type:v("reference").default("reference"),referenceIds:A(H([I(),e()]))}).transform((t)=>b(t,{referenceIds:"reference_ids"}));var $s=l({type:v("text").default("text"),text:e()}),Hs=l({type:v("text").default("text"),text:e()});var q={WebSearch:"web_search",WebSearchPremium:"web_search_premium",CodeInterpreter:"code_interpreter",ImageGeneration:"image_generation",DocumentLibrary:"document_library"},Qn=he(q),Ki=Bt(q);var Ve=H([Qn,e()]),We=H([Ki,e()]);var kl=l({type:v("tool_reference").default("tool_reference"),tool:H([Qn,e()]),title:e(),url:y(e()).optional(),favicon:y(e()).optional(),description:y(e()).optional()}),Qu=l({type:v("tool_reference").default("tool_reference"),tool:H([Ki,e()]),title:e(),url:y(e()).optional(),favicon:y(e()).optional(),description:y(e()).optional()});var Xe=H([kl,$s,z]),et=H([Qu,Hs,S]);var ja=l({type:v("thinking").default("thinking"),thinking:A(H([kl,$s,z])),signature:y(e()).optional(),closed:E().optional()}),qa=l({type:v("thinking").default("thinking"),thinking:A(H([Qu,Hs,S])),signature:y(e()).optional(),closed:E().optional()});var yc=It("type",{image_url:za.and(l({type:v("image_url")})),document_url:Ua.and(l({type:v("document_url")})),text:$s.and(l({type:v("text")})),reference:z.and(l({type:v("reference")})),file:B.and(l({type:v("file")})),thinking:ja.and(l({type:v("thinking")})),input_audio:M}),Wi=D([Vi.and(l({type:v("image_url")})),Gi.and(l({type:v("document_url")})),Hs.and(l({type:v("text")})),S.and(l({type:v("reference")})),Hu.and(l({type:v("file")})),qa.and(l({type:v("thinking")})),Y]);var pt=H([k(e(),F()),e()]),ft=H([k(e(),F()),e()]);var G=l({name:e(),arguments:H([k(e(),F()),e()])}),Q=l({name:e(),arguments:H([k(e(),F()),e()])});var _f=l({id:e().default("null"),type:e().optional(),function:G,index:I().default(0)}),aA=l({id:e().default("null"),type:e().optional(),function:Q,index:I().default(0)});var Ct=H([e(),A(yc)]);var yf=l({role:y(e()).optional(),content:y(H([e(),A(yc)])).optional(),tool_calls:y(A(_f)).optional(),tool_call_id:y(e()).optional(),index:y(I()).optional(),metadata:y(k(e(),F())).optional()}).transform((t)=>b(t,{tool_calls:"toolCalls",tool_call_id:"toolCallId"}));var Is=l({prompt_tokens:I().default(0),completion_tokens:I().default(0),total_tokens:I().default(0),prompt_audio_seconds:y(I()).optional()}).catchall(F()).transform((t)=>b(t,{prompt_tokens:"promptTokens",completion_tokens:"completionTokens",total_tokens:"totalTokens",prompt_audio_seconds:"promptAudioSeconds"})),Gu=l({promptTokens:I().default(0),completionTokens:I().default(0),totalTokens:I().default(0),promptAudioSeconds:y(I()).optional()}).catchall(F()).transform((t)=>({...b(t,{promptTokens:"prompt_tokens",completionTokens:"completion_tokens",totalTokens:"total_tokens",promptAudioSeconds:"prompt_audio_seconds"})}));var ne={Stop:"stop",Length:"length",Error:"error",ToolCalls:"tool_calls"},oe=he(ne),X=l({index:I(),delta:yf,finish_reason:y(oe)}).transform((t)=>b(t,{finish_reason:"finishReason"}));var Mm=l({id:e(),object:e().optional(),created:I().optional(),model:e(),usage:Is.optional(),choices:A(X)});function lA(t){return P(t,(n)=>Mm.parse(JSON.parse(n)),"Failed to parse 'CompletionChunk' from JSON")}
4
+ export{Rm,Tl,qs,K,P,b,O,he,_c,Bt,iA,It,H,Ua,Gi,Hu,za,Vi,$s,Hs,Qn,Ki,kl,Qu,ja,qa,yc,Wi,_f,aA,yf,Is,Gu,Mm,lA};
@@ -1 +1 @@
1
- import{S,Q,w,L,W,a,g,Tt,We,Je,R,K,Ja,yo,No,$e,He,Qe,Tb,Lw,th,vd,aT,Yn,Pt,Vt,$r,lr,qt,Mg}from"./chunk-5ngftxjb.js";import{Yr}from"./chunk-d55138xx.js";import{Un,zn,jn,Tr,vt,ut}from"./chunk-c02727j9.js";import{Ar}from"./chunk-b3t7gbhm.js";L();var I=(t)=>{if(!t)return"??";return t.split(" ").map((o)=>o[0]).slice(0,2).join("").toUpperCase()};function k(){let{projectId:t}=T.useParams(),{teamId:o,ensureTeamIdForProject:l}=Pt(),b=We();S(()=>{l(t)},[t,l]);let{data:s}=Ar(Mg(t)),n=s?.rootFolder,[x,v]=w(240),{fileListLeftSidebarCollapsed:d,setFileListLeftSidebarCollapsed:N}=lr(),{data:m,isLoading:h,fetchNextPage:c,hasNextPage:f,isFetchingNextPage:i}=Tt({queryKey:["collections",t],queryFn:async({pageParam:e})=>{let r=await R.api.projects[":projectId"].collections.$get({param:{projectId:t},query:{first:"20",after:e}});if(!r.ok)throw Error("Failed to fetch collections");return await r.json()},initialPageParam:"",getNextPageParam:(e)=>e.pageInfo?.cursor||void 0,enabled:!!t}),{ref:y,inView:p}=Vt();S(()=>{if(p&&f&&!i)c()},[p,f,i,c]);let u=Q(()=>m?.pages.flatMap((e)=>e.data)||[],[m]);if(!o||!n||!s)return a(qt,{});return a("div",{className:"flex flex-1 flex-col bg-background min-h-0",children:g("div",{className:"flex flex-1 overflow-hidden relative",children:[!d&&a("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:()=>N(!0)}),!d&&g(W,{children:[a("div",{className:"bg-background",style:{width:x},children:a($r,{teamId:o,projectId:t,projectName:s.name??"",rootFolderId:n})}),a(Yr,{onResize:(e)=>{v((r)=>Math.max(180,Math.min(400,r+e)))},className:"hidden md:block"})]}),g("div",{className:"flex-1 flex flex-col min-h-0 bg-card overflow-hidden",children:[a("header",{className:"h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10",children:g("div",{className:"flex items-center gap-2",children:[a(Ja,{className:"h-5 w-5 text-primary"}),a("h1",{className:"font-bold text-lg text-foreground",children:Tb()})]})}),a("div",{className:"flex-1 overflow-y-auto p-6",children:h?a("div",{className:"flex justify-center items-center h-64",children:a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):u.length===0?g("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground gap-3",children:[a(No,{className:"h-10 w-10 text-muted-foreground/50"}),a("p",{children:aT()})]}):g("div",{className:"border border-border rounded-xl bg-background overflow-hidden shadow-xs",children:[g(Un,{children:[a(zn,{children:g(Tr,{className:"hover:bg-transparent bg-muted/20",children:[a(vt,{className:"font-semibold px-4 py-3",children:Lw()}),a(vt,{className:"font-semibold px-4 py-3",children:vd()}),a(vt,{className:"font-semibold px-4 py-3 w-[200px]",children:th()})]})}),a(jn,{children:u.map((e)=>g(Tr,{className:"hover:bg-muted/10 transition-colors cursor-pointer",onClick:()=>b({to:"/projects/$projectId/collections/$collectionId",params:{projectId:t,collectionId:e.id}}),children:[a(ut,{className:"font-medium px-4 py-3.5",children:g("div",{className:"flex items-center gap-2",children:[a(Ja,{className:"h-4 w-4 text-primary shrink-0"}),a("span",{className:"text-foreground font-semibold hover:underline",children:e.name})]})}),a(ut,{className:"px-4 py-3.5",children:g("div",{className:"flex items-center gap-2",children:[g($e,{className:"h-6 w-6",children:[e.creator?.image&&a(He,{src:e.creator.image,alt:e.creator.name,className:"object-cover"}),a(Qe,{className:"text-[10px]",children:I(e.creator?.name)})]}),a("span",{className:"text-sm font-medium text-foreground truncate max-w-[200px]",children:e.creator?.name||Yn()})]})}),a(ut,{className:"px-4 py-3.5 text-muted-foreground text-sm",children:g("div",{className:"flex items-center gap-2",children:[a(yo,{className:"h-3.5 w-3.5 text-muted-foreground/70"}),a("span",{children:new Date(e.createdAt).toLocaleDateString()})]})})]},e.id))})]}),a("div",{ref:y,className:"h-10 w-full flex items-center justify-center",children:i&&a(K,{className:"h-6 w-6 animate-spin text-primary"})})]})})]})]})})}var T=Je("/projects/$projectId/collections/")({component:k});export{T as Route};
1
+ import{S,Q,w,L,W,a,g,Rt,We,Je,R,V,ll,xo,Bo,$e,He,Qe,ew,OE,xh,Ld,k1,to,Ft,Vt,Qr,cr,$t,eA}from"./chunk-akafypge.js";import{en}from"./chunk-s4hkcw24.js";import{zn,jn,qn,Rr,bt,yt}from"./chunk-bywk8mbc.js";import{yr}from"./chunk-e8zzg57c.js";L();var I=(t)=>{if(!t)return"??";return t.split(" ").map((o)=>o[0]).slice(0,2).join("").toUpperCase()};function k(){let{projectId:t}=T.useParams(),{teamId:o,ensureTeamIdForProject:l}=Ft(),b=We();S(()=>{l(t)},[t,l]);let{data:s}=yr(eA(t)),n=s?.rootFolder,[x,v]=w(240),{fileListLeftSidebarCollapsed:d,setFileListLeftSidebarCollapsed:N}=cr(),{data:m,isLoading:h,fetchNextPage:c,hasNextPage:f,isFetchingNextPage:i}=Rt({queryKey:["collections",t],queryFn:async({pageParam:e})=>{let r=await R.api.projects[":projectId"].collections.$get({param:{projectId:t},query:{first:"20",after:e}});if(!r.ok)throw Error("Failed to fetch collections");return await r.json()},initialPageParam:"",getNextPageParam:(e)=>e.pageInfo?.cursor||void 0,enabled:!!t}),{ref:y,inView:p}=Vt();S(()=>{if(p&&f&&!i)c()},[p,f,i,c]);let u=Q(()=>m?.pages.flatMap((e)=>e.data)||[],[m]);if(!o||!n||!s)return a($t,{});return a("div",{className:"flex flex-1 flex-col bg-background min-h-0",children:g("div",{className:"flex flex-1 overflow-hidden relative",children:[!d&&a("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:()=>N(!0)}),!d&&g(W,{children:[a("div",{className:"bg-background",style:{width:x},children:a(Qr,{teamId:o,projectId:t,projectName:s.name??"",rootFolderId:n})}),a(en,{onResize:(e)=>{v((r)=>Math.max(180,Math.min(400,r+e)))},className:"hidden md:block"})]}),g("div",{className:"flex-1 flex flex-col min-h-0 bg-card overflow-hidden",children:[a("header",{className:"h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10",children:g("div",{className:"flex items-center gap-2",children:[a(ll,{className:"h-5 w-5 text-primary"}),a("h1",{className:"font-bold text-lg text-foreground",children:ew()})]})}),a("div",{className:"flex-1 overflow-y-auto p-6",children:h?a("div",{className:"flex justify-center items-center h-64",children:a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):u.length===0?g("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground gap-3",children:[a(Bo,{className:"h-10 w-10 text-muted-foreground/50"}),a("p",{children:k1()})]}):g("div",{className:"border border-border rounded-xl bg-background overflow-hidden shadow-xs",children:[g(zn,{children:[a(jn,{children:g(Rr,{className:"hover:bg-transparent bg-muted/20",children:[a(bt,{className:"font-semibold px-4 py-3",children:OE()}),a(bt,{className:"font-semibold px-4 py-3",children:Ld()}),a(bt,{className:"font-semibold px-4 py-3 w-[200px]",children:xh()})]})}),a(qn,{children:u.map((e)=>g(Rr,{className:"hover:bg-muted/10 transition-colors cursor-pointer",onClick:()=>b({to:"/projects/$projectId/collections/$collectionId",params:{projectId:t,collectionId:e.id}}),children:[a(yt,{className:"font-medium px-4 py-3.5",children:g("div",{className:"flex items-center gap-2",children:[a(ll,{className:"h-4 w-4 text-primary shrink-0"}),a("span",{className:"text-foreground font-semibold hover:underline",children:e.name})]})}),a(yt,{className:"px-4 py-3.5",children:g("div",{className:"flex items-center gap-2",children:[g($e,{className:"h-6 w-6",children:[e.creator?.image&&a(He,{src:e.creator.image,alt:e.creator.name,className:"object-cover"}),a(Qe,{className:"text-[10px]",children:I(e.creator?.name)})]}),a("span",{className:"text-sm font-medium text-foreground truncate max-w-[200px]",children:e.creator?.name||to()})]})}),a(yt,{className:"px-4 py-3.5 text-muted-foreground text-sm",children:g("div",{className:"flex items-center gap-2",children:[a(xo,{className:"h-3.5 w-3.5 text-muted-foreground/70"}),a("span",{children:new Date(e.createdAt).toLocaleDateString()})]})})]},e.id))})]}),a("div",{ref:y,className:"h-10 w-full flex items-center justify-center",children:i&&a(V,{className:"h-6 w-6 animate-spin text-primary"})})]})})]})]})})}var T=Je("/projects/$projectId/collections/")({component:k});export{T as Route};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{wc}from"./chunk-yncmfr39.js";export default wc();
@@ -0,0 +1,2 @@
1
+ import{j}from"./chunk-akafypge.js";var e=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Ba=j("code",e);
2
+ export{Ba};
@@ -3,16 +3,16 @@ function b(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable
3
3
  `)}}q=new WeakMap,H=new WeakMap;je.NEWLINE_CHARS=new Set([`
4
4
  `,"\r"]);je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Gn(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 Ys(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var gr={off:0,error:200,warn:300,info:400,debug:500},rs=(e,t,r)=>{if(!e)return;if(vs(gr,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gr))}`);return};function Pt(){}function _r(e,t,r){if(!t||gr[e]>gr[r])return Pt;else return t[e].bind(t)}var zn={error:Pt,warn:Pt,info:Pt,debug:Pt},Zs=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return zn;let s=Zs.get(t);if(s&&s[0]===r)return s[1];let n={error:_r("error",t,r),warn:_r("warn",t,r),info:_r("info",t,r),debug:_r("debug",t,r)};return Zs.set(t,[r,n]),n}var ne=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var St;class J{constructor(e,t,r){this.iterator=e,St.set(this,void 0),this.controller=t,b(this,St,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?v(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Qn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new O(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new O(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(ht(d))return;throw d}finally{if(!f)t.abort()}}return new J(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new je,f=Kr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(ht(f))return;throw f}finally{if(!a)t.abort()}}return new J(o,t,r)}[(St=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new J(()=>s(e),this.controller,i(this,St,"f")),new J(()=>s(t),this.controller,i(this,St,"f"))]}toReadableStream(){let e=this,t;return Vr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ue(JSON.stringify(s)+`
5
5
  `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Qn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new en,s=new je,n=Kr(e.body);for await(let o of Yn(n))for(let a of s.decode(o)){let f=r.decode(a);if(f)yield f}for(let o of s.flush()){let a=r.decode(o);if(a)yield a}}async function*Yn(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?Ue(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Ys(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class en{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
6
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Zn(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function Zn(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function yr(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(v(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return J.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ss(u,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,ne({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ss(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Rt;class Ie extends Promise{constructor(e,t,r=yr){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Rt.set(this,void 0),b(this,Rt,e,"f")}_thenUnwrap(e){return new Ie(i(this,Rt,"f"),this.responsePromise,async(t,r)=>ss(e(await this.parseResponse(t,r),r),r.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(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Rt,"f"),e));return 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)}}Rt=new WeakMap;var br;class wr{constructor(e,t,r,s){br.set(this,void 0),b(this,br,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class xr extends Ie{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await yr(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class oe extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class x extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Xr(this.options.query),after:t}}}}class Y extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Xr(this.options.query),after:e}}}}var is=()=>{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 De(e,t,r){return is(),new File(e,t??"unknown_file",r)}function Et(e){return(typeof e==="object"&&e!==null&&(("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 Ar=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ie=async(e,t)=>{if(!ns(e.body))return e;return{...e,body:await rn(e.body,t)}},V=async(e,t)=>({...e,body:await rn(e.body,t)}),tn=new WeakMap;function to(e){let t=typeof e==="function"?e:e.fetch,r=tn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return tn.set(t,s),s}var rn=async(e,t)=>{if(!await to(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,n])=>os(r,s,n))),r},sn=(e)=>e instanceof Blob&&("name"in e),ro=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ar(e)||sn(e)),ns=(e)=>{if(ro(e))return!0;if(Array.isArray(e))return e.some(ns);if(e&&typeof e==="object"){for(let t in e)if(ns(e[t]))return!0}return!1},os=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,De([await r.blob()],Et(r)));else if(Ar(r))e.append(t,De([await new Response(pr(r)).blob()],Et(r)));else if(sn(r))e.append(t,r,Et(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>os(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>os(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var nn=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",so=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&nn(e),no=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Ir(e,t,r){if(is(),e=await e,so(e)){if(e instanceof File)return e;return De([await e.arrayBuffer()],e.name)}if(no(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),De(await as(n),t,r)}let s=await as(e);if(t||(t=Et(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return De(s,t,r)}async function as(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ar(e))for await(let r of e)t.push(...await as(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${oo(e)}`)}return t}function oo(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function an(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var on=Object.freeze(Object.create(null)),ao=(e=an)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??on)??on)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),R="^".repeat(w.length);return y=w.start+w.length,u+g+R},"");throw new m(`Path parameters result in path with invalid segments:
6
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Zn(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function Zn(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function yr(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(v(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return J.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ss(u,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,ne({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ss(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Rt;class Ie extends Promise{constructor(e,t,r=yr){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Rt.set(this,void 0),b(this,Rt,e,"f")}_thenUnwrap(e){return new Ie(i(this,Rt,"f"),this.responsePromise,async(t,r)=>ss(e(await this.parseResponse(t,r),r),r.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(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Rt,"f"),e));return 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)}}Rt=new WeakMap;var br;class wr{constructor(e,t,r,s){br.set(this,void 0),b(this,br,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class xr extends Ie{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await yr(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class oe extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class x extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Xr(this.options.query),after:t}}}}class Y extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Xr(this.options.query),after:e}}}}var is=()=>{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 De(e,t,r){return is(),new File(e,t??"unknown_file",r)}function Ct(e){return(typeof e==="object"&&e!==null&&(("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 Ar=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ie=async(e,t)=>{if(!ns(e.body))return e;return{...e,body:await rn(e.body,t)}},V=async(e,t)=>({...e,body:await rn(e.body,t)}),tn=new WeakMap;function to(e){let t=typeof e==="function"?e:e.fetch,r=tn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return tn.set(t,s),s}var rn=async(e,t)=>{if(!await to(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,n])=>os(r,s,n))),r},sn=(e)=>e instanceof Blob&&("name"in e),ro=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ar(e)||sn(e)),ns=(e)=>{if(ro(e))return!0;if(Array.isArray(e))return e.some(ns);if(e&&typeof e==="object"){for(let t in e)if(ns(e[t]))return!0}return!1},os=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,De([await r.blob()],Ct(r)));else if(Ar(r))e.append(t,De([await new Response(pr(r)).blob()],Ct(r)));else if(sn(r))e.append(t,r,Ct(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>os(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>os(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var nn=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",so=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&nn(e),no=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Ir(e,t,r){if(is(),e=await e,so(e)){if(e instanceof File)return e;return De([await e.arrayBuffer()],e.name)}if(no(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),De(await as(n),t,r)}let s=await as(e);if(t||(t=Ct(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return De(s,t,r)}async function as(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ar(e))for await(let r of e)t.push(...await as(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${oo(e)}`)}return t}function oo(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function an(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var on=Object.freeze(Object.create(null)),ao=(e=an)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??on)??on)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),R="^".repeat(w.length);return y=w.start+w.length,u+g+R},"");throw new m(`Path parameters result in path with invalid segments:
7
7
  ${o.map((u)=>u.error).join(`
8
8
  `)}
9
9
  ${a}
10
- ${p}`)}return a},l=ao(an);class We extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,x,{query:t,...r})}}function vt(e){return e!==void 0&&"function"in e&&e.function!==void 0}function $t(e){return e?.$brand==="auto-parseable-response-format"}function Pe(e){return e?.$brand==="auto-parseable-tool"}function ln(e,t){if(!t||!ls(t))return{...e,choices:e.choices.map((r)=>(un(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return kt(e,t)}function kt(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new At;if(s.finish_reason==="content_filter")throw new It;return un(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>fo(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?uo(t,s.message.content):null}}});return{...e,choices:r}}function uo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function fo(e,t){let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Pe(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function cn(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return vt(r)&&(Pe(r)||r?.function.strict||!1)}function ls(e){if($t(e.response_format))return!0;return e.tools?.some((t)=>Pe(t)||t.type==="function"&&t.function.strict===!0)??!1}function un(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function fn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var qe=(e)=>e?.role==="assistant",cs=(e)=>e?.role==="tool";var us,Pr,Sr,Ot,Tt,Rr,Ft,ae,Nt,Cr,Er,He,hn;class Se{constructor(){us.add(this),this.controller=new AbortController,Pr.set(this,void 0),Sr.set(this,()=>{}),Ot.set(this,()=>{}),Tt.set(this,void 0),Rr.set(this,()=>{}),Ft.set(this,()=>{}),ae.set(this,{}),Nt.set(this,!1),Cr.set(this,!1),Er.set(this,!1),He.set(this,!1),b(this,Pr,new Promise((e,t)=>{b(this,Sr,e,"f"),b(this,Ot,t,"f")}),"f"),b(this,Tt,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,Ft,t,"f")}),"f"),i(this,Pr,"f").catch(()=>{}),i(this,Tt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,us,"m",hn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Sr,"f").call(this),this._emit("connect")}get ended(){return i(this,Nt,"f")}get errored(){return i(this,Cr,"f")}get aborted(){return i(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,ae,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(b(this,He,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){b(this,He,!0,"f"),await i(this,Tt,"f")}_emit(e,...t){if(i(this,Nt,"f"))return;if(e==="end")b(this,Nt,!0,"f"),i(this,Rr,"f").call(this);let r=i(this,ae,"f")[e];if(r)i(this,ae,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Pr=new WeakMap,Sr=new WeakMap,Ot=new WeakMap,Tt=new WeakMap,Rr=new WeakMap,Ft=new WeakMap,ae=new WeakMap,Nt=new WeakMap,Cr=new WeakMap,Er=new WeakMap,He=new WeakMap,us=new WeakSet,hn=function(t){if(b(this,Cr,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new F;if(t instanceof F)return b(this,Er,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function dn(e){return typeof e.parse==="function"}var D,fs,vr,hs,ds,ps,pn,mn,ho=10;class Mt extends Se{constructor(){super(...arguments);D.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),cs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(qe(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,D,"m",fs).call(this)}async finalMessage(){return await this.done(),i(this,D,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,D,"m",hs).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,D,"m",ds).call(this)}async totalUsage(){return await this.done(),i(this,D,"m",ps).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,D,"m",vr).call(this);if(t)this._emit("finalMessage",t);let r=i(this,D,"m",fs).call(this);if(r)this._emit("finalContent",r);let s=i(this,D,"m",hs).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,D,"m",ds).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,D,"m",ps).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,D,"m",pn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(kt(n,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=ho}=r||{},_=t.tools.map((u)=>{if(Pe(u)){if(!u.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),y={};for(let u of _)if(u.type==="function")y[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let g=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let R of g.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:I,arguments:A}=R.function,k=y[I];if(!k){let C=`Invalid tool_call: ${JSON.stringify(I)}. Available options are: ${Object.keys(y).map((j)=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}else if(f&&f!==I){let C=`Invalid tool_call: ${JSON.stringify(I)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}let E;try{E=dn(k)?await k.parse(A):A}catch(C){let j=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:S,content:j});continue}let W=await k.function(E,this),T=i(this,D,"m",mn).call(this,W);if(this._addMessage({role:"tool",tool_call_id:S,content:T}),f)return}}return}}D=new WeakSet,fs=function(){return i(this,D,"m",vr).call(this).content??null},vr=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(qe(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},hs=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(qe(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(cs(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ps=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},pn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},mn=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Lt extends Mt{static runTools(e,t,r){let s=new Lt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),qe(e)&&e.content)this._emit("content",e.content)}}var L={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class _n extends Error{}class gn extends Error{}function po(e,t=L.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return mo(e.trim(),t)}var mo=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new _n(`${u} at position ${s}`)},o=(u)=>{throw new gn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||L.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||L.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||L.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||L.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||L.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||L.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return y()},f=()=>{let u=s,w=!1;s++;while(s<r&&(e[s]!=='"'||w&&e[s-1]==="\\"))w=e[s]==="\\"?!w:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(w)))}catch(g){o(String(g))}else if(L.STR&t)try{return JSON.parse(e.substring(u,s-Number(w))+'"')}catch(g){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&L.OBJ&t)return u;let w=f();p(),s++;try{let g=a();Object.defineProperty(u,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(L.OBJ&t)return u;else throw g}if(p(),e[s]===",")s++}}catch(w){if(L.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(w){if(L.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},y=()=>{if(s===0){if(e==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(w){if(L.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(g){}o(String(w))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(L.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(w){if(e.substring(u,s)==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(g){o(String(g))}}},p=()=>{while(s<r&&`
11
- \r `.includes(e[s]))s++};return a()},ms=(e)=>po(e,L.ALL^L.NUM);var M,le,Je,he,_s,$r,gs,ys,bs,kr,ws,yn;class de extends Mt{constructor(e){super();M.add(this),le.set(this,void 0),Je.set(this,void 0),he.set(this,void 0),b(this,le,e,"f"),b(this,Je,[],"f")}get currentChatCompletionSnapshot(){return i(this,he,"f")}static fromReadableStream(e){let t=new de(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new de(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,M,"m",_s).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)i(this,M,"m",gs).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}i(this,M,"m",_s).call(this),this._connected();let s=J.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,M,"m",kr).call(this));i(this,M,"m",gs).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}[(le=new WeakMap,Je=new WeakMap,he=new WeakMap,M=new WeakSet,_s=function(){if(this.ended)return;b(this,he,void 0,"f")},$r=function(t){let r=i(this,Je,"f")[t.index];if(r)return r;return r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i(this,Je,"f")[t.index]=r,r},gs=function(t){if(this.ended)return;let r=i(this,M,"m",yn).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let n=r.choices[s.index];if(s.delta.content!=null&&n.message?.role==="assistant"&&n.message?.content)this._emit("content",s.delta.content,n.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:n.message.content,parsed:n.message.parsed});if(s.delta.refusal!=null&&n.message?.role==="assistant"&&n.message?.refusal)this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:n.message.refusal});if(s.logprobs?.content!=null&&n.message?.role==="assistant")this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:n.logprobs?.content??[]});if(s.logprobs?.refusal!=null&&n.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:n.logprobs?.refusal??[]});let o=i(this,M,"m",$r).call(this,n);if(n.finish_reason){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).call(this,n,o.current_tool_call_index)}for(let a of s.delta.tool_calls??[]){if(o.current_tool_call_index!==a.index){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).call(this,n,o.current_tool_call_index)}o.current_tool_call_index=a.index}for(let a of s.delta.tool_calls??[]){let f=n.message.tool_calls?.[a.index];if(!f?.type)continue;if(f?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:f.function?.name,index:a.index,arguments:f.function.arguments,parsed_arguments:f.function.parsed_arguments,arguments_delta:a.function?.arguments??""});else wn(f?.type)}}},ys=function(t,r){if(i(this,M,"m",$r).call(this,t).done_tool_calls.has(r))return;let n=t.message.tool_calls?.[r];if(!n)throw Error("no tool call snapshot");if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type==="function"){let o=i(this,le,"f")?.tools?.find((a)=>vt(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:r,arguments:n.function.arguments,parsed_arguments:Pe(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else wn(n.type)},bs=function(t){let r=i(this,M,"m",$r).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,M,"m",ws).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}if(t.message.refusal&&!r.refusal_done)r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal});if(t.logprobs?.content&&!r.logprobs_content_done)r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!r.logprobs_refusal_done)r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},kr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,he,"f");if(!t)throw new m("request ended without sending any chunks");return b(this,he,void 0,"f"),b(this,Je,[],"f"),_o(t,i(this,le,"f"))},ws=function(){let t=i(this,le,"f")?.response_format;if($t(t))return t;return null},yn=function(t){var r,s,n,o;let a=i(this,he,"f"),{choices:f,...d}=t;if(!a)a=b(this,he,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:_,finish_reason:y,index:p,logprobs:u=null,...w}of t.choices){let g=a.choices[p];if(!g)g=a.choices[p]={finish_reason:y,index:p,message:{},logprobs:u,...w};if(u)if(!g.logprobs)g.logprobs=Object.assign({},u);else{let{content:W,refusal:T,...C}=u;if(bn(C),Object.assign(g.logprobs,C),W)(r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...W);if(T)(s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...T)}if(y){if(g.finish_reason=y,i(this,le,"f")&&ls(i(this,le,"f"))){if(y==="length")throw new At;if(y==="content_filter")throw new It}}if(Object.assign(g,w),!_)continue;let{content:R,refusal:S,function_call:I,role:A,tool_calls:k,...E}=_;if(bn(E),Object.assign(g.message,E),S)g.message.refusal=(g.message.refusal||"")+S;if(A)g.message.role=A;if(I)if(!g.message.function_call)g.message.function_call=I;else{if(I.name)g.message.function_call.name=I.name;if(I.arguments)(n=g.message.function_call).arguments??(n.arguments=""),g.message.function_call.arguments+=I.arguments}if(R){if(g.message.content=(g.message.content||"")+R,!g.message.refusal&&i(this,M,"m",ws).call(this))g.message.parsed=ms(g.message.content)}if(k){if(!g.message.tool_calls)g.message.tool_calls=[];for(let{index:W,id:T,type:C,function:j,...re}of k){let P=(o=g.message.tool_calls)[W]??(o[W]={});if(Object.assign(P,re),T)P.id=T;if(C)P.type=C;if(j)P.function??(P.function={name:j.name??"",arguments:""});if(j?.name)P.function.name=j.name;if(j?.arguments){if(P.function.arguments+=j.arguments,cn(i(this,le,"f"),P))P.function.parsed_arguments=ms(P.function.arguments)}}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function _o(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:_,finish_reason:y,index:p,logprobs:u,...w})=>{if(!y)throw new m(`missing finish_reason for choice ${p}`);let{content:g=null,function_call:R,tool_calls:S,...I}=_,A=_.role;if(!A)throw new m(`missing role for choice ${p}`);if(R){let{arguments:k,name:E}=R;if(k==null)throw new m(`missing function_call.arguments for choice ${p}`);if(!E)throw new m(`missing function_call.name for choice ${p}`);return{...w,message:{content:g,function_call:{arguments:k,name:E},role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}if(S)return{...w,index:p,finish_reason:y,logprobs:u,message:{...I,role:A,content:g,refusal:_.refusal??null,tool_calls:S.map((k,E)=>{let{function:W,type:T,id:C,...j}=k,{arguments:re,name:P,...ue}=W||{};if(C==null)throw new m(`missing choices[${p}].tool_calls[${E}].id
10
+ ${p}`)}return a},l=ao(an);class We extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,x,{query:t,...r})}}function Et(e){return e!==void 0&&"function"in e&&e.function!==void 0}function vt(e){return e?.$brand==="auto-parseable-response-format"}function Pe(e){return e?.$brand==="auto-parseable-tool"}function ln(e,t){if(!t||!ls(t))return{...e,choices:e.choices.map((r)=>(un(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return $t(e,t)}function $t(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new At;if(s.finish_reason==="content_filter")throw new It;return un(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>fo(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?uo(t,s.message.content):null}}});return{...e,choices:r}}function uo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function fo(e,t){let r=e.tools?.find((s)=>Et(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Pe(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function cn(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>Et(s)&&s.function?.name===t.function.name);return Et(r)&&(Pe(r)||r?.function.strict||!1)}function ls(e){if(vt(e.response_format))return!0;return e.tools?.some((t)=>Pe(t)||t.type==="function"&&t.function.strict===!0)??!1}function un(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function fn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var qe=(e)=>e?.role==="assistant",cs=(e)=>e?.role==="tool";var us,Pr,Sr,kt,Ot,Rr,Ft,ae,Nt,Cr,Er,He,hn;class Se{constructor(){us.add(this),this.controller=new AbortController,Pr.set(this,void 0),Sr.set(this,()=>{}),kt.set(this,()=>{}),Ot.set(this,void 0),Rr.set(this,()=>{}),Ft.set(this,()=>{}),ae.set(this,{}),Nt.set(this,!1),Cr.set(this,!1),Er.set(this,!1),He.set(this,!1),b(this,Pr,new Promise((e,t)=>{b(this,Sr,e,"f"),b(this,kt,t,"f")}),"f"),b(this,Ot,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,Ft,t,"f")}),"f"),i(this,Pr,"f").catch(()=>{}),i(this,Ot,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,us,"m",hn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Sr,"f").call(this),this._emit("connect")}get ended(){return i(this,Nt,"f")}get errored(){return i(this,Cr,"f")}get aborted(){return i(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,ae,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(b(this,He,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){b(this,He,!0,"f"),await i(this,Ot,"f")}_emit(e,...t){if(i(this,Nt,"f"))return;if(e==="end")b(this,Nt,!0,"f"),i(this,Rr,"f").call(this);let r=i(this,ae,"f")[e];if(r)i(this,ae,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,kt,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,kt,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Pr=new WeakMap,Sr=new WeakMap,kt=new WeakMap,Ot=new WeakMap,Rr=new WeakMap,Ft=new WeakMap,ae=new WeakMap,Nt=new WeakMap,Cr=new WeakMap,Er=new WeakMap,He=new WeakMap,us=new WeakSet,hn=function(t){if(b(this,Cr,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new F;if(t instanceof F)return b(this,Er,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function dn(e){return typeof e.parse==="function"}var D,fs,vr,hs,ds,ps,pn,mn,ho=10;class Mt extends Se{constructor(){super(...arguments);D.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),cs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(qe(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,D,"m",fs).call(this)}async finalMessage(){return await this.done(),i(this,D,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,D,"m",hs).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,D,"m",ds).call(this)}async totalUsage(){return await this.done(),i(this,D,"m",ps).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,D,"m",vr).call(this);if(t)this._emit("finalMessage",t);let r=i(this,D,"m",fs).call(this);if(r)this._emit("finalContent",r);let s=i(this,D,"m",hs).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,D,"m",ds).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,D,"m",ps).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,D,"m",pn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion($t(n,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=ho}=r||{},_=t.tools.map((u)=>{if(Pe(u)){if(!u.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),y={};for(let u of _)if(u.type==="function")y[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let g=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let R of g.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:I,arguments:A}=R.function,k=y[I];if(!k){let C=`Invalid tool_call: ${JSON.stringify(I)}. Available options are: ${Object.keys(y).map((j)=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}else if(f&&f!==I){let C=`Invalid tool_call: ${JSON.stringify(I)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}let E;try{E=dn(k)?await k.parse(A):A}catch(C){let j=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:S,content:j});continue}let W=await k.function(E,this),T=i(this,D,"m",mn).call(this,W);if(this._addMessage({role:"tool",tool_call_id:S,content:T}),f)return}}return}}D=new WeakSet,fs=function(){return i(this,D,"m",vr).call(this).content??null},vr=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(qe(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},hs=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(qe(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(cs(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ps=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},pn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},mn=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Lt extends Mt{static runTools(e,t,r){let s=new Lt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),qe(e)&&e.content)this._emit("content",e.content)}}var L={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class _n extends Error{}class gn extends Error{}function po(e,t=L.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return mo(e.trim(),t)}var mo=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new _n(`${u} at position ${s}`)},o=(u)=>{throw new gn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||L.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||L.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||L.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||L.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||L.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||L.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return y()},f=()=>{let u=s,w=!1;s++;while(s<r&&(e[s]!=='"'||w&&e[s-1]==="\\"))w=e[s]==="\\"?!w:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(w)))}catch(g){o(String(g))}else if(L.STR&t)try{return JSON.parse(e.substring(u,s-Number(w))+'"')}catch(g){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&L.OBJ&t)return u;let w=f();p(),s++;try{let g=a();Object.defineProperty(u,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(L.OBJ&t)return u;else throw g}if(p(),e[s]===",")s++}}catch(w){if(L.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(w){if(L.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},y=()=>{if(s===0){if(e==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(w){if(L.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(g){}o(String(w))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(L.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(w){if(e.substring(u,s)==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(g){o(String(g))}}},p=()=>{while(s<r&&`
11
+ \r `.includes(e[s]))s++};return a()},ms=(e)=>po(e,L.ALL^L.NUM);var M,le,Je,he,_s,$r,gs,ys,bs,kr,ws,yn;class de extends Mt{constructor(e){super();M.add(this),le.set(this,void 0),Je.set(this,void 0),he.set(this,void 0),b(this,le,e,"f"),b(this,Je,[],"f")}get currentChatCompletionSnapshot(){return i(this,he,"f")}static fromReadableStream(e){let t=new de(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new de(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,M,"m",_s).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)i(this,M,"m",gs).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}i(this,M,"m",_s).call(this),this._connected();let s=J.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,M,"m",kr).call(this));i(this,M,"m",gs).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}[(le=new WeakMap,Je=new WeakMap,he=new WeakMap,M=new WeakSet,_s=function(){if(this.ended)return;b(this,he,void 0,"f")},$r=function(t){let r=i(this,Je,"f")[t.index];if(r)return r;return r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i(this,Je,"f")[t.index]=r,r},gs=function(t){if(this.ended)return;let r=i(this,M,"m",yn).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let n=r.choices[s.index];if(s.delta.content!=null&&n.message?.role==="assistant"&&n.message?.content)this._emit("content",s.delta.content,n.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:n.message.content,parsed:n.message.parsed});if(s.delta.refusal!=null&&n.message?.role==="assistant"&&n.message?.refusal)this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:n.message.refusal});if(s.logprobs?.content!=null&&n.message?.role==="assistant")this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:n.logprobs?.content??[]});if(s.logprobs?.refusal!=null&&n.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:n.logprobs?.refusal??[]});let o=i(this,M,"m",$r).call(this,n);if(n.finish_reason){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).call(this,n,o.current_tool_call_index)}for(let a of s.delta.tool_calls??[]){if(o.current_tool_call_index!==a.index){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).call(this,n,o.current_tool_call_index)}o.current_tool_call_index=a.index}for(let a of s.delta.tool_calls??[]){let f=n.message.tool_calls?.[a.index];if(!f?.type)continue;if(f?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:f.function?.name,index:a.index,arguments:f.function.arguments,parsed_arguments:f.function.parsed_arguments,arguments_delta:a.function?.arguments??""});else wn(f?.type)}}},ys=function(t,r){if(i(this,M,"m",$r).call(this,t).done_tool_calls.has(r))return;let n=t.message.tool_calls?.[r];if(!n)throw Error("no tool call snapshot");if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type==="function"){let o=i(this,le,"f")?.tools?.find((a)=>Et(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:r,arguments:n.function.arguments,parsed_arguments:Pe(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else wn(n.type)},bs=function(t){let r=i(this,M,"m",$r).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,M,"m",ws).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}if(t.message.refusal&&!r.refusal_done)r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal});if(t.logprobs?.content&&!r.logprobs_content_done)r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!r.logprobs_refusal_done)r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},kr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,he,"f");if(!t)throw new m("request ended without sending any chunks");return b(this,he,void 0,"f"),b(this,Je,[],"f"),_o(t,i(this,le,"f"))},ws=function(){let t=i(this,le,"f")?.response_format;if(vt(t))return t;return null},yn=function(t){var r,s,n,o;let a=i(this,he,"f"),{choices:f,...d}=t;if(!a)a=b(this,he,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:_,finish_reason:y,index:p,logprobs:u=null,...w}of t.choices){let g=a.choices[p];if(!g)g=a.choices[p]={finish_reason:y,index:p,message:{},logprobs:u,...w};if(u)if(!g.logprobs)g.logprobs=Object.assign({},u);else{let{content:W,refusal:T,...C}=u;if(bn(C),Object.assign(g.logprobs,C),W)(r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...W);if(T)(s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...T)}if(y){if(g.finish_reason=y,i(this,le,"f")&&ls(i(this,le,"f"))){if(y==="length")throw new At;if(y==="content_filter")throw new It}}if(Object.assign(g,w),!_)continue;let{content:R,refusal:S,function_call:I,role:A,tool_calls:k,...E}=_;if(bn(E),Object.assign(g.message,E),S)g.message.refusal=(g.message.refusal||"")+S;if(A)g.message.role=A;if(I)if(!g.message.function_call)g.message.function_call=I;else{if(I.name)g.message.function_call.name=I.name;if(I.arguments)(n=g.message.function_call).arguments??(n.arguments=""),g.message.function_call.arguments+=I.arguments}if(R){if(g.message.content=(g.message.content||"")+R,!g.message.refusal&&i(this,M,"m",ws).call(this))g.message.parsed=ms(g.message.content)}if(k){if(!g.message.tool_calls)g.message.tool_calls=[];for(let{index:W,id:T,type:C,function:j,...re}of k){let P=(o=g.message.tool_calls)[W]??(o[W]={});if(Object.assign(P,re),T)P.id=T;if(C)P.type=C;if(j)P.function??(P.function={name:j.name??"",arguments:""});if(j?.name)P.function.name=j.name;if(j?.arguments){if(P.function.arguments+=j.arguments,cn(i(this,le,"f"),P))P.function.parsed_arguments=ms(P.function.arguments)}}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function _o(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:_,finish_reason:y,index:p,logprobs:u,...w})=>{if(!y)throw new m(`missing finish_reason for choice ${p}`);let{content:g=null,function_call:R,tool_calls:S,...I}=_,A=_.role;if(!A)throw new m(`missing role for choice ${p}`);if(R){let{arguments:k,name:E}=R;if(k==null)throw new m(`missing function_call.arguments for choice ${p}`);if(!E)throw new m(`missing function_call.name for choice ${p}`);return{...w,message:{content:g,function_call:{arguments:k,name:E},role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}if(S)return{...w,index:p,finish_reason:y,logprobs:u,message:{...I,role:A,content:g,refusal:_.refusal??null,tool_calls:S.map((k,E)=>{let{function:W,type:T,id:C,...j}=k,{arguments:re,name:P,...ue}=W||{};if(C==null)throw new m(`missing choices[${p}].tool_calls[${E}].id
12
12
  ${Or(e)}`);if(T==null)throw new m(`missing choices[${p}].tool_calls[${E}].type
13
13
  ${Or(e)}`);if(P==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.name
14
14
  ${Or(e)}`);if(re==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.arguments
15
- ${Or(e)}`);return{...j,id:C,type:T,function:{...ue,name:P,arguments:re}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ln(d,t)}function Or(e){return JSON.stringify(e)}function bn(e){return}function wn(e){}class Xe extends de{static fromReadableStream(e){let t=new Xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Xe(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class pe extends c{constructor(){super(...arguments);this.messages=new We(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(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return fn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Xe.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return de.createChatCompletion(this._client,e,t)}}pe.Messages=We;class Re extends c{constructor(){super(...arguments);this.completions=new pe(this._client)}}Re.Completions=pe;var xn=Symbol("brand.privateNullableHeaders");function*yo(e){if(!e)return;if(xn in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Jr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Jr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of yo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[xn]:!0,values:t,nulls:r}};class Bt extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}},this._client))}}class ce extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ce.Transcriptions=Ut;ce.Translations=jt;ce.Speech=Bt;class Ve extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ce extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ce.Sessions=Wt;Ce.TranscriptionSessions=qt;class Ht extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Jt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Y,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Y,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}Ee.Sessions=Ht;Ee.Threads=Jt;class Xt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Vt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var An=(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),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var K=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim();return};var B,$e,xs,Z,Tr,G,ke,Ke,ve,Mr,X,Fr,Nr,zt,Kt,Gt,In,Pn,Sn,Rn,Cn,En,vn;class me extends Se{constructor(){super(...arguments);B.add(this),xs.set(this,[]),Z.set(this,{}),Tr.set(this,{}),G.set(this,void 0),ke.set(this,void 0),Ke.set(this,void 0),ve.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),Nr.set(this,void 0),zt.set(this,void 0)}[(xs=new WeakMap,Z=new WeakMap,Tr=new WeakMap,G=new WeakMap,ke=new WeakMap,Ke=new WeakMap,ve=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,Nr=new WeakMap,zt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new $e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=J.fromReadableStream(e,this.controller);for await(let n of s)i(this,B,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new $e;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Fr,"f")}currentRun(){return i(this,Nr,"f")}currentMessageSnapshot(){return i(this,G,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Tr,"f"))}async finalRun(){if(await this.done(),!i(this,ke,"f"))throw Error("Final run was not received.");return i(this,ke,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,B,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Be(n)&&Be(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Be(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}$e=me,Kt=function(t){if(this.ended)return;switch(b(this,Fr,t,"f"),i(this,B,"m",Sn).call(this,t),t.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":i(this,B,"m",vn).call(this,t);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":i(this,B,"m",Pn).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,B,"m",In).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ko(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,ke,"f"))throw Error("Final run has not been received");return i(this,ke,"f")},In=function(t){let[r,s]=i(this,B,"m",Cn).call(this,t,i(this,G,"f"));b(this,G,r,"f"),i(this,Tr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ke,"f")){if(i(this,ve,"f"))switch(i(this,ve,"f").type){case"text":this._emit("textDone",i(this,ve,"f").text,i(this,G,"f"));break;case"image_file":this._emit("imageFileDone",i(this,ve,"f").image_file,i(this,G,"f"));break}b(this,Ke,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ke,"f")!==void 0){let n=t.data.content[i(this,Ke,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,G,"f"));break;case"text":this._emit("textDone",n.text,i(this,G,"f"));break}}if(i(this,G,"f"))this._emit("messageDone",t.data);b(this,G,void 0,"f")}},Pn=function(t){let r=i(this,B,"m",Rn).call(this,t);switch(b(this,zt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Mr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f"));if(b(this,Mr,o.index,"f"),b(this,X,r.step_details.tool_calls[o.index],"f"),i(this,X,"f"))this._emit("toolCallCreated",i(this,X,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Sn=function(t){i(this,xs,"f").push(t),this._emit("event",t)},Rn=function(t){switch(t.event){case"thread.run.step.created":return i(this,Z,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,Z,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=$e.accumulateDelta(r,s.delta);i(this,Z,"f")[t.data.id]=n}return i(this,Z,"f")[t.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":i(this,Z,"f")[t.data.id]=t.data;break}if(i(this,Z,"f")[t.data.id])return i(this,Z,"f")[t.data.id];throw Error("No snapshot available")},Cn=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,B,"m",En).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},En=function(t,r){return $e.accumulateDelta(r,t)},vn=function(t){switch(b(this,Nr,t.data,"f"),t.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":if(b(this,ke,t.data,"f"),i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f");break;case"thread.run.cancelling":break}};function ko(e){}class Ge extends c{constructor(){super(...arguments);this.steps=new Vt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return me.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}Ge.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new Ge(this._client),this.messages=new Xt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return me.createThreadAssistantStream(e,this._client.beta.threads,t)}}Oe.Runs=Ge;Oe.Messages=Xt;class ee extends c{constructor(){super(...arguments);this.realtime=new Ce(this._client),this.chatkit=new Ee(this._client),this.assistants=new Dt(this._client),this.threads=new Oe(this._client)}}ee.Realtime=Ce;ee.ChatKit=Ee;ee.Assistants=Dt;ee.Threads=Oe;class ze extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Qe extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,x,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Qe.Content=Qt;class Te extends c{constructor(){super(...arguments);this.files=new Qe(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Te.Files=Qe;class Yt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Y,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Fe extends c{constructor(){super(...arguments);this.items=new Yt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Fe.Items=Yt;class Ye extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return v(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=An(f)});return o})}}class Zt extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class Ze extends c{constructor(){super(...arguments);this.outputItems=new Zt(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,x,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}Ze.OutputItems=Zt;class Ne extends c{constructor(){super(...arguments);this.runs=new Ze(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Ne.Runs=Ze;class et extends c{create(e,t){return this._client.post("/files",V({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await z(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr extends c{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})}}class tt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}tt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,oe,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Y,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class rt extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}rt.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class st extends c{constructor(){super(...arguments);this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}st.Checkpoints=sr;class te extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new st(this._client),this.checkpoints=new rt(this._client),this.alpha=new tt(this._client)}}te.Methods=er;te.Jobs=st;te.Checkpoints=rt;te.Alpha=tt;class nr extends c{}class Me extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Me.GraderModels=nr;class nt extends c{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",V({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})}}class ot extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class it extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _e extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}_e.ClientSecrets=ir;_e.Calls=or;function $n(e,t){if(!t||!zo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return As(e,t)}function As(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:Zo(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:Go(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Lr(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function Go(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function zo(e){if($t(e.text?.format))return!0;return!1}function Qo(e){return e?.$brand==="auto-parseable-tool"}function Yo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function Zo(e,t){let r=Yo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Qo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Lr(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var at,Br,ge,Ur,kn,On,Tn,Fn;class jr extends Se{constructor(e){super();at.add(this),Br.set(this,void 0),ge.set(this,void 0),Ur.set(this,void 0),b(this,Br,e,"f")}static createResponse(e,t,r){let s=new jr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,at,"m",kn).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,at,"m",On).call(this,a,o);if(n.controller.signal?.aborted)throw new F;return i(this,at,"m",Tn).call(this)}[(Br=new WeakMap,ge=new WeakMap,Ur=new WeakMap,at=new WeakSet,kn=function(){if(this.ended)return;b(this,ge,void 0,"f")},On=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,at,"m",Fn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Tn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ge,"f");if(!t)throw new m("request ended without sending any events");b(this,ge,void 0,"f");let r=ei(t,i(this,Br,"f"));return b(this,Ur,r,"f"),r},Fn=function(t){let r=i(this,ge,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ge,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ge,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,Ur,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ei(e,t){return $n(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ye extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Lr(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Lr(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>As(r,e))}stream(e,t){return jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}ye.InputItems=ar;ye.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class lt extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}lt.Content=ur;class be extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new lt(this._client)}create(e={},t){return this._client.post("/skills",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}be.Content=cr;be.Versions=lt;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,V({body:t,...r},this._client))}}class Le extends c{constructor(){super(...arguments);this.parts=new fr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Le.Parts=fr;var Nn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class hr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){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 n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Nn(y),await this.createAndPoll(e,{file_ids:d})}}class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,oe,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class we extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,oe,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}we.Files=dr;we.FileBatches=hr;class ct extends c{create(e,t){return this._client.post("/videos",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Y,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ie({body:t,...r},this._client))}}var ut,Mn,Dr;class ft extends c{constructor(){super(...arguments);ut.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=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");i(this,ut,"m",Mn).call(this,r);let n=h([t]).values,o=i(this,ut,"m",Dr).call(this,n,"webhook-signature"),a=i(this,ut,"m",Dr).call(this,n,"webhook-timestamp"),f=i(this,ut,"m",Dr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new se("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new se("Webhook timestamp is too old");if(d>_+s)throw new se("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new se("The given webhook signature does not match the expected signature")}}ut=new WeakSet,Mn=function(t){if(typeof t!=="string"||t.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")},Dr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Is,Ps,Wr,Ln;class Ct{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("OPENAI_API_KEY"),organization:r=K("OPENAI_ORG_ID")??null,project:s=K("OPENAI_PROJECT_ID")??null,webhookSecret:n=K("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Is.add(this),Wr.set(this,void 0),this.completions=new ze(this),this.chat=new Re(this),this.embeddings=new Ye(this),this.files=new et(this),this.images=new nt(this),this.audio=new ce(this),this.moderations=new it(this),this.models=new ot(this),this.fineTuning=new te(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new ft(this),this.beta=new ee(this),this.batches=new Ve(this),this.uploads=new Le(this),this.responses=new ye(this),this.realtime=new _e(this),this.conversations=new Fe(this),this.evals=new Ne(this),this.containers=new Te(this),this.skills=new be(this),this.videos=new ct(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ns())throw new m(`It looks like you're running in a browser-like environment.
15
+ ${Or(e)}`);return{...j,id:C,type:T,function:{...ue,name:P,arguments:re}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ln(d,t)}function Or(e){return JSON.stringify(e)}function bn(e){return}function wn(e){}class Xe extends de{static fromReadableStream(e){let t=new Xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Xe(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class pe extends c{constructor(){super(...arguments);this.messages=new We(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(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return fn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>$t(r,e))}runTools(e,t){if(e.stream)return Xe.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return de.createChatCompletion(this._client,e,t)}}pe.Messages=We;class Re extends c{constructor(){super(...arguments);this.completions=new pe(this._client)}}Re.Completions=pe;var xn=Symbol("brand.privateNullableHeaders");function*yo(e){if(!e)return;if(xn in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Jr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Jr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of yo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[xn]:!0,values:t,nulls:r}};class Bt extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}},this._client))}}class ce extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ce.Transcriptions=Ut;ce.Translations=jt;ce.Speech=Bt;class Ve extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ce extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ce.Sessions=Wt;Ce.TranscriptionSessions=qt;class Ht extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Jt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Y,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Y,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}Ee.Sessions=Ht;Ee.Threads=Jt;class Xt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Vt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var An=(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),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var K=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim();return};var B,$e,xs,Z,Tr,G,ke,Ke,ve,Mr,X,Fr,Nr,zt,Kt,Gt,In,Pn,Sn,Rn,Cn,En,vn;class me extends Se{constructor(){super(...arguments);B.add(this),xs.set(this,[]),Z.set(this,{}),Tr.set(this,{}),G.set(this,void 0),ke.set(this,void 0),Ke.set(this,void 0),ve.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),Nr.set(this,void 0),zt.set(this,void 0)}[(xs=new WeakMap,Z=new WeakMap,Tr=new WeakMap,G=new WeakMap,ke=new WeakMap,Ke=new WeakMap,ve=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,Nr=new WeakMap,zt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new $e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=J.fromReadableStream(e,this.controller);for await(let n of s)i(this,B,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new $e;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Fr,"f")}currentRun(){return i(this,Nr,"f")}currentMessageSnapshot(){return i(this,G,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Tr,"f"))}async finalRun(){if(await this.done(),!i(this,ke,"f"))throw Error("Final run was not received.");return i(this,ke,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,B,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Be(n)&&Be(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Be(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}$e=me,Kt=function(t){if(this.ended)return;switch(b(this,Fr,t,"f"),i(this,B,"m",Sn).call(this,t),t.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":i(this,B,"m",vn).call(this,t);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":i(this,B,"m",Pn).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,B,"m",In).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ko(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,ke,"f"))throw Error("Final run has not been received");return i(this,ke,"f")},In=function(t){let[r,s]=i(this,B,"m",Cn).call(this,t,i(this,G,"f"));b(this,G,r,"f"),i(this,Tr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ke,"f")){if(i(this,ve,"f"))switch(i(this,ve,"f").type){case"text":this._emit("textDone",i(this,ve,"f").text,i(this,G,"f"));break;case"image_file":this._emit("imageFileDone",i(this,ve,"f").image_file,i(this,G,"f"));break}b(this,Ke,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ke,"f")!==void 0){let n=t.data.content[i(this,Ke,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,G,"f"));break;case"text":this._emit("textDone",n.text,i(this,G,"f"));break}}if(i(this,G,"f"))this._emit("messageDone",t.data);b(this,G,void 0,"f")}},Pn=function(t){let r=i(this,B,"m",Rn).call(this,t);switch(b(this,zt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Mr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f"));if(b(this,Mr,o.index,"f"),b(this,X,r.step_details.tool_calls[o.index],"f"),i(this,X,"f"))this._emit("toolCallCreated",i(this,X,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Sn=function(t){i(this,xs,"f").push(t),this._emit("event",t)},Rn=function(t){switch(t.event){case"thread.run.step.created":return i(this,Z,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,Z,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=$e.accumulateDelta(r,s.delta);i(this,Z,"f")[t.data.id]=n}return i(this,Z,"f")[t.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":i(this,Z,"f")[t.data.id]=t.data;break}if(i(this,Z,"f")[t.data.id])return i(this,Z,"f")[t.data.id];throw Error("No snapshot available")},Cn=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,B,"m",En).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},En=function(t,r){return $e.accumulateDelta(r,t)},vn=function(t){switch(b(this,Nr,t.data,"f"),t.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":if(b(this,ke,t.data,"f"),i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f");break;case"thread.run.cancelling":break}};function ko(e){}class Ge extends c{constructor(){super(...arguments);this.steps=new Vt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return me.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}Ge.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new Ge(this._client),this.messages=new Xt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return me.createThreadAssistantStream(e,this._client.beta.threads,t)}}Oe.Runs=Ge;Oe.Messages=Xt;class ee extends c{constructor(){super(...arguments);this.realtime=new Ce(this._client),this.chatkit=new Ee(this._client),this.assistants=new Dt(this._client),this.threads=new Oe(this._client)}}ee.Realtime=Ce;ee.ChatKit=Ee;ee.Assistants=Dt;ee.Threads=Oe;class ze extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Qe extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,x,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Qe.Content=Qt;class Te extends c{constructor(){super(...arguments);this.files=new Qe(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Te.Files=Qe;class Yt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Y,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Fe extends c{constructor(){super(...arguments);this.items=new Yt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Fe.Items=Yt;class Ye extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return v(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=An(f)});return o})}}class Zt extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class Ze extends c{constructor(){super(...arguments);this.outputItems=new Zt(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,x,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}Ze.OutputItems=Zt;class Ne extends c{constructor(){super(...arguments);this.runs=new Ze(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Ne.Runs=Ze;class et extends c{create(e,t){return this._client.post("/files",V({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await z(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr extends c{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})}}class tt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}tt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,oe,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Y,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class rt extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}rt.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class st extends c{constructor(){super(...arguments);this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}st.Checkpoints=sr;class te extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new st(this._client),this.checkpoints=new rt(this._client),this.alpha=new tt(this._client)}}te.Methods=er;te.Jobs=st;te.Checkpoints=rt;te.Alpha=tt;class nr extends c{}class Me extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Me.GraderModels=nr;class nt extends c{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",V({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})}}class ot extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class it extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _e extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}_e.ClientSecrets=ir;_e.Calls=or;function $n(e,t){if(!t||!zo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return As(e,t)}function As(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:Zo(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:Go(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Lr(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function Go(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function zo(e){if(vt(e.text?.format))return!0;return!1}function Qo(e){return e?.$brand==="auto-parseable-tool"}function Yo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function Zo(e,t){let r=Yo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Qo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Lr(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var at,Br,ge,Ur,kn,On,Tn,Fn;class jr extends Se{constructor(e){super();at.add(this),Br.set(this,void 0),ge.set(this,void 0),Ur.set(this,void 0),b(this,Br,e,"f")}static createResponse(e,t,r){let s=new jr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,at,"m",kn).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,at,"m",On).call(this,a,o);if(n.controller.signal?.aborted)throw new F;return i(this,at,"m",Tn).call(this)}[(Br=new WeakMap,ge=new WeakMap,Ur=new WeakMap,at=new WeakSet,kn=function(){if(this.ended)return;b(this,ge,void 0,"f")},On=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,at,"m",Fn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Tn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ge,"f");if(!t)throw new m("request ended without sending any events");b(this,ge,void 0,"f");let r=ei(t,i(this,Br,"f"));return b(this,Ur,r,"f"),r},Fn=function(t){let r=i(this,ge,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ge,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ge,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,Ur,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ei(e,t){return $n(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ye extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Lr(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Lr(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>As(r,e))}stream(e,t){return jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}ye.InputItems=ar;ye.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class lt extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}lt.Content=ur;class be extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new lt(this._client)}create(e={},t){return this._client.post("/skills",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}be.Content=cr;be.Versions=lt;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,V({body:t,...r},this._client))}}class Le extends c{constructor(){super(...arguments);this.parts=new fr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Le.Parts=fr;var Nn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class hr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){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 n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Nn(y),await this.createAndPoll(e,{file_ids:d})}}class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,oe,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class we extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,oe,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}we.Files=dr;we.FileBatches=hr;class ct extends c{create(e,t){return this._client.post("/videos",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Y,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ie({body:t,...r},this._client))}}var ut,Mn,Dr;class ft extends c{constructor(){super(...arguments);ut.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=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");i(this,ut,"m",Mn).call(this,r);let n=h([t]).values,o=i(this,ut,"m",Dr).call(this,n,"webhook-signature"),a=i(this,ut,"m",Dr).call(this,n,"webhook-timestamp"),f=i(this,ut,"m",Dr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new se("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new se("Webhook timestamp is too old");if(d>_+s)throw new se("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new se("The given webhook signature does not match the expected signature")}}ut=new WeakSet,Mn=function(t){if(typeof t!=="string"||t.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")},Dr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Is,Ps,Wr,Ln;class Tt{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("OPENAI_API_KEY"),organization:r=K("OPENAI_ORG_ID")??null,project:s=K("OPENAI_PROJECT_ID")??null,webhookSecret:n=K("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Is.add(this),Wr.set(this,void 0),this.completions=new ze(this),this.chat=new Re(this),this.embeddings=new Ye(this),this.files=new et(this),this.images=new nt(this),this.audio=new ce(this),this.moderations=new it(this),this.models=new ot(this),this.fineTuning=new te(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new ft(this),this.beta=new ee(this),this.batches=new Ve(this),this.uploads=new Le(this),this.responses=new ye(this),this.realtime=new _e(this),this.conversations=new Fe(this),this.evals=new Ne(this),this.containers=new Te(this),this.skills=new be(this),this.videos=new ct(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ns())throw new m(`It looks like you're running in a browser-like environment.
16
16
 
17
17
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
18
18
  If you understand the risks and have appropriate mitigations in place,
@@ -21,4 +21,4 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
21
21
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
22
22
 
23
23
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
24
- `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}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,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(dt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=ht(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>dt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(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||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=Ct,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};Ct.OpenAI=Ps;Ct.DEFAULT_TIMEOUT=600000;Ct.OpenAIError=m;Ct.APIError=O;Ct.APIConnectionError=xe;Ct.APIConnectionTimeoutError=Ae;Ct.APIUserAbortError=F;Ct.NotFoundError=gt;Ct.ConflictError=yt;Ct.RateLimitError=wt;Ct.BadRequestError=pt;Ct.AuthenticationError=mt;Ct.InternalServerError=xt;Ct.PermissionDeniedError=_t;Ct.UnprocessableEntityError=bt;Ct.InvalidWebhookSignatureError=se;Ct.toFile=Ir;Ct.Completions=ze;Ct.Chat=Re;Ct.Embeddings=Ye;Ct.Files=et;Ct.Images=nt;Ct.Audio=ce;Ct.Moderations=it;Ct.Models=ot;Ct.FineTuning=te;Ct.Graders=Me;Ct.VectorStores=we;Ct.Webhooks=ft;Ct.Beta=ee;Ct.Batches=Ve;Ct.Uploads=Le;Ct.Responses=ye;Ct.Realtime=_e;Ct.Conversations=Fe;Ct.Evals=Ne;Ct.Containers=Te;Ct.Skills=be;Ct.Videos=ct;class Xd extends Ct{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("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")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{Ct,Xd};
24
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}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,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(dt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=ht(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>dt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(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||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=Tt,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};Tt.OpenAI=Ps;Tt.DEFAULT_TIMEOUT=600000;Tt.OpenAIError=m;Tt.APIError=O;Tt.APIConnectionError=xe;Tt.APIConnectionTimeoutError=Ae;Tt.APIUserAbortError=F;Tt.NotFoundError=gt;Tt.ConflictError=yt;Tt.RateLimitError=wt;Tt.BadRequestError=pt;Tt.AuthenticationError=mt;Tt.InternalServerError=xt;Tt.PermissionDeniedError=_t;Tt.UnprocessableEntityError=bt;Tt.InvalidWebhookSignatureError=se;Tt.toFile=Ir;Tt.Completions=ze;Tt.Chat=Re;Tt.Embeddings=Ye;Tt.Files=et;Tt.Images=nt;Tt.Audio=ce;Tt.Moderations=it;Tt.Models=ot;Tt.FineTuning=te;Tt.Graders=Me;Tt.VectorStores=we;Tt.Webhooks=ft;Tt.Beta=ee;Tt.Batches=Ve;Tt.Uploads=Le;Tt.Responses=ye;Tt.Realtime=_e;Tt.Conversations=Fe;Tt.Evals=Ne;Tt.Containers=Te;Tt.Skills=be;Tt.Videos=ct;class vf extends Tt{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("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")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{Tt,vf};
@@ -0,0 +1,2 @@
1
+ import{j}from"./chunk-akafypge.js";var e=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Nu=j("square",e);
2
+ export{Nu};