@arcgis/ai-components 5.1.0-next.104 → 5.1.0-next.105

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.
@@ -0,0 +1,107 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import{$ as Ta,$a as Qs,Aa as ja,Ab as Ha,Ba as L,Ca as w,Cb as No,D as ya,Da as Zs,Db as Dn,E as xe,Ea as je,Eb as $o,F as wa,Fa as Ln,Fb as jo,G as Io,Ga as Le,H as Ds,Ha as fr,I as Us,Ia as hr,J as xo,Ja as Vs,K as Fs,Ka as La,La as Gs,M as D,Ma as Eo,N as Bs,Na as za,O as Aa,Oa as Da,P as ba,Pa as Mo,Q as S,Qa as Ua,R as To,Ra as gr,S as Je,Sa as Ys,T as vo,Ta as Fa,U as Ia,Ua as Ba,V as xa,Va as zn,W as Te,Wa as Ka,X as Ks,Xa as Xs,Y as Ws,Ya as _r,Z as fe,Za as b,_ as Co,a as Ao,aa as va,ab as Ro,b as Z,ba as Hs,ca as ko,da as Ca,ea as ve,eb as Wa,f as de,fa as $n,ga as qs,ha as ka,ia as Js,j as ue,ja as Oa,k as be,ka as jn,kb as he,la as pt,ma as Pa,na as Sa,oa as Ea,pa as dr,qa as Ma,ra as Ze,sa as Ra,t as _a,ta as Na,u as bo,ua as mt,va as Oo,wa as Ve,xa as Po,xb as dt,ya as $a,yb as ei,za as So,zb as ge}from"./WDTUSWTQ.js";export default $arcgis.t(([da,zs,Yc,Pf,Sf])=>{async function ti(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
+
4
+ If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
+
6
+ Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
7
+ |`,`
8
+ \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
9
+ `].join(" "));let n=await Ca(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var Ie=b;var zo={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},Ja=Object.keys(zo);async function ap(t,e){let r;if(e)r=zo[e];else{let n=Object.entries(zo).find(([,o])=>o.className===t);r=n?n[1]:void 0}if(r)try{return(await import(r.package))[r.className]}catch(n){let o=n;if("code"in o&&o.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in o&&typeof o.message=="string"){let s=(o.message.startsWith("Error: ")?o.message.slice(7):o.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function lp(t,e,r={}){let n=e||up(t);if(!n)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);let o=zo[n];if(!o){let a=Ja.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
10
+
11
+ Supported model providers are: ${a}`)}let{modelProvider:s,...i}=r;return new(await ap(o.className,n))({model:t,...i})}function up(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var qa=class Lo extends zn{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(e){let r=this._getCacheKey(e),n=this._modelInstanceCache.get(r);if(n)return n;let o={...this._defaultConfig,...this._modelParams(e)},s=await lp(o.model,o.modelProvider,o);for(let[i,a]of Object.entries(this._queuedMethodOperations))i in s&&typeof s[i]=="function"&&(s=await s[i](...a));return this._modelInstanceCache.set(r,s),s}async _generate(e,r,n){return(await this._getModelInstance(r))._generate(e,r??{},n)}bindTools(e,r){let n={...this._queuedMethodOperations};return n.bindTools=[e,r],new Lo({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(e,...r)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[e,...r],new Lo({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(e){let r=e?.configurable??{},n={};for(let[o,s]of Object.entries(r))if(o.startsWith(this._configPrefix)){let i=this._removePrefix(o,this._configPrefix);n[i]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([o])=>this._configurableFields.includes(o)))),n}_removePrefix(e,r){return e.startsWith(r)?e.slice(r.length):e}withConfig(e){let r={...e||{}},n=this._modelParams(r),o=Object.fromEntries(Object.entries(r).filter(([s])=>s!=="configurable"));return o.configurable=Object.fromEntries(Object.entries(r.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new Le({config:r,bound:new Lo({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,r){let n=await this._getModelInstance(r),o=$n(r);return n.invoke(e,o)}async stream(e,r){let n=new Oa({generator:await(await this._getModelInstance(r)).stream(e,r),config:r});return await n.setup,Js.fromAsyncGenerator(n)}async batch(e,r,n){return super.batch(e,r,n)}async*transform(e,r){let n=await this._getModelInstance(r),o=$n(r);yield*n.transform(e,o)}async*streamLog(e,r,n){let o=await this._getModelInstance(r),s=$n(r);yield*o.streamLog(e,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,r,n){let o=this;async function*s(){let i=await o._getModelInstance(r),a=$n(r),u=i.streamEvents(e,a,n);for await(let l of u)yield l}return Js.fromAsyncGenerator(s())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let r=e??{};if(r.configurable){let{configurable:n}=r,o={};for(let[s,i]of Object.entries(n))s.startsWith("__pregel_")||(o[s]=i);r={...r,configurable:o}}return JSON.stringify(r)}};async function Ge(t,e){let{configurableFields:r,configPrefix:n,modelProvider:o,profile:s,...i}={configPrefix:"",...e??{}};if(o===void 0&&t?.includes(":")){let[c,...m]=t.split(":"),_=m.length===0?[c]:[c,m.join(":")];Ja.includes(_[0])&&([o,t]=_)}let a=Array.isArray(r)?[...r]:r;!t&&a===void 0&&(a=["model","modelProvider"]),n&&a===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...i},l;return a===void 0?l=new qa({defaultConfig:{...u,model:t,modelProvider:o},configPrefix:n,profile:s}):(t&&(u.model=t),o&&(u.modelProvider=o),l=new qa({defaultConfig:u,configPrefix:n,configurableFields:a,profile:s})),await l._getModelInstance(),l}var Do=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},Uo=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},ri=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(r=>`
12
+ - ${r}`).join("")}.`),this.toolName=t,this.errors=e}},Fo=class extends Error{toolCall;toolError;constructor(t,e){let r=t instanceof Error?t:new Error(String(t)),n=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${n} with error: ${r.stack}
13
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=r}},Fn=class Za extends Error{static"~brand"="MiddlewareError";constructor(e,r){let n=e instanceof Error?e.message:String(e);super(n),this.name=e instanceof Error?e.name:`${r[0].toUpperCase()+r.slice(1)}Error`,e instanceof Error&&(this.cause=e)}static wrap(e,r){return _a(e)?e:new Za(e,r)}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="MiddlewareError"}};function Bn(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function yr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}var Va=!0,cp=0,Ce=class ni{constructor(e,r,n){this.schema=e,this.tool=r,this.options=n}get name(){return this.tool.function.name}static fromSchema(e,r){function n(s){return s??`extract-${++cp}`}if(pt(e)||Ze(e)){let s=je(e);return new ni(s,{type:"function",function:{name:n(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},r)}let o;return typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?o=e:o={name:n(e.title),description:e.description??"",parameters:e.schema||e},new ni(je(e),{type:"function",function:o},r)}parse(e){let r=new Zs(this.schema).validate(e);if(!r.valid)throw new ri(this.name,r.errors.map(n=>n.error));return e}},ft=class Ga{_schemaType;schema;strict;constructor(e,r){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){let n=e;this.schema=n.schema,this.strict=n.strict??Va}else this.schema=e,this.strict=r??Va}static fromSchema(e,r){return new Ga(je(e),r)}parse(e){let r;if(typeof e.content=="string")r=e.content;else if(Array.isArray(e.content)){for(let n of e.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){r=n.text;break}}if(!(!r||r===""))try{let n=JSON.parse(r);return new Zs(this.schema).validate(n).valid?n:void 0}catch{}}};function Ya(t,e,r){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(o=>o instanceof Ce||o instanceof ft))return t;if(t.every(o=>pt(o)))return t.map(o=>Ce.fromSchema(o,e));if(t.every(o=>Ve(o)))return t.map(o=>Ce.fromSchema(o,e));if(t.every(o=>typeof o=="object"&&o!==null&&!Ve(o)&&!pt(o)))return t.map(o=>Ce.fromSchema(o,e));throw new Error(`Invalid response format: list contains mixed types.
14
+ All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(t instanceof Ce||t instanceof ft)return[t];let n=pp(r);if(pt(t))return n?[ft.fromSchema(t)]:[Ce.fromSchema(t,e)];if(Ve(t))return n?[ft.fromSchema(t)]:[Ce.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return n?[ft.fromSchema(t)]:[Ce.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function pp(t){return!t||!Bn(t)||!("profile"in t)||typeof t.profile!="object"||!t.profile?!1:"structuredOutput"in t.profile&&t.profile.structuredOutput===!0}function Bo(t,e){let n=0;if(e&&e.length>0){let o=0;for(let s of e){let i=_r(s)?Ro(s):s;o+=JSON.stringify(i).length}n+=o}for(let o of t){let s;typeof o.content=="string"?s=o.content:Array.isArray(o.content)?s=o.content.map(i=>typeof i=="string"?i:i.type==="text"&&"text"in i?i.text:"").join(""):s="",S.isInstance(o)&&Array.isArray(o.tool_calls)&&o.tool_calls.length>0&&(s+=JSON.stringify(o.tool_calls)),D.isInstance(o)&&(s+=o.tool_call_id??""),n+=s.length}return Math.ceil(n/4)}function ze(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function ht(t){return typeof t=="function"?t:t.hook}var oi=Symbol.for("AgentMiddleware");function Q(t){return{[oi]:!0,name:t.name,stateSchema:t.stateSchema,contextSchema:t.contextSchema,wrapToolCall:t.wrapToolCall,wrapModelCall:t.wrapModelCall,beforeAgent:t.beforeAgent,beforeModel:t.beforeModel,afterModel:t.afterModel,afterAgent:t.afterAgent,tools:t.tools}}var si=Symbol.for("langgraph-zod");si in globalThis||(globalThis[si]=new WeakSet);function Xa(t){let e=globalThis[si];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return $o(r,{jsonSchemaExtra:n})},reducer(n,o){return $o(r,{default:So(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{Xa(w.ZodType.prototype),Xa(b.ZodType.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var Qa=class extends Sa{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=So(t);n!=null&&(r.default=n)}return super.add(t,...e)}},mp=new Qa(Dn);function el(t=!0,e,r=[]){let n={jumpTo:new ei},o={},s={},i=a=>{if(ge.isInstance(a)){for(let[l,c]of Object.entries(a.fields))if(!(l in n)){if(n[l]=c,l.startsWith("_"))continue;dt.isInstance(c)?(o[l]=c.inputSchema||c.valueSchema,s[l]=c.valueSchema):(o[l]=c,s[l]=c)}return}let u=Po(a);for(let[l,c]of Object.entries(u)){let m=l.startsWith("_");if(!(l in n)){if(dr(c)){let _=Dn.get(c);if(_?.reducer){_.reducer.schema?(n[l]=new dt(c,{inputSchema:_.reducer.schema,reducer:_.reducer.fn}),m||(o[l]=_.reducer.schema,s[l]=c)):(n[l]=new dt(c,{reducer:_.reducer.fn}),m||(o[l]=c,s[l]=c));continue}}n[l]=c,m||(o[l]=c,s[l]=c)}}};e&&(ge.isInstance(e)||Ve(e))&&i(e);for(let a of r)a.stateSchema&&(ge.isInstance(a.stateSchema)||Ve(a.stateSchema))&&i(a.stateSchema);return t&&(s.structuredResponse=new ei),{state:new ge({messages:No,...n}),input:new ge({messages:No,...o}),output:new ge({messages:No,...s})}}var ii=/<name>(.*?)<\/name>/s,ai=/<content>(.*?)<\/content>/s;function dp(t,e){if(ge.isInstance(t)){let r={};for(let n of Object.keys(t.fields))n in e&&(r[n]=e[n]);return r}if(Ze(t))return mt(t,e);throw new Error(`Invalid state schema type: ${typeof t}`)}function rl(t){if(!S.isInstance(t)||Je.isInstance(t)||!t.name)return t;let{name:e}=t;if(typeof t.content=="string")return new S({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});let r=[],n=0;for(let o of t.content)typeof o=="string"?(n+=1,r.push(`<name>${e}</name><content>${o}</content>`)):typeof o=="object"&&"type"in o&&o.type==="text"?(n+=1,r.push({...o,text:`<name>${e}</name><content>${o.text}</content>`})):r.push(o);return n||r.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new S({...t.lc_kwargs,content:r,name:void 0})}function nl(t){if(!S.isInstance(t)||!t.content)return t;let e=[],r;if(Array.isArray(t.content))e=t.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(ii),s=n.text.match(ai);return o&&(!s||s[1]==="")?(r=o[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(ii),s=n.text.match(ai);return!o||!s?n:(r=o[1],{...n,text:s[1]})}return n});else{let n=t.content,o=n.match(ii),s=n.match(ai);if(!o||!s)return t;r=o[1],e=s[1]}return new S({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:r})}function Nt(t){return Ln.isRunnable(t)}function tl(t){return Bn(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}var li=(t,e,r={})=>{if(tl(t))return t.bindTools(e,r);if(Le.isRunnableBinding(t)&&tl(t.bound)){let n=t.bound.bindTools(e,r);return Le.isRunnableBinding(n)?new Le({bound:n.bound,config:{...t.config,...n.config},kwargs:{...t.kwargs,...n.kwargs},configFactories:n.configFactories??t.configFactories}):new Le({bound:n,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function Ko(t){if(typeof t=="function")return;let e=t;if(fr.isRunnableSequence(e)&&(e=e.steps.find(r=>Le.isRunnableBinding(r))||e),!yr(e)){if(Le.isRunnableBinding(e)){let r=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,n=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(r||n)throw new Do}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new Do}}function wr(t){return!!(S.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function ol(t){if(t==null)return new fe("");if(fe.isInstance(t))return t;if(typeof t=="string")return new fe({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function sl(t,e,r={}){let n=li(t,e,r);if(n)return n;if(yr(t)){let o=li(await t._getModelInstance(),e,r);if(o)return o}if(fr.isRunnableSequence(t)){let o=t.steps.findIndex(s=>Le.isRunnableBinding(s)||Bn(s)||yr(s));if(o>=0){let s=li(t.steps[o],e,r);if(s){let i=t.steps.slice();return i.splice(o,1,s),fr.from(i)}}}throw new Error(`llm ${t} must define bindTools method.`)}function fp(t){if(t.length===0)return;if(t.length===1)return t[0];function e(n,o){return async(s,i)=>n(s,async u=>o(u,i))}let r=t[t.length-1];for(let n=t.length-2;n>=0;n--)r=e(t[n],r);return r}function il(t){let e=t.filter(r=>r.wrapToolCall);if(e.length!==0)return fp(e.map(r=>{let n=r.wrapToolCall;return async(s,i)=>{let a=s.state,u=async l=>{let c={...a,...l.state};return i({...l,state:c})};try{let l=await n({...s,state:{messages:a.messages,...r.stateSchema?dp(r.stateSchema,{...a}):{}}},u);if(!D.isInstance(l)&&!be(l))throw new Error(`Invalid response from "wrapToolCall" in middleware "${r.name}": expected ToolMessage or Command, got ${typeof l}`);return l}catch(l){throw Fn.wrap(l,r.name)}}}))}async function al(t,e){let r={};for(let n of t){if(!n.stateSchema)continue;let o=n.stateSchema;if(ge.isInstance(n.stateSchema)){let a={};for(let[u,l]of Object.entries(n.stateSchema.fields))dt.isInstance(l)?a[u]=l.inputSchema||l.valueSchema:a[u]=l;o=b.object(a)}let s=await Ra(ja(o,a=>a.startsWith("_")),e);if(s.success){Object.assign(r,s.data);continue}let i=s.error.issues.filter(a=>a.code==="invalid_type").map(a=>` - ${a.path.join(".")}: Required`).join(`
15
+ `);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
16
+ ${i}
17
+
18
+ To fix this, either:
19
+ 1. Provide default values in your middleware's state schema using .default():
20
+ stateSchema: z.object({
21
+ myField: z.string().default("default value")
22
+ })
23
+
24
+ 2. Or make the fields optional using .optional():
25
+ stateSchema: z.object({
26
+ myField: z.string().optional()
27
+ })
28
+
29
+ 3. Or ensure you pass these values when invoking the agent:
30
+ agent.invoke({
31
+ messages: [...],
32
+ ${s.error.issues[0]?.path.join(".")}: "value"
33
+ })`)}return r}function ll(t){let e={messages:b.custom(()=>[]),structuredResponse:b.any().optional()};if(!t)return b.object(e);let r;if(ge.isInstance(t)){r={};for(let[o,s]of Object.entries(t.fields))dt.isInstance(s)?r[o]=s.inputSchema||s.valueSchema:r[o]=s}else r=Po(t);let n={...e};for(let[o,s]of Object.entries(r))o.startsWith("_")?n[o]=s.optional():n[o]=s;return b.object(n)}function ul(t){if(Ve(t))return $a(t);if(ge.isInstance(t)){let e={};for(let[r,n]of Object.entries(t.fields)){let o;dt.isInstance(n)?o=n.inputSchema||n.valueSchema:o=n,e[r]=dr(o)?o.optional():b.any().optional()}return b.object(e)}return b.object({})}function ke(t){if(t){if(["model_request","tools",Z].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return Z;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function Wo(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var Ar=class extends Ln{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){let r=ve(this.config,e),n=await ko.runWithConfig(r,async()=>this.func(t,r));return Ln.isRunnable(n)&&this.recurse?await ko.runWithConfig(r,async()=>n.invoke(t,r)):(this.#e=n,n)}};function cl(t,e){let r,n;if(e==="inline")r=rl,n=nl;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function o(s){return s.map(r)}return fr.from([hr.from(o),t,hr.from(n)])}function hp(t){return S.isInstance(t)||be(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}var re="model_request",pl=class extends Ar{#e;#r;constructor(t){super({name:t.name??"model",func:(e,r)=>this.#t(e,r)}),this.#e=t,this.#r=t.systemMessage}async#s(t,e=this.#e.responseFormat){if(!e)return;let r;yr(t)?r=await t._getModelInstance():typeof t!="string"&&(r=t);let n=Ya(e,void 0,r);if(n.length!==0)return n.every(o=>o instanceof ft)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(o=>o instanceof Ce).reduce((o,s)=>(o[s.name]=s,o),{})}}async#t(t,e){let r=t.messages.at(-1);if(r&&D.isInstance(r)&&r.name&&this.#e.shouldReturnDirect.has(r.name))return[new ue({update:{messages:[]}})];let{response:n,lastAiMessage:o,collectedCommands:s}=await this.#i(t,e);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:l}=n;return{messages:[...t.messages,...l],structuredResponse:u}}let i=[],a=S.isInstance(n)?n:o;return a&&(a.name=this.name,a.lc_kwargs.name=this.name,this.#o(t,a)?i.push(new ue({update:{messages:[new S({content:"Sorry, need more steps to process this request.",name:this.name,id:a.id})]}})):i.push(new ue({update:{messages:[a]}}))),be(n)&&!s.includes(n)&&i.push(n),i.push(...s),i}#n(){if(typeof this.#e.model=="string")return Ge(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#i(t,e,r={}){let n=await this.#n(),o=e,s=this.#r,i=null,a=[],u=async _=>{Ko(_.model);let d=await this.#s(_.model,_.responseFormat),y=await this.#c(_.model,_,d),T=[...s.text===""?[]:[s],..._.messages],$=Wo(this.#e.signal,e.signal),f=await ka(y.invoke(T,{...e,signal:$}),$);if(i=f,d?.type==="native"){let z=d.strategy.parse(f);return z?{structuredResponse:z,messages:[f]}:f}if(!d||!f.tool_calls)return f;let A=f.tool_calls.filter(z=>z.name in d.tools);if(A.length===0)return f;if(A.length>1)return this.#l(f,A,d);let C=d.tools[A[0].name]?.options?.toolMessageContent;return this.#u(f,A[0],d,C??r.lastMessage)},l=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let _=l.length-1;_>=0;_--){let[d,y]=l[_];if(d.wrapModelCall){let T=c,$=d,f=y;c=async A=>{let C=s,z=$.contextSchema?mt($.contextSchema,o?.context||{}):o?.context,J=Object.freeze({context:z,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal}),B={...A,state:{...d.stateSchema?mt(ul(d.stateSchema),t):{},...f(),messages:t.messages},runtime:J},U=async M=>{s=C;let x=M.tools??[],k=new Map(this.#e.toolClasses.filter(Nt).map(le=>[le.name,le])),j=x.filter(le=>Nt(le)&&!k.has(le.name)),H=x.filter(le=>{if(!Nt(le))return!1;let ga=k.get(le.name);return ga!=null&&ga!==le});if(j.length>0&&!this.#e.middleware?.some(le=>le.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${$.name}": ${j.map(le=>le.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(H.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${$.name}": ${H.map(le=>le.name).join(", ")}. This is not supported.`);let q=M,R=M.systemPrompt!==s.text,F=M.systemMessage!==s;if(R&&F)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");R&&(s=new fe({content:[{type:"text",text:M.systemPrompt}]}),q={...M,systemPrompt:s.text,systemMessage:s}),F&&(s=new fe({...M.systemMessage}),q={...M,systemPrompt:s.text,systemMessage:s});let wo=await T(q);return be(wo)&&i?(a.includes(wo)||a.push(wo),i):wo};if(!$.wrapModelCall)return U(B);try{let M=await $.wrapModelCall(B,U);if(!hp(M))throw new Error(`Invalid response from "wrapModelCall" in middleware "${$.name}": expected AIMessage or Command, got ${typeof M}`);return S.isInstance(M)?i=M:be(M)&&a.push(M),M}catch(M){throw Fn.wrap(M,$.name)}}}}s=this.#r;let m={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:o?.context,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal})};return{response:await c(m),lastAiMessage:i,collectedCommands:a}}#l(t,e,r){let n=new Uo(e.map(o=>o.name));return this.#a(n,t,e[0],r)}#u(t,e,r,n){let o=r.tools[e.name];try{let s=o.parse(e.args);return{structuredResponse:s,messages:[t,new D({tool_call_id:e.id??"",content:JSON.stringify(s),name:e.name}),new S(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#a(s,t,e,r)}}async#a(t,e,r,n){let o=Object.values(n.tools).at(0)?.options?.handleError,s=r.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(o===!1)throw t;if(o===void 0||typeof o=="boolean"&&o||Array.isArray(o)&&o.some(i=>i instanceof Uo))return new ue({update:{messages:[e,new D({content:t.message,tool_call_id:s})]},goto:re});if(typeof o=="string")return new ue({update:{messages:[e,new D({content:o,tool_call_id:s})]},goto:re});if(typeof o=="function"){let i=await o(t);if(typeof i!="string")throw new Error("Error handler must return a string.");return new ue({update:{messages:[e,new D({content:i,tool_call_id:s})]},goto:re})}return new ue({update:{messages:[e,new D({content:t.message,tool_call_id:s})]},goto:re})}#o(t,e){let r=S.isInstance(e)&&e.tool_calls?.every(o=>this.#e.shouldReturnDirect.has(o.name)),n="remainingSteps"in t?t.remainingSteps:void 0;return!!(n&&(n<1&&r||n<2&&wr(t.messages.at(-1))))}async#c(t,e,r){let n={},o=Object.values(r&&"tools"in r?r.tools:{}),s=[...e?.tools??this.#e.toolClasses,...o.map(u=>u.tool)],i=e?.toolChoice||(o.length>0?"any":void 0);if(r?.type==="native"){let u=e?.modelSettings?.strict??r?.strategy?.strict??!0,l={name:r.strategy.schema?.name??"extract",description:Oo(r.strategy.schema),schema:r.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:l},outputConfig:{format:{type:"json_schema",schema:r.strategy.schema}},responseSchema:r.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:r.strategy.schema},strict:u})}let a=await sl(t,s,{...n,...e?.modelSettings,tool_choice:i});return this.#e.includeAgentName==="inline"?cl(a,this.#e.includeAgentName):a}getState(){let t=super.getState();return{messages:[],...t&&!be(t)?t:{}}}};var ml=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,ce="tools",dl=t=>Array.isArray(t)&&t.every(Fs.isInstance),gp=t=>typeof t=="object"&&t!=null&&"messages"in t&&dl(t.messages),_p=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function yp(t,e){return t instanceof Fo?new D({content:t.message,tool_call_id:e.id,name:e.name}):new D({content:`${t}
34
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var fl=class extends Ar{tools;trace=!1;signal;handleToolErrors=yp;wrapToolCall;constructor(t,e){let{name:r,tags:n,handleToolErrors:o,signal:s,wrapToolCall:i}=e??{};super({name:r,tags:n,func:(a,u)=>this.run(a,u)}),this.options=e,this.tools=t,this.handleToolErrors=o??this.handleToolErrors,this.signal=s,this.wrapToolCall=i}#e(t,e,r){if(bo(t)||this.signal?.aborted||r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(t,e);if(n&&D.isInstance(n))return n;throw t}else if(this.handleToolErrors)return new D({name:e.name,content:`${t}
35
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,r){let n=e,o={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===t.name),i=async u=>{let{toolCall:l,tool:c}=u,m=c??this.tools.find(d=>d.name===l.name);if(m===void 0){let d=this.tools.map(y=>y.name);return new D({content:ml(l.name,d),tool_call_id:l.id,name:l.name,status:"error"})}let _=m;try{let d=await _.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Wo(this.signal,e.signal)});return D.isInstance(d)||be(d)?d:new D({name:_.name,content:typeof d=="string"?d:JSON.stringify(d),tool_call_id:l.id})}catch(d){throw d instanceof ba?new Fo(d,l):d}},a={toolCall:t,tool:s,state:r,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(a,i)}catch(u){return this.#e(u,t,!0)}if(!s){let u=this.tools.map(l=>l.name);return new D({content:ml(t.name,u),tool_call_id:t.id,name:t.name,status:"error"})}try{return await i(a)}catch(u){return this.#e(u,t,!1)}}async run(t,e){let r;if(_p(t)){let{lg_tool_call:s,jumpTo:i,...a}=t;r=[await this.runTool(t.lg_tool_call,e,a)]}else{let s;if(dl(t))s=t;else if(gp(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),a;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(S.isInstance(l)){a=l;break}}if(!S.isInstance(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(u=>u.id==null||!i.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(be))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)be(s)?s.graph===ue.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>wp(i))?o?o.goto.push(...s.goto):o=new ue({graph:ue.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};function wp(t){return t instanceof de}var Ap=class{},bp=class{},gt=class extends Ar{#e;constructor(t,e){super(t),this.#e=e}async invokeMiddleware(t,e){let r={};if(this.middleware.contextSchema){let u=this.middleware.contextSchema?.shape;if(u){let l={},c=e?.context||{};for(let m of Object.keys(u))m in c&&(l[m]=c[m]);r=mt(this.middleware.contextSchema,l)}}let n={...this.#e.getState(),...t,messages:t.messages},o={context:r,store:e?.store,configurable:e?.configurable,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new bp,{...o,context:Object.freeze(Object.assign(new Ap,r))})));if(!s)return{jumpTo:void 0};let i,a;if(this.name?.startsWith("BeforeAgentNode_")?(i=ze(this.middleware.beforeAgent),a="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=ze(this.middleware.beforeModel),a="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=ze(this.middleware.afterAgent),a="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=ze(this.middleware.afterModel),a="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!i?.includes(s.jumpTo)){let u=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:a?`no ${a} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:ll(this.middleware.stateSchema)}}};var hl=class extends gt{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t,e){super({name:`BeforeAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return ht(this.middleware.beforeAgent)(t,e)}};var gl=class extends gt{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t,e){super({name:`BeforeModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return ht(this.middleware.beforeModel)(t,e)}};var _l=class extends gt{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t,e){super({name:`AfterModelNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return ht(this.middleware.afterModel)(t,e)}};var yl=class extends gt{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t,e){super({name:`AfterAgentNode_${t.name}`,func:async(r,n)=>this.invokeMiddleware(r,n)},e),this.middleware=t}runHook(t,e){return ht(this.middleware.afterAgent)(t,e)}};var wl=class{#e=new Map;addNode(t,e){this.#e.set(t.name,[...this.#e.get(t.name)??[],e])}getState(t){let e=(this.#e.get(t)??[]).reduce((r,n)=>({...r,...n.getState()??{}}),{});return delete e.jumpTo,e}};var Al=class bl{#e;#r="v2";#s;#t=new wl;#n;constructor(e,r){if(this.options=e,this.#n=ve(r??{},{metadata:{ls_integration:"langchain_create_agent"}}),e.name&&(this.#n=ve(this.#n,{metadata:{lc_agent_name:e.name}})),this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&Ko(e.model);let n=this.options.middleware?.filter(x=>x.tools).flatMap(x=>x.tools)??[],o=[...e.tools??[],...n],s=new Set(o.filter(Nt).filter(x=>"returnDirect"in x&&x.returnDirect).map(x=>x.name)),i=!!this.options.middleware?.some(x=>x.wrapModelCall),{state:a,input:u,output:l}=el(this.options.responseFormat!==void 0||i,this.options.stateSchema,this.options.middleware),c=new jo(a,{input:u,output:l,context:this.options.contextSchema}),m=[],_=[],d=[],y=[],T=[];this.#s=new pl({model:this.options.model,systemMessage:ol(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:o,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:T});let $=new Set,f=this.options.middleware??[];for(let x=0;x<f.length;x++){let k,j,H,q,R=f[x];if($.has(R.name))throw new Error(`Middleware ${R.name} is defined multiple times`);if($.add(R.name),R.beforeAgent){k=new hl(R,{getState:()=>this.#t.getState(R.name)}),this.#t.addNode(R,k);let F=`${R.name}.before_agent`;m.push({index:x,name:F,allowed:ze(R.beforeAgent)}),c.addNode(F,k,k.nodeOptions)}if(R.beforeModel){j=new gl(R,{getState:()=>this.#t.getState(R.name)}),this.#t.addNode(R,j);let F=`${R.name}.before_model`;_.push({index:x,name:F,allowed:ze(R.beforeModel)}),c.addNode(F,j,j.nodeOptions)}if(R.afterModel){H=new _l(R,{getState:()=>this.#t.getState(R.name)}),this.#t.addNode(R,H);let F=`${R.name}.after_model`;d.push({index:x,name:F,allowed:ze(R.afterModel)}),c.addNode(F,H,H.nodeOptions)}if(R.afterAgent){q=new yl(R,{getState:()=>this.#t.getState(R.name)}),this.#t.addNode(R,q);let F=`${R.name}.after_agent`;y.push({index:x,name:F,allowed:ze(R.afterAgent)}),c.addNode(F,q,q.nodeOptions)}R.wrapModelCall&&T.push([R,()=>this.#t.getState(R.name)])}c.addNode(re,this.#s);let A=f.some(x=>x.wrapToolCall),C=o.filter(Nt);if(C.length>0||A){let x=new fl(C,{signal:this.options.signal,wrapToolCall:il(f)});c.addNode(ce,x)}let z;m.length>0?z=m[0].name:_.length>0?z=_[0].name:z=re;let J=_.length>0?_[0].name:re,B=y.length>0?y[y.length-1].name:Z;c.addEdge(Ao,z);let U=C.length>0||A;for(let x=0;x<m.length;x++){let k=m[x],j=k.name,H=x===m.length-1?J:m[x+1].name;if(k.allowed&&k.allowed.length>0){let q=k.allowed.map(F=>ke(F)).filter(F=>F!=="tools"||U),R=Array.from(new Set([H,...q.map(F=>F===Z?B:F)]));c.addConditionalEdges(j,this.#c(C,H,B,U),R)}else c.addEdge(j,H)}for(let x=0;x<_.length;x++){let k=_[x],j=k.name,H=x===_.length-1?re:_[x+1].name;if(k.allowed&&k.allowed.length>0){let q=k.allowed.map(F=>ke(F)).filter(F=>F!=="tools"||U),R=Array.from(new Set([H,...q]));c.addConditionalEdges(j,this.#m(C,H,U),R)}else c.addEdge(j,H)}let M=d.at(-1);if(d.length>0&&M)c.addEdge(re,M.name);else{let x=this.#i(C,!1,U).map(k=>k===Z?B:k);x.length===1?c.addEdge(re,x[0]):c.addConditionalEdges(re,this.#u(B),x)}for(let x=d.length-1;x>0;x--){let k=d[x],j=k.name,H=d[x-1].name;if(k.allowed&&k.allowed.length>0){let q=k.allowed.map(F=>ke(F)).filter(F=>F!=="tools"||U),R=Array.from(new Set([H,...q]));c.addConditionalEdges(j,this.#o(C,k.allowed,H,U),R)}else c.addEdge(j,H)}if(d.length>0){let x=d[0],k=x.name,j=this.#i(C,!0,U).filter(R=>R!=="tools"||U),H=!!(x.allowed&&x.allowed.length>0),q=j.map(R=>R===Z?B:R);c.addConditionalEdges(k,this.#a(C,H,B,U),q)}for(let x=y.length-1;x>0;x--){let k=y[x],j=k.name,H=y[x-1].name;if(k.allowed&&k.allowed.length>0){let q=k.allowed.map(F=>ke(F)).filter(F=>F!=="tools"||U),R=Array.from(new Set([H,...q]));c.addConditionalEdges(j,this.#o(C,k.allowed,H,U),R)}else c.addEdge(j,H)}if(y.length>0){let x=y[0],k=x.name;if(x.allowed&&x.allowed.length>0){let j=x.allowed.map(q=>ke(q)).filter(q=>q!=="tools"||U),H=Array.from(new Set([Z,...j]));c.addConditionalEdges(k,this.#o(C,x.allowed,Z,U),H)}else c.addEdge(k,Z)}if(U){let x=J;s.size>0?c.addConditionalEdges(ce,this.#l(s,B,x),[x,B]):c.addEdge(ce,x)}this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(e){this.#e.checkpointer=e}get store(){return this.#e.store}set store(e){this.#e.store=e}withConfig(e){return new bl(this.options,ve(this.#n,e))}#i(e,r=!1,n=e.length>0){let o=[];return n&&o.push(ce),r&&o.push(re),o.push(Z),o}#l(e,r,n){return o=>{let s=o.messages,i=s[s.length-1];return D.isInstance(i)&&i.name&&e.has(i.name)?this.options.responseFormat?n:r:n}}#u(e=Z){return r=>{let n=r.messages.at(-1);if(!S.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return e;if(this.#r==="v1")return ce;let o=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return o.length===0?e:o.map(s=>new de(ce,{...r,lg_tool_call:s}))}}#a(e,r,n,o=e.length>0){let s=!!this.options.responseFormat;return i=>{let a=i,u=a.messages,l=u.at(-1);if(S.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(r&&a.jumpTo){let f=ke(a.jumpTo);return f===Z?n:f==="tools"?o?new de(ce,{...i,jumpTo:void 0}):n:new de(re,{...i,jumpTo:void 0})}let c=u.filter(D.isInstance),m=u.filter(S.isInstance).at(-1),_=m?.tool_calls?.filter(f=>!c.some(A=>A.tool_call_id===f.id));if(_&&_.length>0)return this.#r==="v1"?ce:_.map(f=>new de(ce,{...i,lg_tool_call:f}));let d=m?.tool_calls?.some(f=>f.name.startsWith("extract-"));if(_&&_.length===0&&!d&&s)return re;if(!S.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;let y=l.tool_calls.every(f=>f.name.startsWith("extract-")),T=l.tool_calls.some(f=>!f.name.startsWith("extract-"));if(y||!T)return n;if(this.#r==="v1")return ce;let $=l.tool_calls.filter(f=>!f.name.startsWith("extract-"));return $.length===0?n:$.map(f=>new de(ce,{...i,lg_tool_call:f}))}}#o(e,r,n,o=e.length>0){let s=new Set(r.map(i=>ke(i)));return i=>{let a=i;if(a.jumpTo){let u=ke(a.jumpTo);if(u===Z&&s.has(Z))return Z;if(u==="tools"&&s.has("tools"))return o?new de(ce,{...i,jumpTo:void 0}):Z;if(u==="model_request"&&s.has("model_request"))return new de(re,{...i,jumpTo:void 0})}return n}}#c(e,r,n,o=e.length>0){return s=>{let i=s;if(!i.jumpTo)return r;let a=ke(i.jumpTo);return a===Z?n:a==="tools"?o?new de(ce,{...s,jumpTo:void 0}):n:new de(re,{...s,jumpTo:void 0})}}#m(e,r,n=e.length>0){return o=>{let s=o;if(!s.jumpTo)return r;let i=ke(s.jumpTo);return i===Z?Z:i==="tools"?n?new de(ce,{...o,jumpTo:void 0}):Z:new de(re,{...o,jumpTo:void 0})}}async#p(e,r){if(!this.options.middleware||this.options.middleware.length===0||e instanceof ue||!e)return e;let n=await al(this.options.middleware,e),o={...(await this.#e.getState(r).catch(()=>({values:{}}))).values,...e};if(!o)return o;for(let[s,i]of Object.entries(n))s in o||(o[s]=i);return o}async invoke(e,r){let n=ve(this.#n,r),o=await this.#p(e,n);return this.#e.invoke(o,n)}async stream(e,r){let n=ve(this.#n,r),o=await this.#p(e,n);return this.#e.stream(o,n)}async drawMermaidPng(e){let r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,r,n){let o=ve(this.#n,r);return this.#e.streamEvents(e,{...o,version:r?.version??"v2"},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,r){return this.#e.getState(e,r)}getStateHistory(e,r){return this.#e.getStateHistory(e,r)}getSubgraphs(e,r){return this.#e.getSubgraphs(e,r)}getSubgraphsAsync(e,r){return this.#e.getSubgraphsAsync(e,r)}updateState(e,r,n){return this.#e.updateState(e,r,n)}get builder(){return this.#e.builder}};function ui(t){return new Al(t)}var Ip=w.function().args(w.custom(),w.custom(),w.custom()).returns(w.union([w.string(),w.promise(w.string())])),xp=["approve","edit","reject"],Tp=w.enum(xp),vp=w.object({allowedDecisions:w.array(Tp),description:w.union([w.string(),Ip]).optional(),argsSchema:w.record(w.any()).optional()}),ly=w.object({interruptOn:w.record(w.union([w.boolean(),vp])).optional(),descriptionPrefix:w.string().default("Tool execution requires approval")});var Ho=`<role>
36
+ Context Extraction Assistant
37
+ </role>
38
+
39
+ <primary_objective>
40
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
41
+ </primary_objective>
42
+
43
+ <objective_information>
44
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
45
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
46
+ </objective_information>
47
+
48
+ <instructions>
49
+ The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
50
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
51
+ </instructions>
52
+
53
+ The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
54
+
55
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
56
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
57
+
58
+ <messages>
59
+ Messages to summarize:
60
+ {messages}
61
+ </messages>`,Cp="Here is a summary of the conversation to date:",qo=20,kp=4e3,Op=15,Il=5,Pp=w.function().args(w.array(w.custom())).returns(w.union([w.number(),w.promise(w.number())])),Kn=w.object({fraction:w.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:w.number().positive("Tokens must be greater than 0").optional(),messages:w.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),ci=w.object({fraction:w.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:w.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:w.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),xl=w.object({model:w.custom(),trigger:w.union([Kn,w.array(Kn)]).optional(),keep:ci.optional(),tokenCounter:Pp.optional(),summaryPrompt:w.string().default(Ho),trimTokensToSummarize:w.number().optional(),summaryPrefix:w.string().optional(),maxTokensBeforeSummary:w.number().optional(),messagesToKeep:w.number().optional()});function Jo(t){if("profile"in t&&typeof t.profile=="object"&&t.profile&&"maxInputTokens"in t.profile&&(typeof t.profile.maxInputTokens=="number"||t.profile.maxInputTokens==null))return t.profile.maxInputTokens??void 0;if("model"in t&&typeof t.model=="string")return Gs(t.model);if("modelName"in t&&typeof t.modelName=="string")return Gs(t.modelName)}function pi(t){let{data:e,error:r}=Na(xl,t);if(r)throw new Error(`Invalid summarization middleware options: ${b.prettifyError(r)}`);return Q({name:"SummarizationMiddleware",contextSchema:xl.extend({model:w.custom().optional()}),beforeModel:async(n,o)=>{let s=e.trigger,i=e.keep;e.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),s===void 0&&(s={tokens:e.maxTokensBeforeSummary})),e.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===qo)&&(i={messages:e.messagesToKeep}));let a=o.context?.trigger!==void 0?o.context.trigger:s,u=o.context?.keep!==void 0?o.context.keep:i??{messages:qo},l=ci.parse(u),c=[];a===void 0?c=[]:Array.isArray(a)?c=a.map(M=>Kn.parse(M)):c=[Kn.parse(a)];let m=c.some(M=>"fraction"in M)||"fraction"in l,_=typeof e.model=="string"?await Ge(e.model):e.model;if(m&&!Jo(_))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");let d=o.context?.summaryPrompt===Ho?e.summaryPrompt??Ho:o.context?.summaryPrompt??e.summaryPrompt??Ho,y=o.context.summaryPrefix??e.summaryPrefix??Cp,T=o.context?.trimTokensToSummarize!==void 0?o.context.trimTokensToSummarize:e.trimTokensToSummarize??kp;Sp(n.messages);let $=o.context?.tokenCounter!==void 0?o.context.tokenCounter:e.tokenCounter??Bo,f=await $(n.messages);if(!await Rp(n.messages,f,c,_))return;let{systemPrompt:A,conversationMessages:C}=Ep(n.messages),z=await Np(C,l,$,_);if(z<=0)return;let{messagesToSummarize:J,preservedMessages:B}=Mp(A,C,z),U=new Te({content:`${y}
62
+
63
+ ${await Lp(J,_,d,$,T,o)}`,id:Hs(),additional_kwargs:{lc_source:"summarization"}});return{messages:[new Ws({id:Ha}),U,...B]}}})}function Sp(t){for(let e of t)e.id||(e.id=Hs())}function Ep(t){return t.length>0&&fe.isInstance(t[0])?{systemPrompt:t[0],conversationMessages:t.slice(1)}:{conversationMessages:t}}function Mp(t,e,r){let n=e.slice(0,r),o=e.slice(r);return t&&n.unshift(t),{messagesToSummarize:n,preservedMessages:o}}async function Rp(t,e,r,n){if(r.length===0)return!1;for(let o of r){let s=!0,i=!1;if(o.messages!==void 0&&(i=!0,t.length<o.messages&&(s=!1)),o.tokens!==void 0&&(i=!0,e<o.tokens&&(s=!1)),o.fraction!==void 0){i=!0;let a=Jo(n);typeof a=="number"?e<Math.floor(a*o.fraction)&&(s=!1):s=!1}if(i&&s)return!0}return!1}async function Np(t,e,r,n){if("tokens"in e||"fraction"in e){let o=await $p(t,e,r,n);return typeof o=="number"?o:Tl(t,qo)}return Tl(t,e.messages??qo)}async function $p(t,e,r,n){if(t.length===0)return 0;let o;if("fraction"in e&&e.fraction!==void 0){let c=Jo(n);if(typeof c!="number")return;o=Math.floor(c*e.fraction)}else if("tokens"in e&&e.tokens!==void 0)o=Math.floor(e.tokens);else return;if(o<=0&&(o=1),await r(t)<=o)return 0;let s=0,i=t.length,a=t.length,u=Math.floor(Math.log2(t.length))+1;for(let c=0;c<u&&!(s>=i);c++){let m=Math.floor((s+i)/2);await r(t.slice(m))<=o?(a=m,i=m):s=m+1}if(a===t.length&&(a=s),a>=t.length){if(t.length===1)return 0;a=t.length-1}let l=kl(t,a);if(l<=a)return l;for(let c=a;c>=0;c--)if(vl(t,c))return c;return 0}function Tl(t,e){if(t.length<=e)return 0;let r=t.length-e,n=kl(t,r);if(n<=r)return n;for(let o=r;o>=0;o--)if(vl(t,o))return o;return 0}function vl(t,e){if(e>=t.length)return!0;if(e<t.length&&S.isInstance(t[e])&&wr(t[e]))return!1;let r=Math.max(0,e-Il),n=Math.min(t.length,e+Il);for(let o=r;o<n;o++){if(!wr(t[o]))continue;let s=Cl(t[o]);if(jp(t,o,e,s))return!1}return!0}function Cl(t){let e=new Set;if(t.tool_calls)for(let r of t.tool_calls){let n=typeof r=="object"&&"id"in r?r.id:null;n&&e.add(n)}return e}function kl(t,e){if(e>=t.length||!D.isInstance(t[e]))return e;let r=new Set,n=e;for(;n<t.length&&D.isInstance(t[n]);){let o=t[n];o.tool_call_id&&r.add(o.tool_call_id),n++}for(let o=e-1;o>=0;o--){let s=t[o];if(S.isInstance(s)&&wr(s)){let i=Cl(s);for(let a of r)if(i.has(a))return o}}return n}function jp(t,e,r,n){for(let o=e+1;o<t.length;o++){let s=t[o];if(D.isInstance(s)&&n.has(s.tool_call_id)&&e<r!=o<r)return!0}return!1}async function Lp(t,e,r,n,o,s){if(!t.length)return"No previous conversation history.";let i=await zp(t,n,o);if(!i.length)return"Previous conversation was too long to summarize.";let a=va(i);try{let u=r.replace("{messages}",a),l=ve(qs(s)??{},{metadata:{lc_source:"summarization"}}),c=(await e.invoke(u,l)).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(m=>typeof m=="string"?m:typeof m=="object"&&m!==null&&"text"in m?m.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(u){return`Error generating summary: ${u}`}}async function zp(t,e,r){if(r===void 0)return t;try{return await Vs(t,{maxTokens:r,tokenCounter:async n=>e(n),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return t.slice(-Op)}}var Ey=w.object({model:w.string().or(w.instanceof(za)).optional(),systemPrompt:w.string().optional(),maxTools:w.number().optional(),alwaysInclude:w.array(w.string()).optional()});var zy=w.object({applyToInput:w.boolean().optional(),applyToOutput:w.boolean().optional(),applyToToolResults:w.boolean().optional()});var Ky=w.object({rules:w.record(w.string(),w.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Dp=["continue","error","end"],Up="continue";var Fp=w.enum(Dp).default(Up);w.object({toolName:w.string().optional(),threadLimit:w.number().optional(),runLimit:w.number().optional(),exitBehavior:Fp});var ew=w.object({threadToolCallCount:w.record(w.string(),w.number()).default({}),runToolCallCount:w.record(w.string(),w.number()).default({})});var Bp=w.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Kp=w.object({content:w.string().describe("Content of the todo item"),status:Bp}),lw=w.object({todos:w.array(Kp).default([])});var Wp="end",Hp=w.object({threadLimit:w.number().optional(),runLimit:w.number().optional(),exitBehavior:w.enum(["error","end"]).optional()}),qp=w.object({threadModelCallCount:w.number().default(0),runModelCallCount:w.number().default(0)}),Ol=class extends Error{constructor({threadLimit:t,runLimit:e,threadCount:r,runCount:n}){let o=[];typeof t=="number"&&typeof r=="number"&&o.push(`thread level call limit reached with ${r} model calls`),typeof e=="number"&&typeof n=="number"&&o.push(`run level call limit reached with ${n} model calls`),super(`Model call limits exceeded${o.length>0?`: ${o.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function mi(t){return Q({name:"ModelCallLimitMiddleware",contextSchema:Hp,stateSchema:qp,beforeModel:{canJumpTo:["end"],hook:(e,r)=>{let n=r.context.exitBehavior??t?.exitBehavior??Wp;n==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),n="error");let o=r.context.threadLimit??t?.threadLimit,s=r.context.runLimit??t?.runLimit,i=e.threadModelCallCount,a=e.runModelCallCount;if(typeof o=="number"&&o<=i){let u=new Ol({threadLimit:o,threadCount:i});if(n==="end")return{jumpTo:"end",messages:[new S(u.message)]};throw u}if(typeof s=="number"&&s<=a){let u=new Ol({runLimit:s,runCount:a});if(n==="end")return{jumpTo:"end",messages:[new S(u.message)]};throw u}return e}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}var Zo=w.object({maxRetries:w.number().min(0).default(2),retryOn:w.union([w.function().args(w.instanceof(Error)).returns(w.boolean()),w.array(w.custom())]).default(()=>()=>!0),backoffFactor:w.number().min(0).default(2),initialDelayMs:w.number().min(0).default(1e3),maxDelayMs:w.number().min(0).default(6e4),jitter:w.boolean().default(!0)});var Ow=w.object({onFailure:w.union([w.literal("error"),w.literal("continue"),w.function().args(w.instanceof(Error)).returns(w.string())]).default("continue")}).merge(Zo);var jw=w.object({tools:w.array(w.union([w.custom(),w.custom(),w.string()])).optional(),onFailure:w.union([w.literal("error"),w.literal("continue"),w.literal("raise"),w.literal("return_message"),w.function().args(w.instanceof(Error)).returns(w.string())]).default("continue")}).merge(Zo);var Zw=w.object({enableCaching:w.boolean().optional(),ttl:w.enum(["5m","1h"]).optional(),minMessagesToCache:w.number().optional(),unsupportedModelBehavior:w.enum(["ignore","warn","raise"]).optional()});function Wn(t,e){return t.lc_error_code=e,t.message=`${t.message}
64
+
65
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
66
+ `,t}function O(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function g(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var di=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return di=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Hn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var qn=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var v=class extends Error{},V=class t extends v{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new _t({message:n,cause:qn(r)});let s=r?.error;return e===400?new br(e,s,n,o):e===401?new Ir(e,s,n,o):e===403?new xr(e,s,n,o):e===404?new Tr(e,s,n,o):e===409?new vr(e,s,n,o):e===422?new Cr(e,s,n,o):e===429?new kr(e,s,n,o):e>=500?new Or(e,s,n,o):new t(e,s,n,o)}},G=class extends V{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},_t=class extends V{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},De=class extends _t{constructor({message:e}={}){super({message:e??"Request timed out."})}},br=class extends V{},Ir=class extends V{},xr=class extends V{},Tr=class extends V{},vr=class extends V{},Cr=class extends V{},kr=class extends V{},Or=class extends V{},Pr=class extends v{constructor(){super("Could not parse response content as the length limit was reached")}},Sr=class extends v{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ue=class extends Error{constructor(e){super(e)}},$t=class extends V{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let i=r;s=i.error;let a=i.error_description;a&&typeof a=="string"?o=a:s&&(o=s)}super(e,r,o,n),this.error_code=s}},Jn=class extends v{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Qp=/^[a-z][a-z0-9+.-]*:/i,Pl=t=>Qp.test(t),se=t=>(se=Array.isArray,se(t)),fi=se;function Vo(t){return typeof t!="object"?{}:t??{}}function hi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Sl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Zn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var El=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new v(`${t} must be an integer`);if(e<0)throw new v(`${t} must be a positive integer`);return e};var Ml=t=>{try{return JSON.parse(t)}catch{return}};var Fe=t=>new Promise(e=>setTimeout(e,t));var yt="6.37.0";var jl=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function em(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var tm=()=>{let t=em();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":Nl(Deno.build.os),"X-Stainless-Arch":Rl(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":Nl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Rl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=rm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function rm(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var Rl=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Nl=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),$l,Ll=()=>$l??($l=tm());function Go(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function gi(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Yo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return gi({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function _i(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function yi(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Dl=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var wi="RFC3986",Ai=t=>String(t),bi={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Ai},Ul="RFC1738";var Xo=(t,e)=>(Xo=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Xo(t,e)),Be=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Ii=1024,Fl=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=Ii){let u=s.length>=Ii?s.slice(a,a+Ii):s,l=[];for(let c=0;c<u.length;++c){let m=u.charCodeAt(c);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===Ul&&(m===40||m===41)){l[l.length]=u.charAt(c);continue}if(m<128){l[l.length]=Be[m];continue}if(m<2048){l[l.length]=Be[192|m>>6]+Be[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Be[224|m>>12]+Be[128|m>>6&63]+Be[128|m&63];continue}c+=1,m=65536+((m&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=Be[240|m>>18]+Be[128|m>>12&63]+Be[128|m>>6&63]+Be[128|m&63]}i+=l.join("")}return i};function Bl(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function xi(t,e){if(se(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Wl={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Hl=function(t,e){Array.prototype.push.apply(t,se(e)?e:[e])},Kl,ee={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Fl,encodeValuesOnly:!1,format:wi,formatter:Ai,indices:!1,serializeDate(t){return(Kl??(Kl=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function om(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Ti={};function ql(t,e,r,n,o,s,i,a,u,l,c,m,_,d,y,T,$,f){let A=t,C=f,z=0,J=!1;for(;(C=C.get(Ti))!==void 0&&!J;){let k=C.get(t);if(z+=1,typeof k<"u"){if(k===z)throw new RangeError("Cyclic object value");J=!0}typeof C.get(Ti)>"u"&&(z=0)}if(typeof l=="function"?A=l(e,A):A instanceof Date?A=_?.(A):r==="comma"&&se(A)&&(A=xi(A,function(k){return k instanceof Date?_?.(k):k})),A===null){if(s)return u&&!T?u(e,ee.encoder,$,"key",d):e;A=""}if(om(A)||Bl(A)){if(u){let k=T?e:u(e,ee.encoder,$,"key",d);return[y?.(k)+"="+y?.(u(A,ee.encoder,$,"value",d))]}return[y?.(e)+"="+y?.(String(A))]}let B=[];if(typeof A>"u")return B;let U;if(r==="comma"&&se(A))T&&u&&(A=xi(A,u)),U=[{value:A.length>0?A.join(",")||null:void 0}];else if(se(l))U=l;else{let k=Object.keys(A);U=c?k.sort(c):k}let M=a?String(e).replace(/\./g,"%2E"):String(e),x=n&&se(A)&&A.length===1?M+"[]":M;if(o&&se(A)&&A.length===0)return x+"[]";for(let k=0;k<U.length;++k){let j=U[k],H=typeof j=="object"&&typeof j.value<"u"?j.value:A[j];if(i&&H===null)continue;let q=m&&a?j.replace(/\./g,"%2E"):j,R=se(A)?typeof r=="function"?r(x,q):x:x+(m?"."+q:"["+q+"]");f.set(t,z);let F=new WeakMap;F.set(Ti,f),Hl(B,ql(H,R,r,n,o,s,i,a,r==="comma"&&T&&se(A)?null:u,l,c,m,_,d,y,T,$,F))}return B}function sm(t=ee){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||ee.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=wi;if(typeof t.format<"u"){if(!Xo(bi,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=bi[r],o=ee.filter;(typeof t.filter=="function"||se(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Wl?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=ee.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:ee.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ee.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ee.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ee.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?ee.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ee.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ee.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ee.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ee.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ee.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ee.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ee.strictNullHandling}}function Jl(t,e={}){let r=t,n=sm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):se(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=Wl[n.arrayFormat],u=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let _=0;_<o.length;++_){let d=o[_];n.skipNulls&&r[d]===null||Hl(i,ql(r[d],d,a,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let c=i.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),c.length>0?m+c:""}function Zl(t){return Jl(t,{arrayFormat:"brackets"})}function Yl(t){let e=0;for(let o of t)e+=o.length;let r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var Vl;function Er(t){let e;return(Vl??(e=new globalThis.TextEncoder,Vl=e.encode.bind(e)))(t)}var Gl;function vi(t){let e;return(Gl??(e=new globalThis.TextDecoder,Gl=e.decode.bind(e)))(t)}var _e,ye,jt=class{constructor(){_e.set(this,void 0),ye.set(this,void 0),O(this,_e,new Uint8Array,"f"),O(this,ye,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Er(e):e;O(this,_e,Yl([g(this,_e,"f"),r]),"f");let n=[],o;for(;(o=am(g(this,_e,"f"),g(this,ye,"f")))!=null;){if(o.carriage&&g(this,ye,"f")==null){O(this,ye,o.index,"f");continue}if(g(this,ye,"f")!=null&&(o.index!==g(this,ye,"f")+1||o.carriage)){n.push(vi(g(this,_e,"f").subarray(0,g(this,ye,"f")-1))),O(this,_e,g(this,_e,"f").subarray(g(this,ye,"f")),"f"),O(this,ye,null,"f");continue}let s=g(this,ye,"f")!==null?o.preceding-1:o.preceding,i=vi(g(this,_e,"f").subarray(0,s));n.push(i),O(this,_e,g(this,_e,"f").subarray(o.index),"f"),O(this,ye,null,"f")}return n}flush(){return g(this,_e,"f").length?this.decode(`
67
+ `):[]}};_e=new WeakMap,ye=new WeakMap;jt.NEWLINE_CHARS=new Set([`
68
+ `,"\r"]);jt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function am(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Xl(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var es={off:0,error:200,warn:300,info:400,debug:500},Ci=(t,e,r)=>{if(t){if(Sl(es,t))return t;Y(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(es))}`)}};function Vn(){}function Qo(t,e,r){return!e||es[t]>es[r]?Vn:e[t].bind(e)}var lm={error:Vn,warn:Vn,info:Vn,debug:Vn},Ql=new WeakMap;function Y(t){let e=t.logger,r=t.logLevel??"off";if(!e)return lm;let n=Ql.get(e);if(n&&n[0]===r)return n[1];let o={error:Qo("error",e,r),warn:Qo("warn",e,r),info:Qo("info",e,r),debug:Qo("debug",e,r)};return Ql.set(e,[r,o]),o}var Ye=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Gn,Ke=class t{constructor(e,r,n){this.iterator=e,Gn.set(this,void 0),this.controller=r,O(this,Gn,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,i=n?Y(n):console;async function*a(){if(s)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of um(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(m){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),m}if(c&&c.error)throw new V(void 0,c.error,void 0,e.headers);yield o?{event:l.event,data:c}:c}else{let c;try{c=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new V(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}u=!0}catch(l){if(Hn(l))return;throw l}finally{u||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let a=new jt,u=_i(e);for await(let l of u)for(let c of a.decode(l))yield c;for(let l of a.flush())yield l}async function*i(){if(o)throw new v("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let u of s())a||u&&(yield JSON.parse(u));a=!0}catch(u){if(Hn(u))return;throw u}finally{a||r.abort()}}return new t(i,r,n)}[(Gn=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let i=n.next();e.push(i),r.push(i)}return s.shift()}});return[new t(()=>o(e),this.controller,g(this,Gn,"f")),new t(()=>o(r),this.controller,g(this,Gn,"f"))]}toReadableStream(){let e=this,r;return gi({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let i=Er(JSON.stringify(o)+`
69
+ `);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*um(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new v("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new v("Attempted to iterate over a response with no body");let r=new ki,n=new jt,o=_i(t.body);for await(let s of cm(o))for(let i of n.decode(s)){let a=r.decode(i);a&&(yield a)}for(let s of n.flush()){let i=r.decode(s);i&&(yield i)}}async function*cm(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Er(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Xl(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ki=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
70
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=pm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function pm(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ts(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return Y(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):Ke.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let _=await r.json();return Oi(_,r)}return await r.text()})();return Y(t).debug(`[${n}] response parsed`,Ye({retryOfRequestLogID:o,url:r.url,status:r.status,body:i,durationMs:Date.now()-s})),i}function Oi(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Yn,Lt=class t extends Promise{constructor(e,r,n=ts){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Yn.set(this,void 0),O(this,Yn,e,"f")}_thenUnwrap(e){return new t(g(this,Yn,"f"),this.responsePromise,async(r,n)=>Oi(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(g(this,Yn,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Yn=new WeakMap;var rs,Mr=class{constructor(e,r,n,o){rs.set(this,void 0),O(this,rs,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await g(this,rs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(rs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Xn=class extends Lt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await ts(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},ie=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},N=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...Vo(this.options.query),after:r}}:null}},W=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Vo(this.options.query),after:e}}:null}},X=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Vo(this.options.query),after:e}}:null}};var dm={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},fm="urn:ietf:params:oauth:grant-type:token-exchange",ns=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Go()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:fm,client_id:this.config.clientId,subject_token:e,subject_token_type:dm[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!r.ok){let i=await r.text(),a;try{a=JSON.parse(i)}catch{}throw r.status===400||r.status===401||r.status===403?new $t(r.status,a,r.headers):V.generate(r.status,a,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.json(),o=n.expires_in||3600,s=Date.now()+o*1e3;return this.cachedToken={token:n.access_token,expiresAt:s},n.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Ei=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Rr(t,e,r){return Ei(),new File(t,e??"unknown_file",r)}function Qn(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var os=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",wt=async(t,e)=>Pi(t.body)?{...t,body:await tu(t.body,e)}:t,ae=async(t,e)=>({...t,body:await tu(t.body,e)}),eu=new WeakMap;function hm(t){let e=typeof t=="function"?t:t.fetch,r=eu.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return eu.set(e,n),n}var tu=async(t,e)=>{if(!await hm(e))throw new 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(t||{}).map(([n,o])=>Si(r,n,o))),r},ru=t=>t instanceof Blob&&"name"in t,gm=t=>typeof t=="object"&&t!==null&&(t instanceof Response||os(t)||ru(t)),Pi=t=>{if(gm(t))return!0;if(Array.isArray(t))return t.some(Pi);if(t&&typeof t=="object"){for(let e in t)if(Pi(t[e]))return!0}return!1},Si=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Rr([await r.blob()],Qn(r)));else if(os(r))t.append(e,Rr([await new Response(Yo(r)).blob()],Qn(r)));else if(ru(r))t.append(e,r,Qn(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Si(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Si(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var nu=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",_m=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&nu(t),ym=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function eo(t,e,r){if(Ei(),t=await t,_m(t))return t instanceof File?t:Rr([await t.arrayBuffer()],t.name);if(ym(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Rr(await Mi(o),e,r)}let n=await Mi(t);if(e||(e=Qn(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Rr(n,e,r)}async function Mi(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(nu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(os(t))for await(let r of t)e.push(...await Mi(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${wm(t)}`)}return e}function wm(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var h=class{constructor(e){this._client=e}};function su(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ou=Object.freeze(Object.create(null)),bm=(t=su)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i=r.reduce((c,m,_)=>{/[?#]/.test(m)&&(o=!0);let d=n[_],y=(o?encodeURIComponent:t)(""+d);return _!==n.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??ou)??ou)?.toString)&&(y=d+"",s.push({start:c.length+m.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),c+m+(_===n.length?"":y)},""),a=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(a))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((c,m)=>c.start-m.start),s.length>0){let c=0,m=s.reduce((_,d)=>{let y=" ".repeat(d.start-c),T="^".repeat(d.length);return c=d.start+d.length,_+y+T},"");throw new v(`Path parameters result in path with invalid segments:
71
+ ${s.map(_=>_.error).join(`
72
+ `)}
73
+ ${i}
74
+ ${m}`)}return i},p=bm(su);var zt=class extends h{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,N,{query:r,...n,__security:{bearerAuth:!0}})}};function to(t){return t!==void 0&&"function"in t&&t.function!==void 0}function iu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function ro(t){return t?.$brand==="auto-parseable-response-format"}function Dt(t){return t?.$brand==="auto-parseable-tool"}function au(t,e){return!e||!Ri(e)?{...t,choices:t.choices.map(r=>(uu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:no(t,e)}function no(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Pr;if(n.finish_reason==="content_filter")throw new Sr;return uu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>vm(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Tm(e,n.message.content):null}}});return{...t,choices:r}}function Tm(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function vm(t,e){let r=t.tools?.find(n=>to(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Dt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function lu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>to(n)&&n.function?.name===e.function.name);return to(r)&&(Dt(r)||r?.function.strict||!1)}function Ri(t){return ro(t.response_format)?!0:t.tools?.some(e=>Dt(e)||e.type==="function"&&e.function.strict===!0)??!1}function uu(t){for(let e of t||[])if(e.type!=="function")throw new v(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function cu(t){for(let e of t??[]){if(e.type!=="function")throw new v(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new v(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Nr=t=>t?.role==="assistant",Ni=t=>t?.role==="tool";var $i,ss,is,oo,so,as,io,Xe,ao,ls,us,$r,pu,At=class{constructor(){$i.add(this),this.controller=new AbortController,ss.set(this,void 0),is.set(this,()=>{}),oo.set(this,()=>{}),so.set(this,void 0),as.set(this,()=>{}),io.set(this,()=>{}),Xe.set(this,{}),ao.set(this,!1),ls.set(this,!1),us.set(this,!1),$r.set(this,!1),O(this,ss,new Promise((e,r)=>{O(this,is,e,"f"),O(this,oo,r,"f")}),"f"),O(this,so,new Promise((e,r)=>{O(this,as,e,"f"),O(this,io,r,"f")}),"f"),g(this,ss,"f").catch(()=>{}),g(this,so,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},g(this,$i,"m",pu).bind(this))},0)}_connected(){this.ended||(g(this,is,"f").call(this),this._emit("connect"))}get ended(){return g(this,ao,"f")}get errored(){return g(this,ls,"f")}get aborted(){return g(this,us,"f")}abort(){this.controller.abort()}on(e,r){return(g(this,Xe,"f")[e]||(g(this,Xe,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=g(this,Xe,"f")[e];if(!n)return this;let o=n.findIndex(s=>s.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(g(this,Xe,"f")[e]||(g(this,Xe,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{O(this,$r,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){O(this,$r,!0,"f"),await g(this,so,"f")}_emit(e,...r){if(g(this,ao,"f"))return;e==="end"&&(O(this,ao,!0,"f"),g(this,as,"f").call(this));let n=g(this,Xe,"f")[e];if(n&&(g(this,Xe,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!g(this,$r,"f")&&!n?.length&&Promise.reject(o),g(this,oo,"f").call(this,o),g(this,io,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!g(this,$r,"f")&&!n?.length&&Promise.reject(o),g(this,oo,"f").call(this,o),g(this,io,"f").call(this,o),this._emit("end")}}_emitFinal(){}};ss=new WeakMap,is=new WeakMap,oo=new WeakMap,so=new WeakMap,as=new WeakMap,io=new WeakMap,Xe=new WeakMap,ao=new WeakMap,ls=new WeakMap,us=new WeakMap,$r=new WeakMap,$i=new WeakSet,pu=function(e){if(O(this,ls,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new G),e instanceof G)return O(this,us,!0,"f"),this._emit("abort",e);if(e instanceof v)return this._emit("error",e);if(e instanceof Error){let r=new v(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new v(String(e)))};function mu(t){return typeof t.parse=="function"}var pe,ji,cs,Li,zi,Di,du,fu,Cm=10,jr=class extends At{constructor(){super(...arguments),pe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),Ni(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Nr(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new v("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),g(this,pe,"m",ji).call(this)}async finalMessage(){return await this.done(),g(this,pe,"m",cs).call(this)}async finalFunctionToolCall(){return await this.done(),g(this,pe,"m",Li).call(this)}async finalFunctionToolCallResult(){return await this.done(),g(this,pe,"m",zi).call(this)}async totalUsage(){return await this.done(),g(this,pe,"m",Di).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=g(this,pe,"m",cs).call(this);r&&this._emit("finalMessage",r);let n=g(this,pe,"m",ji).call(this);n&&this._emit("finalContent",n);let o=g(this,pe,"m",Li).call(this);o&&this._emit("finalFunctionToolCall",o);let s=g(this,pe,"m",zi).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",g(this,pe,"m",Di).call(this))}async _createChatCompletion(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),g(this,pe,"m",du).call(this,r);let s=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(no(s,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let o="tool",{tool_choice:s="auto",stream:i,...a}=r,u=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:l=Cm}=n||{},c=r.tools.map(d=>{if(Dt(d)){if(!d.$callback)throw new v("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:d.$callback,name:d.function.name,description:d.function.description||"",parameters:d.function.parameters,parse:d.$parseRaw,strict:!0}}}return d}),m={};for(let d of c)d.type==="function"&&(m[d.function.name||d.function.function.name]=d.function);let _="tools"in r?c.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description,strict:d.function.strict}}:d):void 0;for(let d of r.messages)this._addMessage(d,!1);for(let d=0;d<l;++d){let T=(await this._createChatCompletion(e,{...a,tool_choice:s,tools:_,messages:[...this.messages]},n)).choices[0]?.message;if(!T)throw new v("missing message in ChatCompletion response");if(!T.tool_calls?.length)return;for(let $ of T.tool_calls){if($.type!=="function")continue;let f=$.id,{name:A,arguments:C}=$.function,z=m[A];if(z){if(u&&u!==A){let M=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:o,tool_call_id:f,content:M});continue}}else{let M=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(m).map(x=>JSON.stringify(x)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:f,content:M});continue}let J;try{J=mu(z)?await z.parse(C):C}catch(M){let x=M instanceof Error?M.message:String(M);this._addMessage({role:o,tool_call_id:f,content:x});continue}let B=await z.function(J,this),U=g(this,pe,"m",fu).call(this,B);if(this._addMessage({role:o,tool_call_id:f,content:U}),u)return}}}};pe=new WeakSet,ji=function(){return g(this,pe,"m",cs).call(this).content??null},cs=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Nr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new v("stream ended without producing a ChatCompletionMessage with role=assistant")},Li=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Nr(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},zi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Ni(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(o=>o.type==="function"&&o.id===r.tool_call_id)))return r.content}},Di=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},du=function(e){if(e.n!=null&&e.n>1)throw new v("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},fu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var lo=class t extends jr{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),Nr(e)&&e.content&&this._emit("content",e.content)}};var ne={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},Ui=class extends Error{},Fi=class extends Error{};function km(t,e=ne.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Om(t.trim(),e)}var Om=(t,e)=>{let r=t.length,n=0,o=_=>{throw new Ui(`${_} at position ${n}`)},s=_=>{throw new Fi(`${_} at position ${n}`)},i=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||ne.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ne.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ne.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ne.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ne.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ne.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):c()),a=()=>{let _=n,d=!1;for(n++;n<r&&(t[n]!=='"'||d&&t[n-1]==="\\");)d=t[n]==="\\"?!d:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(_,++n-Number(d)))}catch(y){s(String(y))}else if(ne.STR&e)try{return JSON.parse(t.substring(_,n-Number(d))+'"')}catch{return JSON.parse(t.substring(_,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,m();let _={};try{for(;t[n]!=="}";){if(m(),n>=r&&ne.OBJ&e)return _;let d=a();m(),n++;try{let y=i();Object.defineProperty(_,d,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(ne.OBJ&e)return _;throw y}m(),t[n]===","&&n++}}catch{if(ne.OBJ&e)return _;o("Expected '}' at end of object")}return n++,_},l=()=>{n++;let _=[];try{for(;t[n]!=="]";)_.push(i()),m(),t[n]===","&&n++}catch{if(ne.ARR&e)return _;o("Expected ']' at end of array")}return n++,_},c=()=>{if(n===0){t==="-"&&ne.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(d){if(ne.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(d))}}let _=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ne.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(_,n))}catch{t.substring(_,n)==="-"&&ne.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(_,t.lastIndexOf("e")))}catch(y){s(String(y))}}},m=()=>{for(;n<r&&`
75
+ \r `.includes(t[n]);)n++};return i()},Bi=t=>km(t,ne.ALL^ne.NUM);var te,Qe,Lr,bt,Ki,ps,Wi,Hi,qi,ms,Ji,hu,Ut=class t extends jr{constructor(e){super(),te.add(this),Qe.set(this,void 0),Lr.set(this,void 0),bt.set(this,void 0),O(this,Qe,e,"f"),O(this,Lr,[],"f")}get currentChatCompletionSnapshot(){return g(this,bt,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),g(this,te,"m",Ki).call(this);let s=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let i of s)g(this,te,"m",Wi).call(this,i);if(s.controller.signal?.aborted)throw new G;return this._addChatCompletion(g(this,te,"m",ms).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),g(this,te,"m",Ki).call(this),this._connected();let o=Ke.fromReadableStream(e,this.controller),s;for await(let i of o)s&&s!==i.id&&this._addChatCompletion(g(this,te,"m",ms).call(this)),g(this,te,"m",Wi).call(this,i),s=i.id;if(o.controller.signal?.aborted)throw new G;return this._addChatCompletion(g(this,te,"m",ms).call(this))}[(Qe=new WeakMap,Lr=new WeakMap,bt=new WeakMap,te=new WeakSet,Ki=function(){this.ended||O(this,bt,void 0,"f")},ps=function(r){let n=g(this,Lr,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},g(this,Lr,"f")[r.index]=n,n)},Wi=function(r){if(this.ended)return;let n=g(this,te,"m",hu).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index];o.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.delta.content,s.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),o.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let i=g(this,te,"m",ps).call(this,s);s.finish_reason&&(g(this,te,"m",qi).call(this,s),i.current_tool_call_index!=null&&g(this,te,"m",Hi).call(this,s,i.current_tool_call_index));for(let a of o.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(g(this,te,"m",qi).call(this,s),i.current_tool_call_index!=null&&g(this,te,"m",Hi).call(this,s,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of o.delta.tool_calls??[]){let u=s.message.tool_calls?.[a.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:a.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(u?.type,void 0))}}},Hi=function(r,n){if(g(this,te,"m",ps).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let i=g(this,Qe,"f")?.tools?.find(a=>to(a)&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Dt(i)?i.$parseRaw(s.function.arguments):i?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},qi=function(r){let n=g(this,te,"m",ps).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=g(this,te,"m",Ji).call(this);this._emit("content.done",{content:r.message.content,parsed:o?o.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},ms=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let r=g(this,bt,"f");if(!r)throw new v("request ended without sending any chunks");return O(this,bt,void 0,"f"),O(this,Lr,[],"f"),Pm(r,g(this,Qe,"f"))},Ji=function(){let r=g(this,Qe,"f")?.response_format;return ro(r)?r:null},hu=function(r){var n,o,s,i;let a=g(this,bt,"f"),{choices:u,...l}=r;a?Object.assign(a,l):a=O(this,bt,{...l,choices:[]},"f");for(let{delta:c,finish_reason:m,index:_,logprobs:d=null,...y}of r.choices){let T=a.choices[_];if(T||(T=a.choices[_]={finish_reason:m,index:_,message:{},logprobs:d,...y}),d)if(!T.logprobs)T.logprobs=Object.assign({},d);else{let{content:B,refusal:U,...M}=d;Object.assign(T.logprobs,M),B&&((n=T.logprobs).content??(n.content=[]),T.logprobs.content.push(...B)),U&&((o=T.logprobs).refusal??(o.refusal=[]),T.logprobs.refusal.push(...U))}if(m&&(T.finish_reason=m,g(this,Qe,"f")&&Ri(g(this,Qe,"f")))){if(m==="length")throw new Pr;if(m==="content_filter")throw new Sr}if(Object.assign(T,y),!c)continue;let{content:$,refusal:f,function_call:A,role:C,tool_calls:z,...J}=c;if(Object.assign(T.message,J),f&&(T.message.refusal=(T.message.refusal||"")+f),C&&(T.message.role=C),A&&(T.message.function_call?(A.name&&(T.message.function_call.name=A.name),A.arguments&&((s=T.message.function_call).arguments??(s.arguments=""),T.message.function_call.arguments+=A.arguments)):T.message.function_call=A),$&&(T.message.content=(T.message.content||"")+$,!T.message.refusal&&g(this,te,"m",Ji).call(this)&&(T.message.parsed=Bi(T.message.content))),z){T.message.tool_calls||(T.message.tool_calls=[]);for(let{index:B,id:U,type:M,function:x,...k}of z){let j=(i=T.message.tool_calls)[B]??(i[B]={});Object.assign(j,k),U&&(j.id=U),M&&(j.type=M),x&&(j.function??(j.function={name:x.name??"",arguments:""})),x?.name&&(j.function.name=x.name),x?.arguments&&(j.function.arguments+=x.arguments,lu(g(this,Qe,"f"),j)&&(j.function.parsed_arguments=Bi(j.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ke(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Pm(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:i,...a}=t,u={...a,id:r,choices:n.map(({message:l,finish_reason:c,index:m,logprobs:_,...d})=>{if(!c)throw new v(`missing finish_reason for choice ${m}`);let{content:y=null,function_call:T,tool_calls:$,...f}=l,A=l.role;if(!A)throw new v(`missing role for choice ${m}`);if(T){let{arguments:C,name:z}=T;if(C==null)throw new v(`missing function_call.arguments for choice ${m}`);if(!z)throw new v(`missing function_call.name for choice ${m}`);return{...d,message:{content:y,function_call:{arguments:C,name:z},role:A,refusal:l.refusal??null},finish_reason:c,index:m,logprobs:_}}return $?{...d,index:m,finish_reason:c,logprobs:_,message:{...f,role:A,content:y,refusal:l.refusal??null,tool_calls:$.map((C,z)=>{let{function:J,type:B,id:U,...M}=C,{arguments:x,name:k,...j}=J||{};if(U==null)throw new v(`missing choices[${m}].tool_calls[${z}].id
76
+ ${ds(t)}`);if(B==null)throw new v(`missing choices[${m}].tool_calls[${z}].type
77
+ ${ds(t)}`);if(k==null)throw new v(`missing choices[${m}].tool_calls[${z}].function.name
78
+ ${ds(t)}`);if(x==null)throw new v(`missing choices[${m}].tool_calls[${z}].function.arguments
79
+ ${ds(t)}`);return{...M,id:U,type:B,function:{...j,name:k,arguments:x}}})}}:{...d,message:{...f,content:y,role:A,refusal:l.refusal??null},finish_reason:c,index:m,logprobs:_}}),created:o,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return au(u,e)}function ds(t){return JSON.stringify(t)}var uo=class t extends Ut{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,s)),o}};var et=class extends h{constructor(){super(...arguments),this.messages=new zt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return cu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>no(n,e))}runTools(e,r){return e.stream?uo.runTools(this._client,e,r):lo.runTools(this._client,e,r)}stream(e,r){return Ut.createChatCompletion(this._client,e,r)}};et.Messages=zt;var It=class extends h{constructor(){super(...arguments),this.completions=new et(this._client)}};It.Completions=et;var zr=class extends h{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",N,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Dr=class extends h{list(e={},r){return this._client.getAPIList("/organization/audit_logs",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=class extends h{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",ie,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",ie,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Fr=class extends h{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends h{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",X,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends h{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends h{create(e,r,n){return this._client.post(p`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/roles`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends h{create(e,r,n){return this._client.post(p`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/users`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var xt=class extends h{constructor(){super(...arguments),this.users=new Hr(this._client),this.roles=new Wr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",X,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};xt.Users=Hr;xt.Roles=Wr;var qr=class extends h{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/api_keys`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends h{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/activate`,ie,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/deactivate`,ie,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends h{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends h{create(e,r,n){return this._client.post(p`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/projects/${e}/roles`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends h{create(e,r,n){return this._client.post(p`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/service_accounts`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends h{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/groups/${e}/roles`,X,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends h{constructor(){super(...arguments),this.roles=new Yr(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/groups`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Ft.Roles=Yr;var Xr=class extends h{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/users/${e}/roles`,X,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Bt=class extends h{constructor(){super(...arguments),this.roles=new Xr(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/users`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Bt.Roles=Xr;var we=class extends h{constructor(){super(...arguments),this.users=new Bt(this._client),this.serviceAccounts=new Gr(this._client),this.apiKeys=new qr(this._client),this.rateLimits=new Zr(this._client),this.groups=new Ft(this._client),this.roles=new Vr(this._client),this.certificates=new Jr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};we.Users=Bt;we.ServiceAccounts=Gr;we.APIKeys=qr;we.RateLimits=Zr;we.Groups=Ft;we.Roles=Vr;we.Certificates=Jr;var Qr=class extends h{create(e,r,n){return this._client.post(p`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/users/${e}/roles`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends h{constructor(){super(...arguments),this.roles=new Qr(this._client)}retrieve(e,r){return this._client.get(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Kt.Roles=Qr;var me=class extends h{constructor(){super(...arguments),this.auditLogs=new Dr(this._client),this.adminAPIKeys=new zr(this._client),this.usage=new Kr(this._client),this.invites=new Fr(this._client),this.users=new Kt(this._client),this.groups=new xt(this._client),this.roles=new Br(this._client),this.certificates=new Ur(this._client),this.projects=new we(this._client)}};me.AuditLogs=Dr;me.AdminAPIKeys=zr;me.Usage=Kr;me.Invites=Fr;me.Users=Kt;me.Groups=xt;me.Roles=Br;me.Certificates=Ur;me.Projects=we;var Tt=class extends h{constructor(){super(...arguments),this.organization=new me(this._client)}};Tt.Organization=me;var gu=Symbol("brand.privateNullableHeaders");function*Qm(t){if(!t)return;if(gu in t){let{values:n,nulls:o}=t;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():fi(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=fi(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var I=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,i]of Qm(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),r.add(a)):(e.append(s,i),r.delete(a))}}return{[gu]:!0,values:e,nulls:r}};var en=class extends h{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:I([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var tn=class extends h{create(e,r){return this._client.post("/audio/transcriptions",ae({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var rn=class extends h{create(e,r){return this._client.post("/audio/translations",ae({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var We=class extends h{constructor(){super(...arguments),this.transcriptions=new tn(this._client),this.translations=new rn(this._client),this.speech=new en(this._client)}};We.Transcriptions=tn;We.Translations=rn;We.Speech=en;var Wt=class extends h{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",N,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var nn=class extends h{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/assistants/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/assistants/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",N,{query:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/assistants/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var on=class extends h{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var sn=class extends h{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var vt=class extends h{constructor(){super(...arguments),this.sessions=new on(this._client),this.transcriptionSessions=new sn(this._client)}};vt.Sessions=on;vt.TranscriptionSessions=sn;var an=class extends h{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/chatkit/sessions/${e}/cancel`,{...r,headers:I([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var ln=class extends h{retrieve(e,r){return this._client.get(p`/chatkit/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",W,{query:e,...r,headers:I([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chatkit/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(p`/chatkit/threads/${e}/items`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Ct=class extends h{constructor(){super(...arguments),this.sessions=new an(this._client),this.threads=new ln(this._client)}};Ct.Sessions=an;Ct.Threads=ln;var un=class extends h{create(e,r,n){return this._client.post(p`/threads/${e}/messages`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/messages/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/messages/${e}`,{body:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/messages`,N,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(p`/threads/${o}/messages/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var cn=class extends h{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:i,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(p`/threads/${o}/runs/${e}/steps`,N,{query:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var _u=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var He=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var oe,qt,Zi,qe,fs,Oe,Jt,pn,Ht,_s,Ae,hs,gs,mo,co,po,yu,wu,Au,bu,Iu,xu,Tu,tt=class extends At{constructor(){super(...arguments),oe.add(this),Zi.set(this,[]),qe.set(this,{}),fs.set(this,{}),Oe.set(this,void 0),Jt.set(this,void 0),pn.set(this,void 0),Ht.set(this,void 0),_s.set(this,void 0),Ae.set(this,void 0),hs.set(this,void 0),gs.set(this,void 0),mo.set(this,void 0)}[(Zi=new WeakMap,qe=new WeakMap,fs=new WeakMap,Oe=new WeakMap,Jt=new WeakMap,pn=new WeakMap,Ht=new WeakMap,_s=new WeakMap,Ae=new WeakMap,hs=new WeakMap,gs=new WeakMap,mo=new WeakMap,oe=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new qt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=Ke.fromReadableStream(e,this.controller);for await(let s of o)g(this,oe,"m",co).call(this,s);if(o.controller.signal?.aborted)throw new G;return this._addRun(g(this,oe,"m",po).call(this))}toReadableStream(){return new Ke(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new qt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...o,signal:this.controller.signal});this._connected();for await(let u of a)g(this,oe,"m",co).call(this,u);if(a.controller.signal?.aborted)throw new G;return this._addRun(g(this,oe,"m",po).call(this))}static createThreadAssistantStream(e,r,n){let o=new qt;return o._run(()=>o._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new qt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return g(this,hs,"f")}currentRun(){return g(this,gs,"f")}currentMessageSnapshot(){return g(this,Oe,"f")}currentRunStepSnapshot(){return g(this,mo,"f")}async finalRunSteps(){return await this.done(),Object.values(g(this,qe,"f"))}async finalMessages(){return await this.done(),Object.values(g(this,fs,"f"))}async finalRun(){if(await this.done(),!g(this,Jt,"f"))throw Error("Final run was not received.");return g(this,Jt,"f")}async _createThreadAssistantStream(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},i=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of i)g(this,oe,"m",co).call(this,a);if(i.controller.signal?.aborted)throw new G;return this._addRun(g(this,oe,"m",po).call(this))}async _createAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...o,signal:this.controller.signal});this._connected();for await(let u of a)g(this,oe,"m",co).call(this,u);if(a.controller.signal?.aborted)throw new G;return this._addRun(g(this,oe,"m",po).call(this))}static accumulateDelta(e,r){for(let[n,o]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=o;continue}let s=e[n];if(s==null){e[n]=o;continue}if(n==="index"||n==="type"){e[n]=o;continue}if(typeof s=="string"&&typeof o=="string")s+=o;else if(typeof s=="number"&&typeof o=="number")s+=o;else if(Zn(s)&&Zn(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(i=>typeof i=="string"||typeof i=="number")){s.push(...o);continue}for(let i of o){if(!Zn(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let u=s[a];u==null?s.push(i):s[a]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};qt=tt,co=function(e){if(!this.ended)switch(O(this,hs,e,"f"),g(this,oe,"m",Au).call(this,e),e.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":g(this,oe,"m",Tu).call(this,e);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":g(this,oe,"m",wu).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":g(this,oe,"m",yu).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},po=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");if(!g(this,Jt,"f"))throw Error("Final run has not been received");return g(this,Jt,"f")},yu=function(e){let[r,n]=g(this,oe,"m",Iu).call(this,e,g(this,Oe,"f"));O(this,Oe,r,"f"),g(this,fs,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,i=r.content[o.index];if(i&&i.type=="text")this._emit("textDelta",s,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=g(this,pn,"f")){if(g(this,Ht,"f"))switch(g(this,Ht,"f").type){case"text":this._emit("textDone",g(this,Ht,"f").text,g(this,Oe,"f"));break;case"image_file":this._emit("imageFileDone",g(this,Ht,"f").image_file,g(this,Oe,"f"));break}O(this,pn,o.index,"f")}O(this,Ht,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(g(this,pn,"f")!==void 0){let o=e.data.content[g(this,pn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,g(this,Oe,"f"));break;case"text":this._emit("textDone",o.text,g(this,Oe,"f"));break}}g(this,Oe,"f")&&this._emit("messageDone",e.data),O(this,Oe,void 0,"f")}},wu=function(e){let r=g(this,oe,"m",bu).call(this,e);switch(O(this,mo,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==g(this,_s,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(g(this,Ae,"f")&&this._emit("toolCallDone",g(this,Ae,"f")),O(this,_s,s.index,"f"),O(this,Ae,r.step_details.tool_calls[s.index],"f"),g(this,Ae,"f")&&this._emit("toolCallCreated",g(this,Ae,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":O(this,mo,void 0,"f"),e.data.step_details.type=="tool_calls"&&g(this,Ae,"f")&&(this._emit("toolCallDone",g(this,Ae,"f")),O(this,Ae,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Au=function(e){g(this,Zi,"f").push(e),this._emit("event",e)},bu=function(e){switch(e.event){case"thread.run.step.created":return g(this,qe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=g(this,qe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=qt.accumulateDelta(r,n.delta);g(this,qe,"f")[e.data.id]=o}return g(this,qe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":g(this,qe,"f")[e.data.id]=e.data;break}if(g(this,qe,"f")[e.data.id])return g(this,qe,"f")[e.data.id];throw new Error("No snapshot available")},Iu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let i=r.content[s.index];r.content[s.index]=g(this,oe,"m",xu).call(this,s,i)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},xu=function(e,r){return qt.accumulateDelta(r,e)},Tu=function(e){switch(O(this,gs,e.data,"f"),e.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":O(this,Jt,e.data,"f"),g(this,Ae,"f")&&(this._emit("toolCallDone",g(this,Ae,"f")),O(this,Ae,void 0,"f"));break;case"thread.run.cancelling":break}};var Zt=class extends h{constructor(){super(...arguments),this.steps=new cn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/runs/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}`,{body:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/runs`,N,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(p`/threads/${o}/runs/${e}/cancel`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return tt.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=I([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(a=l)}}await Fe(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return tt.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return tt.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Zt.Steps=cn;var kt=class extends h{constructor(){super(...arguments),this.runs=new Zt(this._client),this.messages=new un(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/threads/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return tt.createThreadAssistantStream(e,this._client.beta.threads,r)}};kt.Runs=Zt;kt.Messages=un;var Pe=class extends h{constructor(){super(...arguments),this.realtime=new vt(this._client),this.chatkit=new Ct(this._client),this.assistants=new nn(this._client),this.threads=new kt(this._client)}};Pe.Realtime=vt;Pe.ChatKit=Ct;Pe.Assistants=nn;Pe.Threads=kt;var Vt=class extends h{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var mn=class extends h{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}/content`,{...n,headers:I([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Gt=class extends h{constructor(){super(...arguments),this.content=new mn(this._client)}create(e,r,n){return this._client.post(p`/containers/${e}/files`,wt({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/containers/${e}/files`,N,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(p`/containers/${o}/files/${e}`,{...n,headers:I([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Gt.Content=mn;var Ot=class extends h{constructor(){super(...arguments),this.files=new Gt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/containers/${e}`,{...r,headers:I([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Ot.Files=Gt;var dn=class extends h{create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/conversations/${e}/items`,{query:{include:o},body:s,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{conversation_id:o,...s}=r;return this._client.get(p`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/conversations/${e}/items`,W,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(p`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var Pt=class extends h{constructor(){super(...arguments),this.items=new dn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};Pt.Items=dn;var Yt=class extends h{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&Y(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:o},...r,__security:{bearerAuth:!0}});return n?s:(Y(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let u=a.embedding;a.embedding=_u(u)}),i)))}};var fn=class extends h{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(p`/evals/${o}/runs/${s}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r,n){let{eval_id:o,...s}=r;return this._client.getAPIList(p`/evals/${o}/runs/${e}/output_items`,N,{query:s,...n,__security:{bearerAuth:!0}})}};var Xt=class extends h{constructor(){super(...arguments),this.outputItems=new fn(this._client)}create(e,r,n){return this._client.post(p`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/evals/${e}/runs`,N,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Xt.OutputItems=fn;var St=class extends h{constructor(){super(...arguments),this.runs=new Xt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};St.Runs=Xt;var Qt=class extends h{create(e,r){return this._client.post("/files",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(p`/files/${e}/content`,{...r,headers:I([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),i=await this.retrieve(e);for(;!i.status||!o.has(i.status);)if(await Fe(r),i=await this.retrieve(e),Date.now()-s>n)throw new De({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var hn=class extends h{};var gn=class extends h{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var er=class extends h{constructor(){super(...arguments),this.graders=new gn(this._client)}};er.Graders=gn;var _n=class extends h{create(e,r,n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,ie,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(p`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var tr=class extends h{constructor(){super(...arguments),this.permissions=new _n(this._client)}};tr.Permissions=_n;var yn=class extends h{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,N,{query:r,...n,__security:{bearerAuth:!0}})}};var rr=class extends h{constructor(){super(...arguments),this.checkpoints=new yn(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",N,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/events`,N,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};rr.Checkpoints=yn;var Se=class extends h{constructor(){super(...arguments),this.methods=new hn(this._client),this.jobs=new rr(this._client),this.checkpoints=new tr(this._client),this.alpha=new er(this._client)}};Se.Methods=hn;Se.Jobs=rr;Se.Checkpoints=tr;Se.Alpha=er;var wn=class extends h{};var Et=class extends h{constructor(){super(...arguments),this.graderModels=new wn(this._client)}};Et.GraderModels=wn;var nr=class extends h{createVariation(e,r){return this._client.post("/images/variations",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",ae({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var or=class extends h{retrieve(e,r){return this._client.get(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",ie,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var sr=class extends h{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var An=class extends h{accept(e,r,n){return this._client.post(p`/realtime/calls/${e}/accept`,{body:r,...n,headers:I([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(p`/realtime/calls/${e}/hangup`,{...r,headers:I([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(p`/realtime/calls/${e}/refer`,{body:r,...n,headers:I([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(p`/realtime/calls/${e}/reject`,{body:r,...n,headers:I([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var bn=class extends h{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var rt=class extends h{constructor(){super(...arguments),this.clientSecrets=new bn(this._client),this.calls=new An(this._client)}};rt.ClientSecrets=bn;rt.Calls=An;function vu(t,e){return!e||!Sd(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:Vi(t,e)}function Vi(t,e){let r=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:Rd(e,o)};if(o.type==="message"){let s=o.content.map(i=>i.type==="output_text"?{...i,parsed:Pd(e,i.text)}:i);return{...o,content:s}}return o}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||ys(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let s of o.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function Pd(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Sd(t){return!!ro(t.text?.format)}function Ed(t){return t?.$brand==="auto-parseable-tool"}function Md(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Rd(t,e){let r=Md(t.tools??[],e.name);return{...e,...e,parsed_arguments:Ed(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function ys(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var In,ws,Mt,As,Cu,ku,Ou,Pu,bs=class t extends At{constructor(e){super(),In.add(this),ws.set(this,void 0),Mt.set(this,void 0),As.set(this,void 0),O(this,ws,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),g(this,In,"m",Cu).call(this);let s,i=null;"response_id"in r?(s=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=r.starting_after??null):s=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)g(this,In,"m",ku).call(this,a,i);if(s.controller.signal?.aborted)throw new G;return g(this,In,"m",Ou).call(this)}[(ws=new WeakMap,Mt=new WeakMap,As=new WeakMap,In=new WeakSet,Cu=function(){this.ended||O(this,Mt,void 0,"f")},ku=function(r,n){if(this.ended)return;let o=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},s=g(this,In,"m",Pu).call(this,r);switch(o("event",r),r.type){case"response.output_text.delta":{let i=s.output[r.output_index];if(!i)throw new v(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new v(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new v(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=s.output[r.output_index];if(!i)throw new v(`missing output at index ${r.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:o(r.type,r);break}},Ou=function(){if(this.ended)throw new v("stream has ended, this shouldn't happen");let r=g(this,Mt,"f");if(!r)throw new v("request ended without sending any events");O(this,Mt,void 0,"f");let n=Nd(r,g(this,ws,"f"));return O(this,As,n,"f"),n},Pu=function(r){let n=g(this,Mt,"f");if(!n){if(r.type!=="response.created")throw new v(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=O(this,Mt,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let o=n.output[r.output_index];if(!o)throw new v(`missing output at index ${r.output_index}`);let s=o.type,i=r.part;s==="message"&&i.type!=="reasoning_text"?o.content.push(i):s==="reasoning"&&i.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(i));break}case"response.output_text.delta":{let o=n.output[r.output_index];if(!o)throw new v(`missing output at index ${r.output_index}`);if(o.type==="message"){let s=o.content[r.content_index];if(!s)throw new v(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new v(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta}break}case"response.function_call_arguments.delta":{let o=n.output[r.output_index];if(!o)throw new v(`missing output at index ${r.output_index}`);o.type==="function_call"&&(o.arguments+=r.delta);break}case"response.reasoning_text.delta":{let o=n.output[r.output_index];if(!o)throw new v(`missing output at index ${r.output_index}`);if(o.type==="reasoning"){let s=o.content?.[r.content_index];if(!s)throw new v(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new v(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{O(this,Mt,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=g(this,As,"f");if(!e)throw new v("stream ended without producing a ChatCompletion");return e}};function Nd(t,e){return vu(t,e)}var xn=class extends h{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,N,{query:r,...n,__security:{bearerAuth:!0}})}};var Tn=class extends h{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var nt=class extends h{constructor(){super(...arguments),this.inputItems=new xn(this._client),this.inputTokens=new Tn(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ys(n),n))}retrieve(e,r={},n){return this._client.get(p`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&ys(o),o))}delete(e,r){return this._client.delete(p`/responses/${e}`,{...r,headers:I([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Vi(n,e))}stream(e,r){return bs.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(p`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};nt.InputItems=xn;nt.InputTokens=Tn;var vn=class extends h{retrieve(e,r){return this._client.get(p`/skills/${e}/content`,{...r,headers:I([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Cn=class extends h{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}/content`,{...n,headers:I([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ir=class extends h{constructor(){super(...arguments),this.content=new Cn(this._client)}create(e,r={},n){return this._client.post(p`/skills/${e}/versions`,wt({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/skills/${e}/versions`,N,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};ir.Content=Cn;var ot=class extends h{constructor(){super(...arguments),this.content=new vn(this._client),this.versions=new ir(this._client)}create(e={},r){return this._client.post("/skills",wt({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",N,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};ot.Content=vn;ot.Versions=ir;var kn=class extends h{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,ae({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Rt=class extends h{constructor(){super(...arguments),this.parts=new kn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(p`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};Rt.Parts=kn;var Su=async t=>{let e=await Promise.allSettled(t),r=e.filter(o=>o.status==="rejected");if(r.length){for(let o of r)console.error(o.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let o of e)o.status==="fulfilled"&&n.push(o.value);return n};var On=class extends h{create(e,r,n){return this._client.post(p`/vector_stores/${e}/file_batches`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/file_batches/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(p`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(p`/vector_stores/${o}/file_batches/${e}/files`,N,{query:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=I([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(a=l)}}await Fe(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,i=Math.min(s,r.length),a=this._client,u=r.values(),l=[...n];async function c(_){for(let d of _){let y=await a.files.create({file:d,purpose:"assistants"},o);l.push(y.id)}}let m=Array(i).fill(u).map(c);return await Su(m),await this.createAndPoll(e,{file_ids:l})}};var Pn=class extends h{create(e,r,n){return this._client.post(p`/vector_stores/${e}/files`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/files/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(p`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/vector_stores/${e}/files`,N,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(p`/vector_stores/${o}/files/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=I([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),i=s.data;switch(i.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(a=l)}}await Fe(a);break;case"failed":case"completed":return i}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(p`/vector_stores/${o}/files/${e}/content`,ie,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var st=class extends h{constructor(){super(...arguments),this.files=new Pn(this._client),this.fileBatches=new On(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/vector_stores/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/vector_stores/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",N,{query:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/vector_stores/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(p`/vector_stores/${e}/search`,ie,{body:r,method:"post",...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};st.Files=Pn;st.FileBatches=On;var ar=class extends h{create(e,r){return this._client.post("/videos",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",W,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(p`/videos/${e}/content`,{query:r,...n,headers:I([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",ae({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(p`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(p`/videos/${e}/remix`,wt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Sn,Eu,Is,lr=class extends h{constructor(){super(...arguments),Sn.add(this)}async unwrap(e,r,n=this._client.webhookSecret,o=300){return await this.verifySignature(e,r,n,o),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");g(this,Sn,"m",Eu).call(this,n);let s=I([r]).values,i=g(this,Sn,"m",Is).call(this,s,"webhook-signature"),a=g(this,Sn,"m",Is).call(this,s,"webhook-timestamp"),u=g(this,Sn,"m",Is).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new Ue("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-l>o)throw new Ue("Webhook timestamp is too old");if(l>c+o)throw new Ue("Webhook timestamp is too new");let m=i.split(" ").map(T=>T.startsWith("v1,")?T.substring(3):T),_=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=u?`${u}.${a}.${e}`:`${a}.${e}`,y=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let T of m)try{let $=Buffer.from(T,"base64");if(await crypto.subtle.verify("HMAC",y,$,new TextEncoder().encode(d)))return}catch{continue}throw new Ue("The given webhook signature does not match the expected signature")}};Sn=new WeakSet,Eu=function(e){if(typeof e!="string"||e.length===0)throw new 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")},Is=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Gi,Yi,xs,Mu,Wd="workload-identity-auth",P=class{constructor({baseURL:e=He("OPENAI_BASE_URL"),apiKey:r=He("OPENAI_API_KEY")??null,adminAPIKey:n=He("OPENAI_ADMIN_KEY")??null,organization:o=He("OPENAI_ORG_ID")??null,project:s=He("OPENAI_PROJECT_ID")??null,webhookSecret:i=He("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:a,...u}={}){Gi.add(this),xs.set(this,void 0),this.completions=new Vt(this),this.chat=new It(this),this.embeddings=new Yt(this),this.files=new Qt(this),this.images=new nr(this),this.audio=new We(this),this.moderations=new sr(this),this.models=new or(this),this.fineTuning=new Se(this),this.graders=new Et(this),this.vectorStores=new st(this),this.webhooks=new lr(this),this.beta=new Pe(this),this.batches=new Wt(this),this.uploads=new Rt(this),this.admin=new Tt(this),this.responses=new nt(this),this.realtime=new rt(this),this.conversations=new Pt(this),this.evals=new St(this),this.containers=new Ot(this),this.skills=new ot(this),this.videos=new ar(this);let l={apiKey:r,adminAPIKey:n,organization:o,project:s,webhookSecret:i,workloadIdentity:a,...u,baseURL:e||"https://api.openai.com/v1"};if(r&&a)throw new v("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!a)throw new v("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&jl())throw new v(`It looks like you're running in a browser-like environment.
80
+
81
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
82
+ If you understand the risks and have appropriate mitigations in place,
83
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
84
+
85
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
86
+
87
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
88
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??Yi.DEFAULT_TIMEOUT,this.logger=l.logger??console;let c="warn";this.logLevel=c,this.logLevel=Ci(l.logLevel,"ClientOptions.logLevel",this)??Ci(He("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Go(),O(this,xs,Dl,"f");let m=He("OPENAI_CUSTOM_HEADERS");if(m){let _={};for(let d of m.split(`
89
+ `)){let y=d.indexOf(":");y>=0&&(_[d.substring(0,y).trim()]=d.substring(y+1).trim())}l.defaultHeaders=I([_,l.defaultHeaders])}this._options=l,a&&(this._workloadIdentityAuth=new ns(a,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=o,this.project=s,this.webhookSecret=i}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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return I([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return I([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return I([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return I([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Zl(e)}getUserAgent(){return`${this.constructor.name}/JS ${yt}`}defaultIdempotencyKey(){return`stainless-node-retry-${di()}`}makeStatusError(e,r,n,o){return V.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof v?n:new v(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new v(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!g(this,Gi,"m",Mu).call(this)&&n||this.baseURL,s=Pl(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!hi(i)||!hi(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Lt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:i,url:a,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(i,{url:a,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(Y(this).debug(`[${l}] sending request`,Ye({retryOfRequestLogID:n,method:o.method,url:a,options:o,headers:i.headers})),o.signal?.aborted)throw new G;let _=o.__security??{bearerAuth:!0},d=new AbortController,y=await this.fetchWithAuth(a,i,u,d,_).catch(qn),T=Date.now();if(y instanceof globalThis.Error){let A=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new G;let C=Hn(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(r)return Y(this).info(`[${l}] connection ${C?"timed out":"failed"} - ${A}`),Y(this).debug(`[${l}] connection ${C?"timed out":"failed"} (${A})`,Ye({retryOfRequestLogID:n,url:a,durationMs:T-m,message:y.message})),this.retryRequest(o,r,n??l);throw Y(this).info(`[${l}] connection ${C?"timed out":"failed"} - error; no more retries left`),Y(this).debug(`[${l}] connection ${C?"timed out":"failed"} (error; no more retries left)`,Ye({retryOfRequestLogID:n,url:a,durationMs:T-m,message:y.message})),y instanceof $t||y instanceof Jn?y:C?new De:new _t({cause:y})}let $=[...y.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,C])=>", "+A+": "+JSON.stringify(C)).join(""),f=`[${l}${c}${$}] ${i.method} ${a} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${T-m}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await yi(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let A=await this.shouldRetry(y);if(r&&A){let M=`retrying, ${r} attempts remaining`;return await yi(y.body),Y(this).info(`${f} - ${M}`),Y(this).debug(`[${l}] response error (${M})`,Ye({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:T-m})),this.retryRequest(o,r,n??l,y.headers)}let C=A?"error; no more retries left":"error; not retryable";Y(this).info(`${f} - ${C}`);let z=await y.text().catch(M=>qn(M).message),J=Ml(z),B=J?void 0:z;throw Y(this).debug(`[${l}] response error (${C})`,Ye({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:B,durationMs:Date.now()-m})),this.makeStatusError(y.status,J,B,y.headers)}return Y(this).info(f),Y(this).debug(`[${l}] response start`,Ye({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:T-m})),{response:y,options:o,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:m}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Xn(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let a=r.headers,u=a.get("Authorization");if(!u||u===`Bearer ${Wd}`){let l=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:i,...a}=r||{},u=this._makeAbort(o);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,m={signal:o.signal,...c?{duplex:"half"}:{},method:"GET",...a};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,i=o?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(s=u)}let a=o?.get("retry-after");if(a&&!s){let u=parseFloat(a);Number.isNaN(u)?s=Date.parse(a)-Date.now():s=u*1e3}if(s===void 0){let u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,u)}return await Fe(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,i=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:i,defaultBaseURL:a}=n,u=this.buildURL(s,i,a);"timeout"in n&&El("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:c,isStreamingBody:m}=this.buildBody({options:n});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let _=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:_,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let i=I([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ll(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=I([r]),o=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,s=!o&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||o?{bodyHeaders:void 0,body:e,isStreamingBody:!s}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Yo(e),isStreamingBody:!0}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...g(this,xs,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};Yi=P,xs=new WeakMap,Gi=new WeakSet,Mu=function(){return this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=Yi;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=v;P.APIError=V;P.APIConnectionError=_t;P.APIConnectionTimeoutError=De;P.APIUserAbortError=G;P.NotFoundError=Tr;P.ConflictError=vr;P.RateLimitError=kr;P.BadRequestError=br;P.AuthenticationError=Ir;P.InternalServerError=Or;P.PermissionDeniedError=xr;P.UnprocessableEntityError=Cr;P.InvalidWebhookSignatureError=Ue;P.toFile=eo;P.Completions=Vt;P.Chat=It;P.Embeddings=Yt;P.Files=Qt;P.Images=nr;P.Audio=We;P.Moderations=sr;P.Models=or;P.FineTuning=Se;P.Graders=Et;P.VectorStores=st;P.Webhooks=lr;P.Beta=Pe;P.Batches=Wt;P.Uploads=Rt;P.Admin=Tt;P.Responses=nt;P.Realtime=rt;P.Conversations=Pt;P.Evals=St;P.Containers=Ot;P.Skills=ot;P.Videos=ar;function Hd(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function Ee(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===De.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===G.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Hd(t)?e=wa.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Wn(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Wn(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Wn(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Wn(t,"MODEL_NOT_FOUND"):e=t,e}var Me=t=>t();function it(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function qd(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Qi(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Jd="LC_AUTOGENERATED";function En(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),Jd)}function at(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!vo.isInstance(t))throw new Error("Invalid generic chat message");return qd(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ru(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("codex"))}function lt(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((n||i)&&o&&e)return`${o}/${e}`;if((n||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function ea(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Nu(t){let e=Me(()=>{if(ea(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&ea(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,n])=>typeof n=="string").map(([n,o])=>[n,o]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function $u(){let t=ya();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function ut(t,e=!1,r="1.0.0"){let n=Nu(t),o=$u(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function ju(t,e){let r;return _r(t)?r=Ro(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Zd(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Lu(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(zu(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
90
+ `)}function zu(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${Ts(o,e)},`):r.push(`${n}?: ${Ts(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
91
+ `)}function Ts(t,e){if(Zd(t))return t.anyOf.map(r=>Ts(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",zu(t,e+2),"}"].join(`
92
+ `);case"array":return t.items?`${Ts(t.items,e)}[]`:"any[]";default:return""}}function vs(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function Mn(t){return"type"in t&&t.type!=="function"}function Du(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function Uu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function ur(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Cs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Fu(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function Bu(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function Ku(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Wu(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Hu(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function qu(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var Zu=Symbol("Let zodToJsonSchema decide on which parser to use"),Ju={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Vu=t=>typeof t=="string"?{...Ju,basePath:["#"],definitions:{},name:t}:{...Ju,basePath:["#"],definitions:{},...t};var fo=t=>"_def"in t?t._def:t;function Gu(t){if(!t)return!0;for(let e in t)return!1;return!0}var Yu=t=>{let e=Vu(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[fo(o),{def:fo(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ta(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function K(t,e,r,n,o){t[e]=r,ta(t,e,n,o)}function Xu(){return{}}function Qu(t,e){let r={type:"array"};return t.type?._def?.typeName!==L.ZodAny&&(r.items=E(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&K(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&K(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(K(r,"minItems",t.exactLength.value,t.exactLength.message,e),K(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ec(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?K(r,"minimum",n.value,n.message,e):K(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),K(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?K(r,"maximum",n.value,n.message,e):K(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),K(r,"maximum",n.value,n.message,e));break;case"multipleOf":K(r,"multipleOf",n.value,n.message,e);break}return r}function tc(){return{type:"boolean"}}function rc(t,e){return E(t.type._def,e)}var nc=(t,e)=>E(t.innerType._def,e);function ra(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ra(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Vd(t,e)}}var Vd=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":K(r,"minimum",n.value,n.message,e);break;case"max":K(r,"maximum",n.value,n.message,e);break}return r};function oc(t,e){return{...E(t.innerType._def,e),default:t.defaultValue()}}function sc(t,e,r){return e.effectStrategy==="input"?E(t.schema._def,e,r):{}}function ic(t){return{type:"string",enum:[...t.values]}}var Gd=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function ac(t,e){let r=[E(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),E(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Gd(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...u}=s;i=u}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function lc(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var na,cr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(na===void 0&&(na=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),na),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function ks(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Yd(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":K(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":K(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Re(r,"email",o.message,e);break;case"format:idn-email":Re(r,"idn-email",o.message,e);break;case"pattern:zod":Ne(r,cr.email,o.message,e);break}break;case"url":Re(r,"uri",o.message,e);break;case"uuid":Re(r,"uuid",o.message,e);break;case"regex":Ne(r,o.regex,o.message,e);break;case"cuid":Ne(r,cr.cuid,o.message,e);break;case"cuid2":Ne(r,cr.cuid2,o.message,e);break;case"startsWith":Ne(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":Ne(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Re(r,"date-time",o.message,e);break;case"date":Re(r,"date",o.message,e);break;case"time":Re(r,"time",o.message,e);break;case"duration":Re(r,"duration",o.message,e);break;case"length":K(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),K(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{Ne(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Re(r,"ipv4",o.message,e),o.version!=="v4"&&Re(r,"ipv6",o.message,e);break}case"emoji":Ne(r,cr.emoji,o.message,e);break;case"ulid":{Ne(r,cr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Re(r,"binary",o.message,e);break}case"contentEncoding:base64":{K(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Ne(r,cr.base64,o.message,e);break}}break}case"nanoid":Ne(r,cr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Yd=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Re=(t,e,r,n)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):K(t,"format",e,r,n)},Ne=(t,e,r,n)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:uc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):K(t,"pattern",uc(e,n),r,n)},uc=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",i=!1,a=!1,u=!1;for(let l=0;l<o.length;l++){if(i){s+=o[l],i=!1;continue}if(n.i){if(a){if(o[l].match(/[a-z]/)){u?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],u=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
93
+ ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
94
+ ]))`;continue}}if(n.s&&o[l]==="."){s+=a?`${o[l]}\r
95
+ `:`[${o[l]}\r
96
+ ]`;continue}s+=o[l],o[l]==="\\"?i=!0:a&&o[l]==="]"?a=!1:!a&&o[l]==="["&&(a=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Os(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===L.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:E(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:E(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===L.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(ks(t.keyType._def,e)).reduce((o,[s,i])=>s==="type"?o:{...o,[s]:i},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===L.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function cc(t,e){if(e.mapStrategy==="record")return Os(t,e);let r=E(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=E(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function pc(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function mc(){return{not:{}}}function dc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ho={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hc(t,e){if(e.target==="openApi3")return fc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ho&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ho[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return fc(t,e)}var fc=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>E(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function gc(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:ho[t.innerType._def.typeName],nullable:!0}:{type:[ho[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=E(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=E(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function _c(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ta(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?K(r,"minimum",n.value,n.message,e):K(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),K(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?K(r,"maximum",n.value,n.message,e):K(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),K(r,"maximum",n.value,n.message,e));break;case"multipleOf":K(r,"multipleOf",n.value,n.message,e);break}return r}function Xd(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":E(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":E(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function yc(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let i=[...e.currentPath,"properties",o],a=E(s._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:a},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:Xd(t,e)};return r.required.length||delete r.required,r}var wc=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return E(t.innerType._def,{...e,currentPath:e.currentPath});let r=E(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var Ac=(t,e)=>{if(e.pipeStrategy==="input")return E(t.in._def,e);if(e.pipeStrategy==="output")return E(t.out._def,e);let r=E(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=E(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function bc(t,e){return E(t.type._def,e)}function Ic(t,e){let n={type:"array",uniqueItems:!0,items:E(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&K(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&K(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function xc(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>E(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:E(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>E(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Tc(){return{not:{}}}function vc(){return{}}var Cc=(t,e)=>E(t.innerType._def,e);function E(t,e,r=!1){let n=e.seen.get(t);if(e.override){let i=e.override?.(t,e,n,r);if(i!==Zu)return i}if(n&&!r){let i=Qd(n,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=tf(t,t.typeName,e,r);return s&&rf(t,e,s),o.jsonSchema=s,s}var Qd=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:ef(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ef=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},tf=(t,e,r,n)=>{switch(e){case L.ZodString:return ks(t,r);case L.ZodNumber:return _c(t,r);case L.ZodObject:return yc(t,r);case L.ZodBigInt:return ec(t,r);case L.ZodBoolean:return tc();case L.ZodDate:return ra(t,r);case L.ZodUndefined:return Tc();case L.ZodNull:return dc(r);case L.ZodArray:return Qu(t,r);case L.ZodUnion:case L.ZodDiscriminatedUnion:return hc(t,r);case L.ZodIntersection:return ac(t,r);case L.ZodTuple:return xc(t,r);case L.ZodRecord:return Os(t,r);case L.ZodLiteral:return lc(t,r);case L.ZodEnum:return ic(t);case L.ZodNativeEnum:return pc(t);case L.ZodNullable:return gc(t,r);case L.ZodOptional:return wc(t,r);case L.ZodMap:return cc(t,r);case L.ZodSet:return Ic(t,r);case L.ZodLazy:return E(t.getter()._def,r);case L.ZodPromise:return bc(t,r);case L.ZodNaN:case L.ZodNever:return mc();case L.ZodEffects:return sc(t,r,n);case L.ZodAny:return Xu();case L.ZodUnknown:return vc();case L.ZodDefault:return oc(t,r);case L.ZodBranded:return rc(t,r);case L.ZodReadonly:return Cc(t,r);case L.ZodCatch:return nc(t,r);case L.ZodPipeline:return Ac(t,r);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(o=>{})(e)}},rf=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var oa=(t,e)=>{let r=Yu(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=E(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let i=(()=>{if(Gu(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let m=Object.entries(r.definitions).filter(([_])=>!l.has(_));if(m.length===0)break;for(let[_,d]of m)u[_]=E(fo(d),{...r,currentPath:[...r.basePath,r.definitionPath,_]},!0)??{},l.add(_)}return u})(),a=n===void 0?i?{...o,[r.definitionPath]:i}:o:r.nameStrategy==="duplicate-ref"?{...o,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function kc(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return ct(e,[],e)}function sa(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(sa(e))return!0;for(let e of t.anyOf??[])if(sa(e))return!0;return!1}function ct(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!pr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(pr(n))for(let[_,d]of Object.entries(n))ct(d,[...e,"$defs",_],r);let o=t.definitions;if(pr(o))for(let[_,d]of Object.entries(o))ct(d,[...e,"definitions",_],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(pr(a)){for(let[_,d]of Object.entries(a))if(!sa(d)&&!i.includes(_))throw new Error(`Zod field at \`${[...e,"properties",_].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([_,d])=>[_,ct(d,[...e,"properties",_],r)]))}let u=t.items;pr(u)&&(t.items=ct(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((_,d)=>ct(_,[...e,"anyOf",String(d)],r)));let c=t.allOf;if(Array.isArray(c))if(c.length===1){let _=ct(c[0],[...e,"allOf","0"],r);Object.assign(t,_),delete t.allOf}else t.allOf=c.map((_,d)=>ct(_,[...e,"allOf",String(d)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&of(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let _=nf(r,m);if(typeof _=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!pr(_))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(_)}`);return Object.assign(t,{..._,...t}),delete t.$ref,ct(t,e,r)}return t}function nf(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!pr(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function pr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function of(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function sf(t,e){return oa(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function af(t){return kc(Ea(t,{target:"draft-7"}))}function lf(t){return"_zod"in t}function Oc(t,e,r){return iu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:lf(t)?af(t):sf(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var Pc=["jsonSchema","functionCalling","jsonMode"];function Sc(t,e){if(typeof e<"u"&&!Pc.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Pc.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function uf(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Ec(t,e,r){if(Ma(t))return Oc(t,e,r);if(dr(t))return uf({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:je(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Pa(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function Mc(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var Rc={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Rn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var mr=class extends zn{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??xe("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??xe("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.4.3")}_getReasoningParams(t){if(!it(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Ze(t.json_schema.schema)?Ec(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=lt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=ut(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return ur(t)?qu(t.metadata.customTool):Eo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:ju(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if(Mn(n)||ur(n))return n;if(Du(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return _r(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[i,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(at(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=i+r+a+u,c=s;if(c._getType()==="function"&&(l-=2),c.additional_kwargs?.function_call&&(l+=3),c?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(c.additional_kwargs.function_call)),l+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=Lu(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw Ee(o)}})}get profile(){return Rc[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=Sc(this.model,e?.method);if(a==="jsonMode"){n=Ys(o);let u=je(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(a==="jsonSchema"){let u=je(o),l={name:s??"extract",description:Oo(u),schema:Ze(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),Ze(o)||pt(o)){let c=Ys(o);n=hr.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:c.invoke(m.content))}else n=new Da}else{let u=s??"extract",l=je(o),c;Ze(o)||pt(o)?c={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(c=o,u=o.name):(u=o.title??u,c={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:c}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=Fa(o,u)}return Ba(r,n,i)}};var Ps={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Us({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=Ds(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Ds(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=Us({dataUrl:t.url}),r=En(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=En(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},ia=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],i=[];for(let l of n??[])try{s.push(Mo(l,{returnId:!0}))}catch(c){i.push(gr(l,c.message))}let a={function_call:t.function_call,tool_calls:n};r!==void 0&&(a.__raw_response=e),o!==void 0&&(a.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new S({content:Mc(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:i,additional_kwargs:a,response_metadata:u,id:e.id})}default:return new vo(t.content||"",t.role??"unknown")}},aa=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ks({content:s,response_metadata:a});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new Je({content:s,tool_call_chunks:u,additional_kwargs:i,id:e.id,response_metadata:a})}else return o==="system"?new Co({content:s,response_metadata:a}):o==="developer"?new Co({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new xa({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new Bs({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Ia({content:s,role:o,response_metadata:a})},Nc=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=Ta(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=En(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},$c=({message:t,model:e})=>{let r=at(t);if(r==="system"&&it(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="tool"&&D.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")};function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let i=Nc(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},go=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return $c({message:r});let n=at(r);n==="system"&&it(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>Io(i)?xo(i,Ps):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),S.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Ua):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),D.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var Ss=class extends mr{constructor(t,e){super(Rn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:vs(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),it(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=go({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let d of i){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};let y=d.generationInfo?.completion??0;a[y]===void 0?a[y]=d:a[y]=a[y].concat(d)}let u=Object.entries(a).sort(([d],[y])=>parseInt(d,10)-parseInt(y,10)).map(([d,y])=>y),{functions:l,function_call:c}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,c),_=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=_,n.total_tokens=m+_,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let i=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:u,total_tokens:l,prompt_tokens_details:c,completion_tokens_details:m}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(n.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let _=[];for(let d of i?.choices??[]){let y={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},i)};y.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},To(y.message)&&(y.message.usage_metadata=n),y.message=new S(Object.fromEntries(Object.entries(y.message).filter(([T])=>!T.startsWith("lc_")))),_.push(y)}return{generations:_,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(t,e,r){let n=go({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,i=await this.completionWithRetry(o,e),a;for await(let u of i){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(a=u.usage),!l)continue;let{delta:c}=l;if(!c)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(c,u,s);s=c.role??s;let _={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let d={..._};l.finish_reason!=null&&(d.finish_reason=l.finish_reason,d.system_fingerprint=u.system_fingerprint,d.model_name=u.model,d.service_tier=u.service_tier),this.logprobs&&(d.logprobs=l.logprobs);let y=new jn({message:m,text:m.content,generationInfo:d});yield y,await r?.handleLLMNewToken(y.text??"",_,void 0,void 0,void 0,{chunk:y})}if(a){let u={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},l={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},c=new jn({message:new Je({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield c,await r?.handleLLMNewToken(c.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:c})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Ee(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return aa({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return ia({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Es="__openai_function_call_ids__";function Bc(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function pf(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var la=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},Ms=t=>{if(t.error){let u=new Error(t.error.message);throw u.name=t.error.code,u}let e,r=[],n=[],o=[],s=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){let l={...u};return delete l.parsed_arguments,l}return u}),i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:s,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let u of t.output)if(u.type==="message")e=u.id,r.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(a.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(Bc),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(a.refusal=l.refusal,[]):l));else if(u.type==="function_call"){let l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{n.push(Mo(l,{returnId:!0}))}catch(c){let m;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(m=c.message),o.push(gr(l,m))}a[Es]??={},u.id&&(a[Es][u.call_id]=u.id)}else if(u.type==="reasoning"){a.reasoning=u;let l=u.summary?.map(c=>c.text).filter(Boolean).join("");l&&r.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){let l=Fu(u);l?n.push(l):o.push(gr(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){let l=Bu(u);l?n.push(l):o.push(gr(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&r.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),a.tool_outputs??=[],a.tool_outputs.push(u)):(a.tool_outputs??=[],a.tool_outputs.push(u));return new S({id:e,content:r,tool_calls:n,invalid_tool_calls:o,usage_metadata:la(t.usage),additional_kwargs:a,response_metadata:i})},Kc=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},ua=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[Bc(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){a=t.item.id;let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Es]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"){let u=Ms(t.response);n=la(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text&&(i.parsed??=JSON.parse(u.text));for(let[l,c]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=c)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((c,m)=>({...c,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta});else return t.type==="response.image_generation_call.partial_image",null;return new jn({text:e.map(u=>u.text).join(""),message:new Je({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},Wc=t=>{let e=S.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Me(()=>{try{let f=at(t);return f==="system"||f==="developer"||f==="assistant"||f==="user"?f:"assistant"}catch{return"assistant"}}),o,s=new Set,i=new Set,a=new Map,u=new Map;function*l(){if(!o)return;let f=o.content;(typeof f=="string"&&f.length>0||Array.isArray(f)&&f.length>0)&&(yield o),o=void 0}let c=(f,A)=>{o||(o={type:"message",role:n,content:[],...A?{phase:A}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...f]:[...f]:o.content.push(...f)},m=f=>{if(typeof f=="string")return f;try{return JSON.stringify(f??{})}catch{return"{}"}},_=f=>{let A=Me(()=>{let C=f.metadata?.detail;return C==="low"||C==="high"||C==="auto"?C:"auto"});if(f.fileId)return{type:"input_image",detail:A,file_id:f.fileId};if(f.url)return{type:"input_image",detail:A,image_url:f.url};if(f.data){let C=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${f.mimeType??"image/png"};base64,${C}`}}},d=f=>{if(f.fileId){let A=Qi(f);return{type:"input_file",file_id:f.fileId,...A?{filename:A}:{}}}if(f.url){let A=Qi(f);return{...A?{filename:A}:{},type:"input_file",file_url:f.url}}if(f.data){let A=En(f),C=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64");return{type:"input_file",file_data:`data:${f.mimeType??"application/octet-stream"};base64,${C}`,filename:A}}},y=f=>{let A=Me(()=>{if(Array.isArray(f.summary)){let J=f.summary?.map(B=>B?.text).filter(B=>typeof B=="string")??[];if(J.length>0)return J}return f.reasoning?[f.reasoning]:[]}),C=A.length>0?A.map(J=>({type:"summary_text",text:J})):[{type:"summary_text",text:""}],z={type:"reasoning",id:f.id??"",summary:C};return f.reasoning&&(z.content=[{type:"reasoning_text",text:f.reasoning}]),z},T=f=>({type:"function_call",name:f.name??"",call_id:f.id??"",arguments:m(f.args)}),$=f=>{let A=m(f.output),C=f.status==="success"?"completed":f.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:f.toolCallId??"",output:A,...C?{status:C}:{}}};for(let f of t.contentBlocks)if(f.type==="text"){let A=Me(()=>{if("extras"in f&&typeof f.extras=="object"&&f.extras!==null&&"phase"in f.extras)return f.extras.phase});c([{type:"input_text",text:f.text}],A)}else if(f.type!=="invalid_tool_call"){if(f.type==="reasoning")yield*l(),yield y(f);else if(f.type==="tool_call"){yield*l();let A=f.id??"";A&&(s.add(A),a.delete(A)),yield T(f)}else if(f.type==="tool_call_chunk"){if(f.id){let A=a.get(f.id)??{name:f.name,args:[]};f.name&&(A.name=f.name),f.args&&A.args.push(f.args),a.set(f.id,A)}}else if(f.type==="server_tool_call"){yield*l();let A=f.id??"";A&&(i.add(A),u.delete(A)),yield T(f)}else if(f.type==="server_tool_call_chunk"){if(f.id){let A=u.get(f.id)??{name:f.name,args:[]};f.name&&(A.name=f.name),f.args&&A.args.push(f.args),u.set(f.id,A)}}else if(f.type==="server_tool_call_result")yield*l(),yield $(f);else if(f.type!=="audio")if(f.type==="file"){let A=d(f);A&&c([A])}else if(f.type==="image"){let A=_(f);A&&c([A])}else if(f.type==="video"){let A=d(f);A&&c([A])}else f.type==="text-plain"?f.text&&c([{type:"input_text",text:f.text}]):f.type==="non_standard"&&e&&(yield*l(),yield f.value)}yield*l();for(let[f,A]of a){if(!f||s.has(f))continue;let C=A.args.join("");!A.name&&!C||(yield{type:"function_call",call_id:f,name:A.name??"",arguments:C})}for(let[f,A]of u){if(!f||i.has(f))continue;let C=A.args.join("");!A.name&&!C||(yield{type:"function_call",call_id:f,name:A.name??"",arguments:C})}}return Array.from(r())},Rs=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Wc(n);let s=n.additional_kwargs,i=at(n);if(i==="system"&&it(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(_=>_.type==="input_image");if(l)return l;let c=a.content.find(_=>_.type==="computer_screenshot");if(c)return c;let m=a.content.find(_=>_.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let u=Array.isArray(a.content)&&a.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:u?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(y=>"type"in y))return o?.output;let a=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let y=Kc(u);a.push(y)}let{content:c}=n;if(s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),typeof c=="string"||c.length>0){let y={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Me(()=>typeof c=="string"?c:c.flatMap(T=>{if(T.type==="text"){let $=T;return{type:"output_text",text:$.text,annotations:($.annotations??[]).map(pf)}}return T.type==="output_text"||T.type==="refusal"?T:[]})),phase:Me(()=>{if(Array.isArray(c))return c.find(T=>"phase"in T&&typeof T.phase=="string")?.phase})};a.push(y)}let m=s?.[Es];S.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(y=>Wu(y)?{type:"custom_tool_call",id:y.call_id,call_id:y.id??"",input:y.args.input,name:y.name}:Ku(y)?{type:"computer_call",id:y.call_id,call_id:y.id??"",action:y.args.action}:{type:"function_call",name:y.name,arguments:JSON.stringify(y.args),call_id:y.id,...e?{}:{id:m?.[y.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(y=>({type:"function_call",name:y.function.name,call_id:y.id,arguments:y.function.arguments,...e?{}:{id:m?.[y.id]}})));let _=o?.output?.length?o?.output:s.tool_outputs,d=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(_!=null){let y=_?.filter(T=>d.includes(T.type));y.length>0&&a.push(...y)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],u=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Io(l)?xo(l,Ps):l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Me(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Me(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]));return u.length>0&&a.push({type:"message",role:i,content:u}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var Ns=class extends mr{constructor(t,e){super(Rn(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Uu(t?.tool_choice)?t?.tool_choice:(()=>{let o=vs(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let i of o)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},s=s?.concat(i)??i;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:Rs({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Ms(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:Rs({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let o of n){if(e.signal?.aborted)return;let s=ua(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw Ee(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Mn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(ur(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Eo(n)){let o={};for(let[s,i]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=i);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Cs(n)&&r.push(Hu(n));return r}};var $s=class Hc extends mr{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Rn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Ns(n),this.completions=n?.completions??new Ss(n)}_useResponsesApi(e){let r=e?.tools?.some(Mn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Cs)||e?.tools?.some(ur);return this.useResponsesApi||r||n||o||Ru(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new Hc(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var js=class extends La{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??xe("OPENAI_API_KEY");this.organization=e?.configuration?.organization??xe("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Qs(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let i={model:this.model,input:s};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let i=e[s],{data:a}=n[s];for(let u=0;u<i.length;u+=1)o.push(a[u].embedding)}return o}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=lt({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=ut(n.defaultHeaders),this.client=new P(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw Ee(r)}})}};var hf=b.object({type:b.literal("screenshot")}),gf=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),_f=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),yf=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),wf=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),Af=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),bf=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),If=b.object({type:b.literal("type"),text:b.string()}),xf=b.object({type:b.literal("wait"),duration:b.number().optional()}),Tf=b.union([hf,gf,_f,yf,wf,Af,bf,If,xf]),v$=b.object({action:Tf});var vf=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),P$=b.union([vf]);var R$=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var Cf=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),kf=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),Of=b.object({type:b.literal("delete_file"),path:b.string()}),L$=b.union([Cf,kf,Of]);var Xc={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},fa={default:"text-embedding-ada-002"},ca=new Map,Ls=null,Ef=()=>{let t=zs.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},Qc=async t=>{let e=Ef();ca.size===0&&(Ls||(Ls=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>ca.set(o.name,o))}catch(n){throw Ls=null,n}})()),await Ls);let r=ca.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Mf=async(t="default")=>await Qc(Xc[t]),ep=async(t="default")=>await Qc(fa[t]),Rf=async t=>{let e=await Nf(),r=await ep("default"),n=zs.getDefault(),o=(await da.getCredential(`${n.url}/sharing`)).token,s={type:"generateEmbeddings",webmapEmbeddings:t,auth:{apiUrl:r,token:o}};return e.postMessage(s),await new Promise((i,a)=>{let u=c=>{c.data==="completed"&&(e.removeEventListener("message",u),i())},l=c=>{e.removeEventListener("message",u),a(c instanceof Error?c:new Error("Embeddings worker error"))};e.addEventListener("message",u),e.addEventListener("error",l,{once:!0})}),e},Nf=async()=>{{let t=(await import("./24MYCR6F.js")).default;return new t}},Nn=(t,e)=>e,tp=(t,e)=>({...t,...e}),rp=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
97
+
98
+ `);return o[o.length-1]?.trim()===r?t:`${t}
99
+
100
+ ${r}`},np=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),$f=()=>({agentExecutionContext:he({reducer:tp,default:np}),outputMessage:he({reducer:rp,default:()=>""}),summary:he({reducer:Nn,default:()=>""}),status:he({reducer:Nn})}),oL=()=>({...$f(),sharedStatePatch:he({reducer:Nn})}),jf=he.Root({agentExecutionContext:he({default:np,reducer:tp}),currentIntent:he({default:()=>"none",reducer:Nn}),lastExecutedAgent:he({default:()=>"",reducer:Nn}),requiresFollowUp:he({default:()=>!0,reducer:Nn}),stepCount:he({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:he({default:()=>"",reducer:rp})}),$e=async(t,e)=>{await ti("trace_message",t,e)},sL=async(t,e)=>{await ti("graph_ux_suggestion",t,e)},Lf=t=>{t.currentIntent="none"},zf=async(t,e)=>{if(t.agentExecutionContext.userRequest){let n=new Te(t.agentExecutionContext.userRequest.trim());t.agentExecutionContext.messages=[...t.agentExecutionContext.messages,n],Lf(t)}let r=e?.configurable?.services.agentRegistry.list().map(n=>n.agent.id)??[];return await $e({text:`Available agents: ${[...r].join(", ")}`},e),await $e({text:"Analyzing user input"},e),t},Df=async(t,e)=>(await $e({text:"Exiting..."},e),t),qc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Uf=(t,e)=>{if(!qc(t)){t!==void 0&&console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);return}let r={};for(let[n,o]of Object.entries(t)){if(!qc(o)||!("value"in o)){console.warn(`Agent "${e}" returned invalid sharedStatePatch entry for key "${n}". Ignoring that entry.`);continue}r[n]={value:o.value}}return r},Ff=t=>{let{previousSharedState:e,patch:r,agentId:n}=t;if(!r)return e;let o=Date.now(),s={...e};for(let[i,a]of Object.entries(r))a?.value!==void 0&&(s[i]={value:a.value,meta:{updatedByAgentId:n,updatedAt:o}});return s},Jc=t=>typeof t!="string"?void 0:t.trim()||void 0,Bf=t=>{switch(t){case"failed":return"Agent failed without a summary.";case"unknown":return"Agent returned with unknown status.";case"success":return"Agent completed without a summary.";default:return"Agent completed without a summary."}},Kf=(t,e)=>{let r=Jc(e?.outputMessage),n=Jc(e?.summary),o=e?.status,s=o==="success"||o==="failed"?o:"unknown";s==="unknown"&&console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);let i=Uf(e?.sharedStatePatch,t);return{outputMessage:r,summary:n??r??Bf(s),status:s,sharedStatePatch:i}},Zc=4e3,Wf=async(t,e)=>{let r=e?.configurable,{agentRegistry:n}=r.services,o=n?.get(t.currentIntent);if(!o)return console.warn(`No agent found for intent: ${t.currentIntent}`),t;await $e({text:`Executing registered agent: ${o.agent.name}`},e);let s={...e??{},configurable:{...r??{},agentId:o.agent.id,context:o.getContext?await o.getContext():void 0}},i;try{let l=await o.agent.createGraph().compile().invoke({agentExecutionContext:{...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages],priorSteps:structuredClone(t.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(t.agentExecutionContext.sharedState??{})}},s);i=Kf(o.agent.name,l),await $e({text:`Finished executing registered agent: ${o.agent.name}`},e)}catch(l){if(bo(l))throw l;let c=l instanceof Error?l.message:String(l);console.error(`Agent "${o.agent.name}" failed:`,l),await $e({text:`Registered agent failed: ${o.agent.name}. ${c}`},e),i={status:"failed",outputMessage:`Agent execution failed: ${c}`,summary:`Agent execution failed: ${c}`}}let a=i.outputMessage,u=[...t.agentExecutionContext.messages];if(a){let l=a.length>Zc?`${a.slice(0,Zc-14)}
101
+ [truncated]`:a;u.push(new S(l))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:o.agent.id,requiresFollowUp:i.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:a??"",agentExecutionContext:{...t.agentExecutionContext,messages:u,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:o.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:i?.summary||"No summary provided.",status:i?.status||"unknown"}],sharedState:Ff({previousSharedState:t.agentExecutionContext.sharedState,patch:i.sharedStatePatch,agentId:o.agent.id})}}},Hf=(t,e,r)=>{let n=t[e];return n?typeof n=="function"?n():Promise.resolve(n):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},qf=async t=>(await Hf(Object.assign({"./field_descriptions_prompt.md":()=>import("./W5CHGOOR.js"),"./intent_prompt.md":()=>import("./Z7GVYVWK.js"),"./layer_descriptions_prompt.md":()=>import("./JDL3HFFX.js")}),`./${t}.md`,2)).default,Jf=async t=>{let{agent:e,messages:r,config:n}=t;return{structuredResponse:(await e.invoke({messages:r},n)).structuredResponse}},op=t=>async(e,r)=>{let n=new Headers(r?.headers);return n.delete("Authorization"),n.delete("api-key"),t&&t.length>0&&(n.set("X-Esri-Authorization",`Bearer ${t}`),n.set("X-Esri-Request-Source","MapsSDK")),await fetch(e,{...r,headers:n})},yo=async(t="default",e=0)=>{let r=zs.getDefault(),n=await da.getCredential(`${r.url}/sharing`),o=Xc[t],s=await Mf(t);return new $s({modelName:o,apiKey:"dummy-key",...t!=="default"&&{temperature:e},configuration:{baseURL:s,fetch:op(n.token)}})},Zf=async(t="default")=>{let e=zs.getDefault(),r=await da.getCredential(`${e.url}/sharing`),n=fa[t],o=await ep(t);return new js({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:op(r.token)},batchSize:2048,maxConcurrency:10})},Vf=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(Vf);var Vc=t=>JSON.stringify(t,null,2),Gf=t=>{let e=t.map(n=>n.id),r=b.enum(e);return b.object({intent:r.nullable(),assignedTask:b.string().nullable(),requiresFollowUp:b.boolean()})},Yf=async(t,e)=>{try{await $e({text:"Asking LLM to route to an agent"},e);let r=(e?.configurable?.services.agentRegistry?.list()??[]).map(({agent:d})=>({id:d.id,name:d.name,description:d.description}));if(!r.length)return await $e({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none"};let n=await qf("intent_prompt"),o=Vc(r),s=Gf(r),i={registeredAgents:o,priorSteps:Vc(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},a=await Xs.fromTemplate(n).format(i),u=ui({model:await yo("fast"),tools:[],systemPrompt:a,checkpointer:!0,responseFormat:s,middleware:[pi({model:await yo("fast"),trigger:{tokens:4e3},keep:{messages:6}}),mi({runLimit:2})]}),{structuredResponse:l}=await Jf({agent:u,messages:t.agentExecutionContext.messages,config:e}),c=s.parse(l??{intent:null,assignedTask:null,requiresFollowUp:!1}),m=c.intent??"none",_={...t,currentIntent:m,requiresFollowUp:c.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:c.assignedTask??""}};if(m==="none"){let d="I could not find a matching agent for that request. Please rephrase your question with more detail.";return await $e({text:"LLM did not identify a clear intent."},e),{...t,currentIntent:m,requiresFollowUp:!1,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new S(d)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await $e({text:`Agent picked: ${m}
102
+ Task Assigned: ${c.assignedTask??""}
103
+ Requires Follow-Up: ${c.requiresFollowUp}`},e),_}catch(r){throw await $e({text:"Error during intent detection"},e),new Error(`Error during intent detection: ${r instanceof Error?r.message:String(r)}`)}},Xf=3,Qf=()=>new jo(jf).addNode("ingestInput",zf).addNode("intentLLM",Yf).addNode("executeRegisteredAgent",Wf).addNode("exit",Df).addEdge(Ao,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",t=>t.stepCount>=Xf||!t.requiresFollowUp?"exit":"intentLLM").addEdge("exit",Z),pa=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:r}=e;if(this.agentRegistry.has(r.id))throw new Error(`Duplicate agent id: ${r.id}`);this.agentRegistry.set(r.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},ma=class{constructor(e,r){this.graph=e,this.config={...r}}async waitForUser(){return await new Promise((e,r)=>{this.resolveWait=e,this.rejectWait=r})}handle(e,r){try{let n={agentId:e.agentId,id:e.id,payload:r},o=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:n},subgraphs:!0,version:"v2"});this.resolveWait?.(o)}catch(n){this.rejectWait?.(n)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("Request cancelled by user.")),this.resolveWait=void 0,this.rejectWait=void 0)}},eh=async t=>{try{return await(await Zf()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}},sp=async(t,e)=>{let r=e.get(t);if(r)return r;let n=await eh([t]);return e.set(t,n[0]),n[0]};async function th(t,e,r,n){let o=`req-${Date.now()}`,s={type:"layerSearch",precomputedEmbedding:n?await sp(t,n):void 0,requestId:o,minScore:r};return await new Promise(i=>{let a=u=>{u.data.requestId===o&&i(u.data.results)};e.addEventListener("message",a,{once:!0}),e.postMessage(s)})}function rh(t){let{worker:e}=t;return{async searchLayers({text:r,minScore:n,embeddingCache:o}){return await th(r,e,n,o)}}}var nh=async({combinedQuery:t,layerIds:e,embeddingsWorker:r,minScore:n,topResults:o,embeddingCache:s})=>{let i=`req-${Date.now()}`,a=s?await sp(t,s):void 0,u={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:a,requestId:i,minScore:n,topResults:o};return await new Promise(l=>{let c=m=>{if(m.data.requestId!==i)return;let _=m.data.results.map(({layerId:d,results:y})=>({layerId:d,results:y}));l(_)};r.addEventListener("message",c,{once:!0}),r.postMessage(u)})};function oh(t){let{worker:e}=t;return{async searchFields({text:r,layerIds:n,minScore:o,topResults:s,embeddingCache:i}){return await nh({combinedQuery:r,layerIds:n,embeddingsWorker:e,minScore:o,topResults:s,embeddingCache:i})}}}var sh="0.1",_o=1536,ih="openai",ah=fa.default,lh=`Name: {name}
104
+ Title: {title}
105
+ Description: {description}`,uh=`Name: {name}
106
+ Alias: {alias}
107
+ Description: {description}`,ch=b.object({schemaVersion:b.literal(sh),modified:b.number().int().nonnegative(),embeddings:b.object({modelProvider:b.literal(ih),model:b.literal(ah),dimensions:b.literal(_o),templates:b.object({layer:b.string().default(lh),field:b.string().default(uh)})}),layers:b.array(b.object({id:b.string().min(1),name:b.string().min(1),title:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(_o,{message:`Layer vector must be exactly ${_o} dimensions`}),fields:b.array(b.object({name:b.string().min(1),alias:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(_o,{message:`Field vector must be exactly ${_o} dimensions`})}))})).default([])}),ph=t=>{let e=ch.safeParse(t);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},mh=(t,e)=>{let r=new Map,n=new Map;if(e.allLayers.forEach(o=>{o instanceof Pf&&n.set(o.id,o)}),t.length!==n.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let o of t){let s=n.get(o.id);if(!s)throw new Error(`Layer with ID ${o.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(o.fields.length!==s.fields.length)throw new Error(`Field count mismatch for layer ID ${o.id} during registry restoration. Regenerate embeddings.`);let i={name:o.name,title:o.title,description:o.description},a=new Map;for(let u of o.fields){let l=s.fieldsIndex.get(u.name);if(!l)throw new Error(`Field with name ${u.name} not found in the original layer ${o.id} during registry restoration. Regenerate embeddings.`);a.set(u.name,{name:u.name,alias:s.getFieldAlias(u.name)??u.alias,description:u.description,type:l.type||"unknown",valueType:l.valueType||"unknown",domain:s.getFieldDomain(u.name)??void 0})}r.set(o.id,{layerItem:i,fieldRegistry:a})}return r},dh=async t=>{try{return(await Sf(t,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${t}: ${String(e)}`)}},fh=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:r}=await e.portalItem.fetchResources(),n=r.find(s=>s.resource.path==="embeddings-v01.json");if(!n?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let o=await dh(n.resource.url);return ph(o)},Gc=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.threadId="",this.agentRegistry=new pa,this.streamEpoch=0}static async init(e){let r=new t;try{if(e.view?.map){await Yc.whenOnce(()=>e.view.ready);let n=await fh(e.view),o=mh(n.layers,e.view.map);r.layersAndFieldsRegistry=o,r.embeddingsWorker=await Rf(n)}return e.agents?.forEach(n=>{r.agentRegistry.register(n)}),r.orchestratorReady=!0,r}catch(n){throw console.error("Orchestrator initialization failed:",n),n}}async*ask(e){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!e.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=Qf().compile({checkpointer:new Wa}));let r=this.embeddingsWorker?rh({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?oh({worker:this.embeddingsWorker}):void 0,o=new Map,s={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:r,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:o}},subgraphs:!0},i=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},s),a=++this.streamEpoch;for(yield*this.pipeStream(i,a);;){let l=(await this.graph.getState(s,{subgraphs:!0})).tasks.find(c=>c.interrupts.length>0)?.interrupts[0]?.value;if(!l)break;this.currentInterrupt=l,this.interruptHandler=new ma(this.graph,s),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:l};try{let c=await this.interruptHandler.waitForUser(),m=++this.streamEpoch;yield*this.pipeStream(c,m)}catch(c){if(c){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:c?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let u=(await this.graph.getState(s,{subgraphs:!0})).values;this.chatHistory=u.agentExecutionContext.messages.length?u.agentExecutionContext.messages:this.chatHistory,this.priorSteps=u.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=u.agentExecutionContext.sharedState??{},yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:u.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(e,r){for await(let n of e){if(r!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}},hh=t=>{let e=new Set;for(let r of t)if(To(r)){let n=r;n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(o=>{o.id&&e.add(o.id)})}return t.filter(r=>{if(Aa(r)){let n=r;return e.has(n.tool_call_id)}return!0})},ha=(t,e)=>{let r=Ka.fromTemplate(t);return Xs.fromMessages([r,...e])},gh=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o}=t,s=ha(e,o??[]),i=await yo(r,n);return s.pipe(i)},iL=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s}=t,i=await(await gh({promptText:e,modelTier:r,temperature:n,messages:o})).invoke(s??{});if(typeof i=="string")return i;let a=i.content;return typeof a=="string"?a:JSON.stringify(a)},aL=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i}=t,a=ha(e,o??[]),u=(await yo(r,n)).withStructuredOutput(i);return await a.pipe(u).invoke(s??{})},lL=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,tools:i}=t,a=i.length>0?hh(o??[]):o??[],u=ha(e,a),l=await yo(r,n);return await u.pipe(l.bindTools(i)).invoke(s??{})},_h=Ie.object({name:Ie.string(),description:Ie.string(),valueType:Ie.string(),alias:Ie.string()}),uL=Ie.object({fields:Ie.array(_h)});var cL=Ie.object({title:Ie.string(),description:Ie.string(),name:Ie.string().nullable()});return{a:Ie,b:$f,c:oL,d:$e,e:sL,f:Gc,g:iL,h:aL,i:lL}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request")