@arcgis/portal-components 5.2.0-next.88 → 5.2.0-next.89
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.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import c from"./OHEUIODH.js";import b from"./AMBLICID.js";import{a as Gl,c as Vl,e as Wl,f as Hl,g as Jl}from"./3YCG5UCH.js";import a from"./F3ODJVJC.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as en,b as _l,d as Fn}from"./2GBRZSEC.js";import{a as wl}from"./O3RR6UMN.js";import"./BTLJZVSE.js";import"./UEL7BVMB.js";import{K as Yo,L as Xo,M as gl,S as yl,h as pl,j as ve,n as ml,w as fl,z as hl}from"./BXCQOWAD.js";import{$ as wa,Aa as zl,Ca as Ll,Cb as on,Da as Yn,Ea as Xn,Fa as jl,Ga as br,Gb as es,Ha as Ar,Hb as ts,Ia as v,Ib as ce,J as Al,Ja as E,K as ge,Ka as Ia,L as Et,La as va,M as xl,Ma as Ta,N as Il,O as Bn,P as ga,Q as ya,R as Kn,S as tn,T as B,U as _a,V as F,W as st,Wa as M,X as at,Y as Gn,Z as vl,_ as Tl,a as ue,aa as Vn,b as K,ba as Sl,ca as Cl,da as rn,ea as Wn,fa as kl,g as bl,ga as El,ha as Ml,ia as Hn,j as Be,ja as Pl,k as kt,ka as Mt,la as ba,ma as Jn,na as
|
|
2
|
+
import c from"./OHEUIODH.js";import b from"./AMBLICID.js";import{a as Gl,c as Vl,e as Wl,f as Hl,g as Jl}from"./3YCG5UCH.js";import a from"./F3ODJVJC.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as en,b as _l,d as Fn}from"./2GBRZSEC.js";import{a as wl}from"./O3RR6UMN.js";import"./BTLJZVSE.js";import"./UEL7BVMB.js";import{K as Yo,L as Xo,M as gl,S as yl,h as pl,j as ve,n as ml,w as fl,z as hl}from"./BXCQOWAD.js";import{$ as wa,Aa as zl,Ca as Ll,Cb as on,Da as Yn,Ea as Xn,Fa as jl,Ga as br,Gb as es,Ha as Ar,Hb as ts,Ia as v,Ib as ce,J as Al,Ja as E,K as ge,Ka as Ia,L as Et,La as va,M as xl,Ma as Ta,N as Il,O as Bn,P as ga,Q as ya,R as Kn,S as tn,T as B,U as _a,V as F,W as st,Wa as M,X as at,Y as Gn,Z as vl,_ as Tl,a as ue,aa as Vn,b as K,ba as Sl,ca as Cl,da as rn,ea as Wn,fa as kl,g as bl,ga as El,ha as Ml,ia as Hn,j as Be,ja as Pl,k as kt,ka as Mt,la as ba,ma as Jn,na as N,oa as A,pa as Pt,pb as Dl,qa as it,ra as Ol,s as Un,sa as Zn,ta as Rl,ua as $l,va as Qn,wa as Aa,xa as wr,y as qn,ya as xa,za as Nl}from"./JCYCRSPL.js";import"./UZLQALHY.js";export default $arcgis.t(([ZV,YV,Ld,jd,py,my,Ty,sW,iW,MZ,HA,pp,Wo,mp,,yp,,Ly,jy,Ny,ep,{formatDateOnly:Vy,convertDateFormatToIntlOptions:Xs,formatTimeOnly:Wy,formatDate:tp},a_,i_,l_,f_,h_,{createRenderer:k_},{getSchemesByTag:E_,getSchemes:M_},{getBackgroundColorTheme:fp},{createAgeRenderer:P_,createContinuousRenderer:O_},{getSchemesByTag:Zi},{createContinuousRenderer:R_},{createRenderer:$_},{getSchemesByTag:N_},{createRenderer:z_},{getSchemesByTag:L_},{createRenderer:j_},{getSchemesByTag:D_},{createRenderer:F_},{getSchemesByTag:U_},{createAgeRenderer:q_,createContinuousRenderer:B_},{createRenderer:K_},{getSchemesByTag:G_},V_,_p,{fetchKnowledgeGraph:hp,executeQueryStreaming:W_,executeSearchStreaming:H_},J_,{getBindParametersFromCypherQuery:Z_},,,,,,,Yi,oA,nA,{addressToLocations:sA},aA,wA,zA,,,,,,,,,,,,,,,,,,,QJ,XJ,,,,,,,,,,,,,Cp,kp,JA,,{a:Bl,b:Kl},{a:Fl,b:Ul,c:ql}])=>{var lt=(t,e)=>e,Sa=(t,e)=>({...t,...e}),Ca=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let o=t.trim();if(!o)return r;if(o===r)return t;let n=o.split(`
|
|
3
3
|
|
|
4
4
|
`);return n[n.length-1]?.trim()===r?t:`${t}
|
|
5
5
|
|
|
@@ -10,7 +10,7 @@ If you continue to see this error, please import from "@langchain/core/callbacks
|
|
|
10
10
|
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
11
11
|
|`,`
|
|
12
12
|
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
13
|
-
`].join(" "));let o=await Cl(r),n=o?.getParentRunId();o!==void 0&&n!==void 0&&await o.handleCustomEvent?.(t,e,n)}var J=async(t,e)=>{await Ea("trace_message",t,e)},fe=async(t,e)=>{await Ea("graph_ux_suggestion",t,e)};var pm={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},langsmith:{package:"@langchain/openai",className:"ChatOpenAI"},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"}},Kv=Object.keys(pm);var
|
|
13
|
+
`].join(" "));let o=await Cl(r),n=o?.getParentRunId();o!==void 0&&n!==void 0&&await o.handleCustomEvent?.(t,e,n)}var J=async(t,e)=>{await Ea("trace_message",t,e)},fe=async(t,e)=>{await Ea("graph_ux_suggestion",t,e)};var pm={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},langsmith:{package:"@langchain/openai",className:"ChatOpenAI"},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"}},Kv=Object.keys(pm);var $a=Symbol.for("langgraph-zod");$a in globalThis||(globalThis[$a]=new WeakSet);function Ql(t){let e=globalThis[$a];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(o){return ts(r,{jsonSchemaExtra:o})},reducer(o,n){return ts(r,{default:Jn(r),reducer:{schema:n,fn:o}})}}}}),e.add(t))}try{Ql(A.ZodType.prototype),Ql(v.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 Yl=class extends El{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let o=Jn(t);o!=null&&(r.default=o)}return super.add(t,...e)}},gm=new Yl(es);var Em=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Mm=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),Pm=["approve","edit","reject"],Om=A.enum(Pm),Rm=A.object({allowedDecisions:A.array(Om),description:A.union([A.string(),Mm]).optional(),argsSchema:A.record(A.any()).optional(),when:Em.optional()}),XC=A.object({interruptOn:A.record(A.union([A.boolean(),Rm])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var as=A.object({maxRetries:A.number().min(0).default(2),retryOn:A.union([A.function().args(A.instanceof(Error)).returns(A.boolean()),A.array(A.custom())]).default(()=>t=>xl(t)??!0),backoffFactor:A.number().min(0).default(2),initialDelayMs:A.number().min(0).default(1e3),maxDelayMs:A.number().min(0).default(6e4),jitter:A.boolean().default(!0)});var zm=`<role>
|
|
14
14
|
Context Extraction Assistant
|
|
15
15
|
</role>
|
|
16
16
|
|
|
@@ -39,20 +39,20 @@ Messages to summarize:
|
|
|
39
39
|
</messages>`;var Lm=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),Da=A.object({fraction:A.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().positive("Tokens must be greater than 0").optional(),messages:A.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"}),cu=A.object({fraction:A.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:A.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"}),Ak=A.object({model:A.custom(),trigger:A.union([Da,A.array(Da)]).optional(),keep:cu.optional(),tokenCounter:Lm.optional(),summaryPrompt:A.string().default(zm),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var Rk=A.object({model:A.string().or(A.instanceof(Rl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var Fk=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var Gk=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var jm=["continue","error","end"],Dm="continue";var Fm=A.enum(jm).default(Dm);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Fm});var rE=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Um=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),qm=A.object({content:A.string().describe("Content of the todo item"),status:Um}),cE=A.object({todos:A.array(qm).default([])});var hE=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),gE=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var kE=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(as);var zE=A.object({tools:A.array(A.union([A.custom(),A.custom(),A.string()])).optional(),onFailure:A.union([A.literal("error"),A.literal("continue"),A.literal("raise"),A.literal("return_message"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(as);var oM=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var iM=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function nn(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
40
40
|
|
|
41
41
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
42
|
-
`,t}function P(t,e,r,o,n){if(o==="m")throw new TypeError("Private method is not writable");if(o==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function _(t,e,r,o){if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?o:r==="a"?o.call(t):o?o.value:e.get(t)}var qa=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return qa=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,o=>(+o^r()&15>>+o/4).toString(16))};function sn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var an=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 C=class extends Error{},V=class t extends C{constructor(e,r,o,n){super(`${t.makeMessage(e,r,o)}`),this.status=e,this.headers=n,this.requestID=n?.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,o){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):o;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,o,n){if(!e||!n)return new ct({message:o,cause:an(r)});let s=r?.error;return e===400?new Ir(e,s,o,n):e===401?new vr(e,s,o,n):e===403?new Tr(e,s,o,n):e===404?new Sr(e,s,o,n):e===409?new Cr(e,s,o,n):e===422?new kr(e,s,o,n):e===429?new Er(e,s,o,n):e>=500?new Mr(e,s,o,n):new t(e,s,o,n)}},W=class extends V{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends V{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ne=class extends ct{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ir=class extends V{},vr=class extends V{},Tr=class extends V{},Sr=class extends V{},Cr=class extends V{},kr=class extends V{},Er=class extends V{},Mr=class extends V{},Pr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Or=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},$e=class extends Error{constructor(e){super(e)}},Nt=class extends V{constructor(e,r,o){let n="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?n=i:s&&(n=s)}super(e,r,n,o),this.error_code=s}},ln=class extends C{constructor(e,r,o){super(e),this.provider=r,this.cause=o}};var Sf=/^[a-z][a-z0-9+.-]*:/i,mu=t=>Sf.test(t),de=t=>(de=Array.isArray,de(t)),Ba=de;function is(t){return typeof t!="object"?{}:t??{}}function Ka(t){if(!t)return!0;for(let e in t)return!1;return!0}function fu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function un(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var hu=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var gu=t=>{try{return JSON.parse(t)}catch{return}};var ze=t=>new Promise(e=>setTimeout(e,t));var dt="6.45.0";var bu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Cf(){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 kf=()=>{let t=Cf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":_u(Deno.build.os),"X-Stainless-Arch":yu(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":dt,"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":dt,"X-Stainless-OS":_u(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ef();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"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":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ef(){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 o=r.exec(navigator.userAgent);if(o){let n=o[1]||0,s=o[2]||0,a=o[3]||0;return{browser:e,version:`${n}.${s}.${a}`}}}return null}var yu=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",_u=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"),wu,Au=()=>wu??(wu=kf());function ls(){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 Ga(...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 us(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ga({start(){},async pull(r){let{done:o,value:n}=await e.next();o?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function Va(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 Wa(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 Iu=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ha="RFC3986",Ja=t=>String(t),Za={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Ja},vu="RFC1738";var cs=(t,e)=>(cs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cs(t,e)),Le=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Qa=1024,Tu=(t,e,r,o,n)=>{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(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=Qa){let u=s.length>=Qa?s.slice(i,i+Qa):s,l=[];for(let d=0;d<u.length;++d){let p=u.charCodeAt(d);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===vu&&(p===40||p===41)){l[l.length]=u.charAt(d);continue}if(p<128){l[l.length]=Le[p];continue}if(p<2048){l[l.length]=Le[192|p>>6]+Le[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Le[224|p>>12]+Le[128|p>>6&63]+Le[128|p&63];continue}d+=1,p=65536+((p&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Le[240|p>>18]+Le[128|p>>12&63]+Le[128|p>>6&63]+Le[128|p&63]}a+=l.join("")}return a};function Su(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Ya(t,e){if(de(t)){let r=[];for(let o=0;o<t.length;o+=1)r.push(e(t[o]));return r}return e(t)}var ku={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Eu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},Cu,te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Tu,encodeValuesOnly:!1,format:Ha,formatter:Ja,indices:!1,serializeDate(t){return(Cu??(Cu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Pf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Xa={};function Mu(t,e,r,o,n,s,a,i,u,l,d,p,f,x,w,b,y,S){let h=t,I=S,k=0,U=!1;for(;(I=I.get(Xa))!==void 0&&!U;){let Q=I.get(t);if(k+=1,typeof Q<"u"){if(Q===k)throw new RangeError("Cyclic object value");U=!0}typeof I.get(Xa)>"u"&&(k=0)}if(typeof l=="function"?h=l(e,h):h instanceof Date?h=f?.(h):r==="comma"&&de(h)&&(h=Ya(h,function(Q){return Q instanceof Date?f?.(Q):Q})),h===null){if(s)return u&&!b?u(e,te.encoder,y,"key",x):e;h=""}if(Pf(h)||Su(h)){if(u){let Q=b?e:u(e,te.encoder,y,"key",x);return[w?.(Q)+"="+w?.(u(h,te.encoder,y,"value",x))]}return[w?.(e)+"="+w?.(String(h))]}let q=[];if(typeof h>"u")return q;let G;if(r==="comma"&&de(h))b&&u&&(h=Ya(h,u)),G=[{value:h.length>0?h.join(",")||null:void 0}];else if(de(l))G=l;else{let Q=Object.keys(h);G=d?Q.sort(d):Q}let H=i?String(e).replace(/\./g,"%2E"):String(e),le=o&&de(h)&&h.length===1?H+"[]":H;if(n&&de(h)&&h.length===0)return le+"[]";for(let Q=0;Q<G.length;++Q){let ee=G[Q],cl=typeof ee=="object"&&typeof ee.value<"u"?ee.value:h[ee];if(a&&cl===null)continue;let ha=p&&i?ee.replace(/\./g,"%2E"):ee,cm=de(h)?typeof r=="function"?r(le,ha):le:le+(p?"."+ha:"["+ha+"]");S.set(t,k);let dl=new WeakMap;dl.set(Xa,S),Eu(q,Mu(cl,cm,r,o,n,s,a,i,r==="comma"&&b&&de(h)?null:u,l,d,p,f,x,w,b,y,dl))}return q}function Of(t=te){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||te.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=Ha;if(typeof t.format<"u"){if(!cs(Za,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let o=Za[r],n=te.filter;(typeof t.filter=="function"||de(t.filter))&&(n=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in ku?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=te.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:te.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:te.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:te.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:te.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?te.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:te.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:te.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:te.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:te.encodeValuesOnly,filter:n,format:r,formatter:o,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:te.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:te.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:te.strictNullHandling}}function Pu(t,e={}){let r=t,o=Of(e),n,s;typeof o.filter=="function"?(s=o.filter,r=s("",r)):de(o.filter)&&(s=o.filter,n=s);let a=[];if(typeof r!="object"||r===null)return"";let i=ku[o.arrayFormat],u=i==="comma"&&o.commaRoundTrip;n||(n=Object.keys(r)),o.sort&&n.sort(o.sort);let l=new WeakMap;for(let f=0;f<n.length;++f){let x=n[f];o.skipNulls&&r[x]===null||Eu(a,Mu(r[x],x,i,u,o.allowEmptyArrays,o.strictNullHandling,o.skipNulls,o.encodeDotInKeys,o.encode?o.encoder:null,o.filter,o.sort,o.allowDots,o.serializeDate,o.format,o.formatter,o.encodeValuesOnly,o.charset,l))}let d=a.join(o.delimiter),p=o.addQueryPrefix===!0?"?":"";return o.charsetSentinel&&(o.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),d.length>0?p+d:""}function Ou(t){return Pu(t,{arrayFormat:"brackets"})}function $u(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}var Ru;function Rr(t){let e;return(Ru??(e=new globalThis.TextEncoder,Ru=e.encode.bind(e)))(t)}var Nu;function ei(t){let e;return(Nu??(e=new globalThis.TextDecoder,Nu=e.decode.bind(e)))(t)}var ye,_e,$t=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),P(this,ye,new Uint8Array,"f"),P(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Rr(e):e;P(this,ye,$u([_(this,ye,"f"),r]),"f");let o=[],n;for(;(n=Nf(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(n.carriage&&_(this,_e,"f")==null){P(this,_e,n.index,"f");continue}if(_(this,_e,"f")!=null&&(n.index!==_(this,_e,"f")+1||n.carriage)){o.push(ei(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),P(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),P(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?n.preceding-1:n.preceding,a=ei(_(this,ye,"f").subarray(0,s));o.push(a),P(this,ye,_(this,ye,"f").subarray(n.index),"f"),P(this,_e,null,"f")}return o}flush(){return _(this,ye,"f").length?this.decode(`
|
|
43
|
-
`):[]}};ye=new WeakMap,_e=new WeakMap
|
|
44
|
-
`,"\r"])
|
|
45
|
-
`);o.enqueue(a)}catch(n){o.error(n)}},async cancel(){await r.return?.()}})}};async function*zf(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("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 C("Attempted to iterate over a response with no body");let r=new ri,o=new
|
|
46
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,o,n]=jf(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function jf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ms(t,e){let{response:r,requestLogID:o,retryOfRequestLogID:n,startTime:s}=e,a=await(async()=>{if(e.options.stream)return Z(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):je.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 f=await r.json();return oi(f,r)}return await r.text()})();return Z(t).debug(`[${o}] response parsed`,Ke({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}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 pn,zt=class t extends Promise{constructor(e,r,o=ms){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=o,pn.set(this,void 0),P(this,pn,e,"f")}_thenUnwrap(e){return new t(_(this,pn,"f"),this.responsePromise,async(r,o)=>oi(e(await this.parseResponse(r,o),o),o.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(_(this,pn,"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)}};pn=new WeakMap;var fs,Nr=class{constructor(e,r,o,n){fs.set(this,void 0),P(this,fs,e,"f"),this.options=n,this.response=r,this.body=o}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,fs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},mn=class extends zt{constructor(e,r,o){super(e,r,async(n,s)=>new o(n,s.response,await ms(n,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.object=o.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},N=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.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:{...is(this.options.query),after:r}}:null}},L=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.has_more||!1,this.last_id=o.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:{...is(this.options.query),after:e}}:null}},X=class extends Nr{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.has_more||!1,this.next=o.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:{...is(this.options.query),after:e}}:null}};var Ff={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Uf="urn:ietf:params:oauth:grant-type:token-exchange",hs=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ls()}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={grant_type:Uf,subject_token:e,subject_token_type:Ff[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let o=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){let u=await o.text(),l;try{l=JSON.parse(u)}catch{}throw o.status===400||o.status===401||o.status===403?new Nt(o.status,l,o.headers):V.generate(o.status,l,`Token exchange failed with status ${o.status}`,o.headers)}let n=await o.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new C("Token exchange response missing 'access_token' field");let s=n.access_token,a=n.expires_in??3600,i=Date.now()+a*1e3;return this.cachedToken={token:s,expiresAt:i},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let o=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-o}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var ai=()=>{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 $r(t,e,r){return ai(),new File(t,e??"unknown_file",r)}function fn(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 gs=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pt=async(t,e)=>ni(t.body)?{...t,body:await Du(t.body,e)}:t,me=async(t,e)=>({...t,body:await Du(t.body,e)}),ju=new WeakMap;function qf(t){let e=typeof t=="function"?t:t.fetch,r=ju.get(e);if(r)return r;let o=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new n(s).text()}catch{return!0}})();return ju.set(e,o),o}var Du=async(t,e)=>{if(!await qf(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(([o,n])=>si(r,o,n))),r},Fu=t=>t instanceof Blob&&"name"in t,Bf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||gs(t)||Fu(t)),ni=t=>{if(Bf(t))return!0;if(Array.isArray(t))return t.some(ni);if(t&&typeof t=="object"){for(let e in t)if(ni(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,$r([await r.blob()],fn(r)));else if(gs(r))t.append(e,$r([await new Response(us(r)).blob()],fn(r)));else if(Fu(r))t.append(e,r,fn(r));else if(Array.isArray(r))await Promise.all(r.map(o=>si(t,e+"[]",o)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([o,n])=>si(t,`${e}[${o}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Uu=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",Kf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Uu(t),Gf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function hn(t,e,r){if(ai(),t=await t,Kf(t))return t instanceof File?t:$r([await t.arrayBuffer()],t.name);if(Gf(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),$r(await ii(n),e,r)}let o=await ii(t);if(e||(e=fn(t)),!r?.type){let n=o.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof n=="string"&&(r={...r,type:n})}return $r(o,e,r)}async function ii(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Uu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(gs(t))for await(let r of t)e.push(...await ii(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Vf(t)}`)}return e}function Vf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function Bu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var qu=Object.freeze(Object.create(null)),Hf=(t=Bu)=>function(r,...o){if(r.length===1)return r[0];let n=!1,s=[],a=r.reduce((d,p,f)=>{/[?#]/.test(p)&&(n=!0);let x=o[f],w=(n?encodeURIComponent:t)(""+x);return f!==o.length&&(x==null||typeof x=="object"&&x.toString===Object.getPrototypeOf(Object.getPrototypeOf(x.hasOwnProperty??qu)??qu)?.toString)&&(w=x+"",s.push({start:d.length+p.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(x).slice(8,-1)} is not a valid path parameter`})),d+p+(f===o.length?"":w)},""),i=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(i))!==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((d,p)=>d.start-p.start),s.length>0){let d=0,p=s.reduce((f,x)=>{let w=" ".repeat(x.start-d),b="^".repeat(x.length);return d=x.start+x.length,f+w+b},"");throw new C(`Path parameters result in path with invalid segments:
|
|
42
|
+
`,t}function P(t,e,r,o,n){if(o==="m")throw new TypeError("Private method is not writable");if(o==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function _(t,e,r,o){if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?o:r==="a"?o.call(t):o?o.value:e.get(t)}var qa=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return qa=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,o=>(+o^r()&15>>+o/4).toString(16))};function sn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var an=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 C=class extends Error{},V=class t extends C{constructor(e,r,o,n){super(`${t.makeMessage(e,r,o)}`),this.status=e,this.headers=n,this.requestID=n?.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,o){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):o;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,o,n){if(!e||!n)return new ct({message:o,cause:an(r)});let s=r?.error;return e===400?new Ir(e,s,o,n):e===401?new vr(e,s,o,n):e===403?new Tr(e,s,o,n):e===404?new Sr(e,s,o,n):e===409?new Cr(e,s,o,n):e===422?new kr(e,s,o,n):e===429?new Er(e,s,o,n):e>=500?new Mr(e,s,o,n):new t(e,s,o,n)}},W=class extends V{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends V{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},$e=class extends ct{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ir=class extends V{},vr=class extends V{},Tr=class extends V{},Sr=class extends V{},Cr=class extends V{},kr=class extends V{},Er=class extends V{},Mr=class extends V{},Pr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Or=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ne=class extends Error{constructor(e){super(e)}},$t=class extends V{constructor(e,r,o){let n="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?n=i:s&&(n=s)}super(e,r,n,o),this.error_code=s}},ln=class extends C{constructor(e,r,o){super(e),this.provider=r,this.cause=o}};var Sf=/^[a-z][a-z0-9+.-]*:/i,mu=t=>Sf.test(t),de=t=>(de=Array.isArray,de(t)),Ba=de;function is(t){return typeof t!="object"?{}:t??{}}function Ka(t){if(!t)return!0;for(let e in t)return!1;return!0}function fu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function un(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var hu=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var gu=t=>{try{return JSON.parse(t)}catch{return}};var ze=t=>new Promise(e=>setTimeout(e,t));var dt="6.45.0";var bu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Cf(){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 kf=()=>{let t=Cf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":_u(Deno.build.os),"X-Stainless-Arch":yu(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":dt,"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":dt,"X-Stainless-OS":_u(globalThis.process.platform??"unknown"),"X-Stainless-Arch":yu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ef();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"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":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ef(){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 o=r.exec(navigator.userAgent);if(o){let n=o[1]||0,s=o[2]||0,a=o[3]||0;return{browser:e,version:`${n}.${s}.${a}`}}}return null}var yu=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",_u=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"),wu,Au=()=>wu??(wu=kf());function ls(){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 Ga(...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 us(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ga({start(){},async pull(r){let{done:o,value:n}=await e.next();o?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function Va(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 Wa(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 Iu=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ha="RFC3986",Ja=t=>String(t),Za={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Ja},vu="RFC1738";var cs=(t,e)=>(cs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cs(t,e)),Le=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Qa=1024,Tu=(t,e,r,o,n)=>{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(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=Qa){let u=s.length>=Qa?s.slice(i,i+Qa):s,l=[];for(let d=0;d<u.length;++d){let p=u.charCodeAt(d);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===vu&&(p===40||p===41)){l[l.length]=u.charAt(d);continue}if(p<128){l[l.length]=Le[p];continue}if(p<2048){l[l.length]=Le[192|p>>6]+Le[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Le[224|p>>12]+Le[128|p>>6&63]+Le[128|p&63];continue}d+=1,p=65536+((p&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Le[240|p>>18]+Le[128|p>>12&63]+Le[128|p>>6&63]+Le[128|p&63]}a+=l.join("")}return a};function Su(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Ya(t,e){if(de(t)){let r=[];for(let o=0;o<t.length;o+=1)r.push(e(t[o]));return r}return e(t)}var ku={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Eu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},Cu,te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Tu,encodeValuesOnly:!1,format:Ha,formatter:Ja,indices:!1,serializeDate(t){return(Cu??(Cu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Pf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Xa={};function Mu(t,e,r,o,n,s,a,i,u,l,d,p,f,x,w,b,y,S){let h=t,I=S,k=0,U=!1;for(;(I=I.get(Xa))!==void 0&&!U;){let Q=I.get(t);if(k+=1,typeof Q<"u"){if(Q===k)throw new RangeError("Cyclic object value");U=!0}typeof I.get(Xa)>"u"&&(k=0)}if(typeof l=="function"?h=l(e,h):h instanceof Date?h=f?.(h):r==="comma"&&de(h)&&(h=Ya(h,function(Q){return Q instanceof Date?f?.(Q):Q})),h===null){if(s)return u&&!b?u(e,te.encoder,y,"key",x):e;h=""}if(Pf(h)||Su(h)){if(u){let Q=b?e:u(e,te.encoder,y,"key",x);return[w?.(Q)+"="+w?.(u(h,te.encoder,y,"value",x))]}return[w?.(e)+"="+w?.(String(h))]}let q=[];if(typeof h>"u")return q;let G;if(r==="comma"&&de(h))b&&u&&(h=Ya(h,u)),G=[{value:h.length>0?h.join(",")||null:void 0}];else if(de(l))G=l;else{let Q=Object.keys(h);G=d?Q.sort(d):Q}let H=i?String(e).replace(/\./g,"%2E"):String(e),le=o&&de(h)&&h.length===1?H+"[]":H;if(n&&de(h)&&h.length===0)return le+"[]";for(let Q=0;Q<G.length;++Q){let ee=G[Q],cl=typeof ee=="object"&&typeof ee.value<"u"?ee.value:h[ee];if(a&&cl===null)continue;let ha=p&&i?ee.replace(/\./g,"%2E"):ee,cm=de(h)?typeof r=="function"?r(le,ha):le:le+(p?"."+ha:"["+ha+"]");S.set(t,k);let dl=new WeakMap;dl.set(Xa,S),Eu(q,Mu(cl,cm,r,o,n,s,a,i,r==="comma"&&b&&de(h)?null:u,l,d,p,f,x,w,b,y,dl))}return q}function Of(t=te){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||te.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=Ha;if(typeof t.format<"u"){if(!cs(Za,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let o=Za[r],n=te.filter;(typeof t.filter=="function"||de(t.filter))&&(n=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in ku?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=te.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:te.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:te.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:te.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:te.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?te.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:te.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:te.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:te.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:te.encodeValuesOnly,filter:n,format:r,formatter:o,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:te.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:te.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:te.strictNullHandling}}function Pu(t,e={}){let r=t,o=Of(e),n,s;typeof o.filter=="function"?(s=o.filter,r=s("",r)):de(o.filter)&&(s=o.filter,n=s);let a=[];if(typeof r!="object"||r===null)return"";let i=ku[o.arrayFormat],u=i==="comma"&&o.commaRoundTrip;n||(n=Object.keys(r)),o.sort&&n.sort(o.sort);let l=new WeakMap;for(let f=0;f<n.length;++f){let x=n[f];o.skipNulls&&r[x]===null||Eu(a,Mu(r[x],x,i,u,o.allowEmptyArrays,o.strictNullHandling,o.skipNulls,o.encodeDotInKeys,o.encode?o.encoder:null,o.filter,o.sort,o.allowDots,o.serializeDate,o.format,o.formatter,o.encodeValuesOnly,o.charset,l))}let d=a.join(o.delimiter),p=o.addQueryPrefix===!0?"?":"";return o.charsetSentinel&&(o.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),d.length>0?p+d:""}function Ou(t){return Pu(t,{arrayFormat:"brackets"})}function Nu(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}var Ru;function Rr(t){let e;return(Ru??(e=new globalThis.TextEncoder,Ru=e.encode.bind(e)))(t)}var $u;function ei(t){let e;return($u??(e=new globalThis.TextDecoder,$u=e.decode.bind(e)))(t)}var ye,_e,Nt=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),P(this,ye,new Uint8Array,"f"),P(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Rr(e):e;P(this,ye,Nu([_(this,ye,"f"),r]),"f");let o=[],n;for(;(n=$f(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(n.carriage&&_(this,_e,"f")==null){P(this,_e,n.index,"f");continue}if(_(this,_e,"f")!=null&&(n.index!==_(this,_e,"f")+1||n.carriage)){o.push(ei(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),P(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),P(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?n.preceding-1:n.preceding,a=ei(_(this,ye,"f").subarray(0,s));o.push(a),P(this,ye,_(this,ye,"f").subarray(n.index),"f"),P(this,_e,null,"f")}return o}flush(){return _(this,ye,"f").length?this.decode(`
|
|
43
|
+
`):[]}};ye=new WeakMap,_e=new WeakMap;Nt.NEWLINE_CHARS=new Set([`
|
|
44
|
+
`,"\r"]);Nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function $f(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function zu(t){for(let o=0;o<t.length-1;o++){if(t[o]===10&&t[o+1]===10||t[o]===13&&t[o+1]===13)return o+2;if(t[o]===13&&t[o+1]===10&&o+3<t.length&&t[o+2]===13&&t[o+3]===10)return o+4}return-1}var ps={off:0,error:200,warn:300,info:400,debug:500},ti=(t,e,r)=>{if(t){if(fu(ps,t))return t;Z(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ps))}`)}};function cn(){}function ds(t,e,r){return!e||ps[t]>ps[r]?cn:e[t].bind(e)}var Nf={error:cn,warn:cn,info:cn,debug:cn},Lu=new WeakMap;function Z(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Nf;let o=Lu.get(e);if(o&&o[0]===r)return o[1];let n={error:ds("error",e,r),warn:ds("warn",e,r),info:ds("info",e,r),debug:ds("debug",e,r)};return Lu.set(e,[r,n]),n}var Ke=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()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var dn,je=class t{constructor(e,r,o){this.iterator=e,dn.set(this,void 0),this.controller=r,P(this,dn,o,"f")}static fromSSEResponse(e,r,o,n){let s=!1,a=o?Z(o):console;async function*i(){if(s)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of zf(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let d;try{d=JSON.parse(l.data)}catch(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(d&&d.error)throw new V(void 0,d.error,void 0,e.headers);yield n?{event:l.event,data:d}:d}else{let d;try{d=JSON.parse(l.data)}catch(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new V(void 0,d.error,d.message,void 0);yield{event:l.event,data:d}}}u=!0}catch(l){if(sn(l))return;throw l}finally{u||r.abort()}}return new t(i,r,o)}static fromReadableStream(e,r,o){let n=!1;async function*s(){let i=new Nt,u=Va(e);for await(let l of u)for(let d of i.decode(l))yield d;for(let l of i.flush())yield l}async function*a(){if(n)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(sn(u))return;throw u}finally{i||r.abort()}}return new t(a,r,o)}[(dn=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],o=this.iterator(),n=s=>({next:()=>{if(s.length===0){let a=o.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>n(e),this.controller,_(this,dn,"f")),new t(()=>n(r),this.controller,_(this,dn,"f"))]}toReadableStream(){let e=this,r;return Ga({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:n,done:s}=await r.next();if(s)return o.close();let a=Rr(JSON.stringify(n)+`
|
|
45
|
+
`);o.enqueue(a)}catch(n){o.error(n)}},async cancel(){await r.return?.()}})}};async function*zf(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("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 C("Attempted to iterate over a response with no body");let r=new ri,o=new Nt,n=Va(t.body);for await(let s of Lf(n))for(let a of o.decode(s)){let i=r.decode(a);i&&(yield i)}for(let s of o.flush()){let a=r.decode(s);a&&(yield a)}}async function*Lf(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let o=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Rr(r):r,n=new Uint8Array(e.length+o.length);n.set(e),n.set(o,e.length),e=n;let s;for(;(s=zu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ri=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(`
|
|
46
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,o,n]=jf(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function jf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ms(t,e){let{response:r,requestLogID:o,retryOfRequestLogID:n,startTime:s}=e,a=await(async()=>{if(e.options.stream)return Z(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):je.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 f=await r.json();return oi(f,r)}return await r.text()})();return Z(t).debug(`[${o}] response parsed`,Ke({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}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 pn,zt=class t extends Promise{constructor(e,r,o=ms){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=o,pn.set(this,void 0),P(this,pn,e,"f")}_thenUnwrap(e){return new t(_(this,pn,"f"),this.responsePromise,async(r,o)=>oi(e(await this.parseResponse(r,o),o),o.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(_(this,pn,"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)}};pn=new WeakMap;var fs,$r=class{constructor(e,r,o,n){fs.set(this,void 0),P(this,fs,e,"f"),this.options=n,this.response=r,this.body=o}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,fs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},mn=class extends zt{constructor(e,r,o){super(e,r,async(n,s)=>new o(n,s.response,await ms(n,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends $r{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.object=o.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},$=class extends $r{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.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:{...is(this.options.query),after:r}}:null}},L=class extends $r{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.has_more||!1,this.last_id=o.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:{...is(this.options.query),after:e}}:null}},X=class extends $r{constructor(e,r,o,n){super(e,r,o,n),this.data=o.data||[],this.has_more=o.has_more||!1,this.next=o.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:{...is(this.options.query),after:e}}:null}};var Ff={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Uf="urn:ietf:params:oauth:grant-type:token-exchange",hs=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ls()}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={grant_type:Uf,subject_token:e,subject_token_type:Ff[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let o=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){let u=await o.text(),l;try{l=JSON.parse(u)}catch{}throw o.status===400||o.status===401||o.status===403?new $t(o.status,l,o.headers):V.generate(o.status,l,`Token exchange failed with status ${o.status}`,o.headers)}let n=await o.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new C("Token exchange response missing 'access_token' field");let s=n.access_token,a=n.expires_in??3600,i=Date.now()+a*1e3;return this.cachedToken={token:s,expiresAt:i},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let o=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-o}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var ai=()=>{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 Nr(t,e,r){return ai(),new File(t,e??"unknown_file",r)}function fn(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 gs=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pt=async(t,e)=>ni(t.body)?{...t,body:await Du(t.body,e)}:t,me=async(t,e)=>({...t,body:await Du(t.body,e)}),ju=new WeakMap;function qf(t){let e=typeof t=="function"?t:t.fetch,r=ju.get(e);if(r)return r;let o=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new n(s).text()}catch{return!0}})();return ju.set(e,o),o}var Du=async(t,e)=>{if(!await qf(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(([o,n])=>si(r,o,n))),r},Fu=t=>t instanceof Blob&&"name"in t,Bf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||gs(t)||Fu(t)),ni=t=>{if(Bf(t))return!0;if(Array.isArray(t))return t.some(ni);if(t&&typeof t=="object"){for(let e in t)if(ni(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,Nr([await r.blob()],fn(r)));else if(gs(r))t.append(e,Nr([await new Response(us(r)).blob()],fn(r)));else if(Fu(r))t.append(e,r,fn(r));else if(Array.isArray(r))await Promise.all(r.map(o=>si(t,e+"[]",o)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([o,n])=>si(t,`${e}[${o}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Uu=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",Kf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Uu(t),Gf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function hn(t,e,r){if(ai(),t=await t,Kf(t))return t instanceof File?t:Nr([await t.arrayBuffer()],t.name);if(Gf(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Nr(await ii(n),e,r)}let o=await ii(t);if(e||(e=fn(t)),!r?.type){let n=o.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof n=="string"&&(r={...r,type:n})}return Nr(o,e,r)}async function ii(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Uu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(gs(t))for await(let r of t)e.push(...await ii(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Vf(t)}`)}return e}function Vf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function Bu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var qu=Object.freeze(Object.create(null)),Hf=(t=Bu)=>function(r,...o){if(r.length===1)return r[0];let n=!1,s=[],a=r.reduce((d,p,f)=>{/[?#]/.test(p)&&(n=!0);let x=o[f],w=(n?encodeURIComponent:t)(""+x);return f!==o.length&&(x==null||typeof x=="object"&&x.toString===Object.getPrototypeOf(Object.getPrototypeOf(x.hasOwnProperty??qu)??qu)?.toString)&&(w=x+"",s.push({start:d.length+p.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(x).slice(8,-1)} is not a valid path parameter`})),d+p+(f===o.length?"":w)},""),i=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(i))!==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((d,p)=>d.start-p.start),s.length>0){let d=0,p=s.reduce((f,x)=>{let w=" ".repeat(x.start-d),b="^".repeat(x.length);return d=x.start+x.length,f+w+b},"");throw new C(`Path parameters result in path with invalid segments:
|
|
47
47
|
${s.map(f=>f.error).join(`
|
|
48
48
|
`)}
|
|
49
49
|
${a}
|
|
50
|
-
${p}`)}return a},m=Hf(Bu);var Lt=class extends g{list(e,r={},o){return this._client.getAPIList(m`/chat/completions/${e}/messages`,N,{query:r,...o,__security:{bearerAuth:!0}})}};function gn(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Gu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function yn(t){return t?.$brand==="auto-parseable-response-format"}function jt(t){return t?.$brand==="auto-parseable-tool"}function Vu(t,e){return!e||!li(e)?{...t,choices:t.choices.map(r=>(Hu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:_n(t,e)}function _n(t,e){let r=t.choices.map(o=>{if(o.finish_reason==="length")throw new Pr;if(o.finish_reason==="content_filter")throw new Or;return Hu(o.message.tool_calls),{...o,message:{...o.message,...o.message.tool_calls?{tool_calls:o.message.tool_calls?.map(n=>Qf(e,n))??void 0}:void 0,parsed:o.message.content&&!o.message.refusal?Zf(e,o.message.content):null}}});return{...t,choices:r}}function Zf(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 Qf(t,e){let r=t.tools?.find(o=>gn(o)&&o.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:jt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Wu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(o=>gn(o)&&o.function?.name===e.function.name);return gn(r)&&(jt(r)||r?.function.strict||!1)}function li(t){return yn(t.response_format)?!0:t.tools?.some(e=>jt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Hu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ju(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var zr=t=>t?.role==="assistant",ui=t=>t?.role==="tool";var ys,_s,ws,wn,bn,bs,An,Ge,As,xn,xs,Is,Lr,Zu,Qu,mt=class{constructor(){ys.add(this),this.controller=new AbortController,_s.set(this,void 0),ws.set(this,()=>{}),wn.set(this,()=>{}),bn.set(this,void 0),bs.set(this,()=>{}),An.set(this,()=>{}),Ge.set(this,{}),As.set(this,[]),xn.set(this,!1),xs.set(this,!1),Is.set(this,!1),Lr.set(this,!1),P(this,_s,new Promise((e,r)=>{P(this,ws,e,"f"),P(this,wn,r,"f")}),"f"),P(this,bn,new Promise((e,r)=>{P(this,bs,e,"f"),P(this,An,r,"f")}),"f"),_(this,_s,"f").catch(()=>{}),_(this,bn,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,ys,"m",Qu).bind(this))},0)}_connected(){this.ended||(_(this,ws,"f").call(this),this._emit("connect"))}get ended(){return _(this,xn,"f")}get errored(){return _(this,xs,"f")}get aborted(){return _(this,Is,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),_(this,As,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ge,"f")[e]||(_(this,Ge,"f")[e]=[])).push({listener:r}),this}off(e,r){let o=_(this,Ge,"f")[e];if(!o)return this;let n=o.findIndex(s=>s.listener===r);return n>=0&&o.splice(n,1),this}once(e,r){return(_(this,Ge,"f")[e]||(_(this,Ge,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,o)=>{P(this,Lr,!0,"f"),e!=="error"&&this.once("error",o),this.once(e,r)})}async done(){P(this,Lr,!0,"f"),await _(this,bn,"f")}_emit(e,...r){if(_(this,xn,"f"))return;e==="end"&&(_(this,ys,"m",Zu).call(this),P(this,xn,!0,"f"),_(this,bs,"f").call(this));let o=_(this,Ge,"f")[e];if(o&&(_(this,Ge,"f")[e]=o.filter(n=>!n.once),o.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!_(this,Lr,"f")&&!o?.length&&Promise.reject(n),_(this,wn,"f").call(this,n),_(this,An,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!_(this,Lr,"f")&&!o?.length&&Promise.reject(n),_(this,wn,"f").call(this,n),_(this,An,"f").call(this,n),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,ws=new WeakMap,wn=new WeakMap,bn=new WeakMap,bs=new WeakMap,An=new WeakMap,Ge=new WeakMap,As=new WeakMap,xn=new WeakMap,xs=new WeakMap,Is=new WeakMap,Lr=new WeakMap,ys=new WeakSet,Zu=function(){for(let{signal:e,listener:r}of _(this,As,"f").splice(0))e.removeEventListener("abort",r)},Qu=function(e){if(P(this,xs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new W),e instanceof W)return P(this,Is,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function Yu(t){return typeof t.parse=="function"}var he,ci,vs,di,pi,mi,Xu,ec,Yf=10,jr=class extends mt{constructor(){super(...arguments),he.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),ui(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(zr(e)&&e.tool_calls)for(let o of e.tool_calls)o.type==="function"&&this._emit("functionToolCall",o.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,he,"m",ci).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",vs).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",di).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",pi).call(this)}async totalUsage(){return await this.done(),_(this,he,"m",mi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,he,"m",vs).call(this);r&&this._emit("finalMessage",r);let o=_(this,he,"m",ci).call(this);o&&this._emit("finalContent",o);let n=_(this,he,"m",di).call(this);n&&this._emit("finalFunctionToolCall",n);let s=_(this,he,"m",pi).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,he,"m",mi).call(this))}async _createChatCompletion(e,r,o){this._listenForAbort(o?.signal),_(this,he,"m",Xu).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...o,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_n(n,r))}async _runChatCompletion(e,r,o){for(let n of r.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,r,o)}async _runTools(e,r,o,n){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=Yf,afterCompletion:p}=n||{},f=r.tools.map(y=>{if(jt(y)){if(!y.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),x={};for(let y of f)y.type==="function"&&(x[y.function.name||y.function.function.name]=y.function);let w="tools"in r?f.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(let y of r.messages)this._addMessage(y,!1);let b=async y=>{if(y.type!=="function")return{message:void 0,functionCalled:!1};let S=y.id,{name:h,arguments:I}=y.function,k=x[h];if(!k){let G=`Invalid tool_call: ${JSON.stringify(h)}. Available options are: ${Object.keys(x).map(H=>JSON.stringify(H)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:S,content:G},functionCalled:!1}}if(l&&l!==h){let G=`Invalid tool_call: ${JSON.stringify(h)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:S,content:G},functionCalled:!1}}let U;if(Yu(k)){let G;try{G=await k.parse(I)}catch(H){let le=H instanceof Error?H.message:String(H);return{message:{role:s,tool_call_id:S,content:le},functionCalled:!1}}U=await k.function(G,o)}else U=await k.function(I,o);let q=_(this,he,"m",ec).call(this,U);return{message:{role:s,tool_call_id:S,content:q},functionCalled:!0}};for(let y=0;y<d;++y){let S=await this._createChatCompletion(e,{...u,tool_choice:a,tools:w,messages:[...this.messages]},n),h=S.choices[0]?.message;if(!h)throw new C("missing message in ChatCompletion response");if(!h.tool_calls?.length){await p?.(S,o);return}if(l||r.parallel_tool_calls===!1)for(let I of h.tool_calls){let k=await b(I);if(k.message&&this._addMessage(k.message),l&&k.functionCalled){await p?.(S,o);return}}else{let I=await Promise.allSettled(h.tool_calls.map(b));for(let k of I)if(k.status==="rejected")throw k.reason;for(let k of I)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message)}await p?.(S,o)}}};he=new WeakSet,ci=function(){return _(this,he,"m",vs).call(this).content??null},vs=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(zr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},di=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(zr(r)&&r?.tool_calls?.length)for(let o=r.tool_calls.length-1;o>=0;o--){let n=r.tool_calls[o];if(n?.type==="function")return n.function}}},pi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ui(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(o=>o.role==="assistant"&&o.tool_calls?.some(n=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}},mi=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},Xu=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ec=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var In=class t extends jr{static runTools(e,r,o){let n=new t,s={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,s)),n}_addMessage(e,r=!0){super._addMessage(e,r),zr(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},fi=class extends Error{},hi=class extends Error{};function Xf(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 eh(t.trim(),e)}var eh=(t,e)=>{let r=t.length,o=0,n=f=>{throw new fi(`${f} at position ${o}`)},s=f=>{throw new hi(`${f} at position ${o}`)},a=()=>(p(),o>=r&&n("Unexpected end of input"),t[o]==='"'?i():t[o]==="{"?u():t[o]==="["?l():t.substring(o,o+4)==="null"||ne.NULL&e&&r-o<4&&"null".startsWith(t.substring(o))?(o+=4,null):t.substring(o,o+4)==="true"||ne.BOOL&e&&r-o<4&&"true".startsWith(t.substring(o))?(o+=4,!0):t.substring(o,o+5)==="false"||ne.BOOL&e&&r-o<5&&"false".startsWith(t.substring(o))?(o+=5,!1):t.substring(o,o+8)==="Infinity"||ne.INFINITY&e&&r-o<8&&"Infinity".startsWith(t.substring(o))?(o+=8,1/0):t.substring(o,o+9)==="-Infinity"||ne.MINUS_INFINITY&e&&1<r-o&&r-o<9&&"-Infinity".startsWith(t.substring(o))?(o+=9,-1/0):t.substring(o,o+3)==="NaN"||ne.NAN&e&&r-o<3&&"NaN".startsWith(t.substring(o))?(o+=3,NaN):d()),i=()=>{let f=o,x=!1;for(o++;o<r&&(t[o]!=='"'||x&&t[o-1]==="\\");)x=t[o]==="\\"?!x:!1,o++;if(t.charAt(o)=='"')try{return JSON.parse(t.substring(f,++o-Number(x)))}catch(w){s(String(w))}else if(ne.STR&e)try{return JSON.parse(t.substring(f,o-Number(x))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{o++,p();let f={};try{for(;t[o]!=="}";){if(p(),o>=r&&ne.OBJ&e)return f;let x=i();p(),o++;try{let w=a();Object.defineProperty(f,x,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(ne.OBJ&e)return f;throw w}p(),t[o]===","&&o++}}catch{if(ne.OBJ&e)return f;n("Expected '}' at end of object")}return o++,f},l=()=>{o++;let f=[];try{for(;t[o]!=="]";)f.push(a()),p(),t[o]===","&&o++}catch{if(ne.ARR&e)return f;n("Expected ']' at end of array")}return o++,f},d=()=>{if(o===0){t==="-"&&ne.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t)}catch(x){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(x))}}let f=o;for(t[o]==="-"&&o++;t[o]&&!",]}".includes(t[o]);)o++;o==r&&!(ne.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(t.substring(f,o))}catch{t.substring(f,o)==="-"&&ne.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},p=()=>{for(;o<r&&`
|
|
50
|
+
${p}`)}return a},m=Hf(Bu);var Lt=class extends g{list(e,r={},o){return this._client.getAPIList(m`/chat/completions/${e}/messages`,$,{query:r,...o,__security:{bearerAuth:!0}})}};function gn(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Gu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function yn(t){return t?.$brand==="auto-parseable-response-format"}function jt(t){return t?.$brand==="auto-parseable-tool"}function Vu(t,e){return!e||!li(e)?{...t,choices:t.choices.map(r=>(Hu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:_n(t,e)}function _n(t,e){let r=t.choices.map(o=>{if(o.finish_reason==="length")throw new Pr;if(o.finish_reason==="content_filter")throw new Or;return Hu(o.message.tool_calls),{...o,message:{...o.message,...o.message.tool_calls?{tool_calls:o.message.tool_calls?.map(n=>Qf(e,n))??void 0}:void 0,parsed:o.message.content&&!o.message.refusal?Zf(e,o.message.content):null}}});return{...t,choices:r}}function Zf(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 Qf(t,e){let r=t.tools?.find(o=>gn(o)&&o.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:jt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Wu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(o=>gn(o)&&o.function?.name===e.function.name);return gn(r)&&(jt(r)||r?.function.strict||!1)}function li(t){return yn(t.response_format)?!0:t.tools?.some(e=>jt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Hu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ju(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var zr=t=>t?.role==="assistant",ui=t=>t?.role==="tool";var ys,_s,ws,wn,bn,bs,An,Ge,As,xn,xs,Is,Lr,Zu,Qu,mt=class{constructor(){ys.add(this),this.controller=new AbortController,_s.set(this,void 0),ws.set(this,()=>{}),wn.set(this,()=>{}),bn.set(this,void 0),bs.set(this,()=>{}),An.set(this,()=>{}),Ge.set(this,{}),As.set(this,[]),xn.set(this,!1),xs.set(this,!1),Is.set(this,!1),Lr.set(this,!1),P(this,_s,new Promise((e,r)=>{P(this,ws,e,"f"),P(this,wn,r,"f")}),"f"),P(this,bn,new Promise((e,r)=>{P(this,bs,e,"f"),P(this,An,r,"f")}),"f"),_(this,_s,"f").catch(()=>{}),_(this,bn,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,ys,"m",Qu).bind(this))},0)}_connected(){this.ended||(_(this,ws,"f").call(this),this._emit("connect"))}get ended(){return _(this,xn,"f")}get errored(){return _(this,xs,"f")}get aborted(){return _(this,Is,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),_(this,As,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ge,"f")[e]||(_(this,Ge,"f")[e]=[])).push({listener:r}),this}off(e,r){let o=_(this,Ge,"f")[e];if(!o)return this;let n=o.findIndex(s=>s.listener===r);return n>=0&&o.splice(n,1),this}once(e,r){return(_(this,Ge,"f")[e]||(_(this,Ge,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,o)=>{P(this,Lr,!0,"f"),e!=="error"&&this.once("error",o),this.once(e,r)})}async done(){P(this,Lr,!0,"f"),await _(this,bn,"f")}_emit(e,...r){if(_(this,xn,"f"))return;e==="end"&&(_(this,ys,"m",Zu).call(this),P(this,xn,!0,"f"),_(this,bs,"f").call(this));let o=_(this,Ge,"f")[e];if(o&&(_(this,Ge,"f")[e]=o.filter(n=>!n.once),o.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!_(this,Lr,"f")&&!o?.length&&Promise.reject(n),_(this,wn,"f").call(this,n),_(this,An,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!_(this,Lr,"f")&&!o?.length&&Promise.reject(n),_(this,wn,"f").call(this,n),_(this,An,"f").call(this,n),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,ws=new WeakMap,wn=new WeakMap,bn=new WeakMap,bs=new WeakMap,An=new WeakMap,Ge=new WeakMap,As=new WeakMap,xn=new WeakMap,xs=new WeakMap,Is=new WeakMap,Lr=new WeakMap,ys=new WeakSet,Zu=function(){for(let{signal:e,listener:r}of _(this,As,"f").splice(0))e.removeEventListener("abort",r)},Qu=function(e){if(P(this,xs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new W),e instanceof W)return P(this,Is,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function Yu(t){return typeof t.parse=="function"}var he,ci,vs,di,pi,mi,Xu,ec,Yf=10,jr=class extends mt{constructor(){super(...arguments),he.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),ui(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(zr(e)&&e.tool_calls)for(let o of e.tool_calls)o.type==="function"&&this._emit("functionToolCall",o.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,he,"m",ci).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",vs).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",di).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",pi).call(this)}async totalUsage(){return await this.done(),_(this,he,"m",mi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,he,"m",vs).call(this);r&&this._emit("finalMessage",r);let o=_(this,he,"m",ci).call(this);o&&this._emit("finalContent",o);let n=_(this,he,"m",di).call(this);n&&this._emit("finalFunctionToolCall",n);let s=_(this,he,"m",pi).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,he,"m",mi).call(this))}async _createChatCompletion(e,r,o){this._listenForAbort(o?.signal),_(this,he,"m",Xu).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...o,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_n(n,r))}async _runChatCompletion(e,r,o){for(let n of r.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,r,o)}async _runTools(e,r,o,n){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=Yf,afterCompletion:p}=n||{},f=r.tools.map(y=>{if(jt(y)){if(!y.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),x={};for(let y of f)y.type==="function"&&(x[y.function.name||y.function.function.name]=y.function);let w="tools"in r?f.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(let y of r.messages)this._addMessage(y,!1);let b=async y=>{if(y.type!=="function")return{message:void 0,functionCalled:!1};let S=y.id,{name:h,arguments:I}=y.function,k=x[h];if(!k){let G=`Invalid tool_call: ${JSON.stringify(h)}. Available options are: ${Object.keys(x).map(H=>JSON.stringify(H)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:S,content:G},functionCalled:!1}}if(l&&l!==h){let G=`Invalid tool_call: ${JSON.stringify(h)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:S,content:G},functionCalled:!1}}let U;if(Yu(k)){let G;try{G=await k.parse(I)}catch(H){let le=H instanceof Error?H.message:String(H);return{message:{role:s,tool_call_id:S,content:le},functionCalled:!1}}U=await k.function(G,o)}else U=await k.function(I,o);let q=_(this,he,"m",ec).call(this,U);return{message:{role:s,tool_call_id:S,content:q},functionCalled:!0}};for(let y=0;y<d;++y){let S=await this._createChatCompletion(e,{...u,tool_choice:a,tools:w,messages:[...this.messages]},n),h=S.choices[0]?.message;if(!h)throw new C("missing message in ChatCompletion response");if(!h.tool_calls?.length){await p?.(S,o);return}if(l||r.parallel_tool_calls===!1)for(let I of h.tool_calls){let k=await b(I);if(k.message&&this._addMessage(k.message),l&&k.functionCalled){await p?.(S,o);return}}else{let I=await Promise.allSettled(h.tool_calls.map(b));for(let k of I)if(k.status==="rejected")throw k.reason;for(let k of I)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message)}await p?.(S,o)}}};he=new WeakSet,ci=function(){return _(this,he,"m",vs).call(this).content??null},vs=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(zr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},di=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(zr(r)&&r?.tool_calls?.length)for(let o=r.tool_calls.length-1;o>=0;o--){let n=r.tool_calls[o];if(n?.type==="function")return n.function}}},pi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ui(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(o=>o.role==="assistant"&&o.tool_calls?.some(n=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}},mi=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},Xu=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ec=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var In=class t extends jr{static runTools(e,r,o){let n=new t,s={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,s)),n}_addMessage(e,r=!0){super._addMessage(e,r),zr(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},fi=class extends Error{},hi=class extends Error{};function Xf(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 eh(t.trim(),e)}var eh=(t,e)=>{let r=t.length,o=0,n=f=>{throw new fi(`${f} at position ${o}`)},s=f=>{throw new hi(`${f} at position ${o}`)},a=()=>(p(),o>=r&&n("Unexpected end of input"),t[o]==='"'?i():t[o]==="{"?u():t[o]==="["?l():t.substring(o,o+4)==="null"||ne.NULL&e&&r-o<4&&"null".startsWith(t.substring(o))?(o+=4,null):t.substring(o,o+4)==="true"||ne.BOOL&e&&r-o<4&&"true".startsWith(t.substring(o))?(o+=4,!0):t.substring(o,o+5)==="false"||ne.BOOL&e&&r-o<5&&"false".startsWith(t.substring(o))?(o+=5,!1):t.substring(o,o+8)==="Infinity"||ne.INFINITY&e&&r-o<8&&"Infinity".startsWith(t.substring(o))?(o+=8,1/0):t.substring(o,o+9)==="-Infinity"||ne.MINUS_INFINITY&e&&1<r-o&&r-o<9&&"-Infinity".startsWith(t.substring(o))?(o+=9,-1/0):t.substring(o,o+3)==="NaN"||ne.NAN&e&&r-o<3&&"NaN".startsWith(t.substring(o))?(o+=3,NaN):d()),i=()=>{let f=o,x=!1;for(o++;o<r&&(t[o]!=='"'||x&&t[o-1]==="\\");)x=t[o]==="\\"?!x:!1,o++;if(t.charAt(o)=='"')try{return JSON.parse(t.substring(f,++o-Number(x)))}catch(w){s(String(w))}else if(ne.STR&e)try{return JSON.parse(t.substring(f,o-Number(x))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{o++,p();let f={};try{for(;t[o]!=="}";){if(p(),o>=r&&ne.OBJ&e)return f;let x=i();p(),o++;try{let w=a();Object.defineProperty(f,x,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(ne.OBJ&e)return f;throw w}p(),t[o]===","&&o++}}catch{if(ne.OBJ&e)return f;n("Expected '}' at end of object")}return o++,f},l=()=>{o++;let f=[];try{for(;t[o]!=="]";)f.push(a()),p(),t[o]===","&&o++}catch{if(ne.ARR&e)return f;n("Expected ']' at end of array")}return o++,f},d=()=>{if(o===0){t==="-"&&ne.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t)}catch(x){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(x))}}let f=o;for(t[o]==="-"&&o++;t[o]&&!",]}".includes(t[o]);)o++;o==r&&!(ne.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(t.substring(f,o))}catch{t.substring(f,o)==="-"&&ne.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},p=()=>{for(;o<r&&`
|
|
51
51
|
\r `.includes(t[o]);)o++};return a()},gi=t=>Xf(t,ne.ALL^ne.NUM);var re,Ve,Dr,ft,yi,Ts,_i,wi,bi,Ss,Ai,tc,Dt=class t extends jr{constructor(e){super(),re.add(this),Ve.set(this,void 0),Dr.set(this,void 0),ft.set(this,void 0),P(this,Ve,e,"f"),P(this,Dr,[],"f")}get currentChatCompletionSnapshot(){return _(this,ft,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,o){let n=new t(r);return n._run(()=>n._runChatCompletion(e,{...r,stream:!0},{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,r,o){super._createChatCompletion,this._listenForAbort(o?.signal),_(this,re,"m",yi).call(this);let n=await e.chat.completions.create({...r,stream:!0},{...o,signal:this.controller.signal});this._connected();for await(let s of n)_(this,re,"m",_i).call(this,s);if(n.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,re,"m",Ss).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,re,"m",yi).call(this),this._connected();let o=je.fromReadableStream(e,this.controller),n;for await(let s of o)n&&n!==s.id&&this._addChatCompletion(_(this,re,"m",Ss).call(this)),_(this,re,"m",_i).call(this,s),n=s.id;if(o.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,re,"m",Ss).call(this))}[(Ve=new WeakMap,Dr=new WeakMap,ft=new WeakMap,re=new WeakSet,yi=function(){this.ended||P(this,ft,void 0,"f")},Ts=function(r){let o=_(this,Dr,"f")[r.index];return o||(o={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},_(this,Dr,"f")[r.index]=o,o)},_i=function(r){if(this.ended)return;let o=_(this,re,"m",tc).call(this,r);this._emit("chunk",r,o);for(let n of r.choices){let s=o.choices[n.index];n.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",n.delta.content,s.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),n.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:s.message.refusal}),n.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:s.logprobs?.content??[]}),n.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=_(this,re,"m",Ts).call(this,s);s.finish_reason&&(_(this,re,"m",bi).call(this,s),a.current_tool_call_index!=null&&_(this,re,"m",wi).call(this,s,a.current_tool_call_index));for(let i of n.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(_(this,re,"m",bi).call(this,s),a.current_tool_call_index!=null&&_(this,re,"m",wi).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of n.delta.tool_calls??[]){let u=s.message.tool_calls?.[i.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:i.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:i.function?.arguments??""}):(u?.type,void 0))}}},wi=function(r,o){if(_(this,re,"m",Ts).call(this,r).done_tool_calls.has(o))return;let s=r.message.tool_calls?.[o];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 a=_(this,Ve,"f")?.tools?.find(i=>gn(i)&&i.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:o,arguments:s.function.arguments,parsed_arguments:jt(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},bi=function(r){let o=_(this,re,"m",Ts).call(this,r);if(r.message.content&&!o.content_done){o.content_done=!0;let n=_(this,re,"m",Ai).call(this);this._emit("content.done",{content:r.message.content,parsed:n?n.$parseRaw(r.message.content):null})}r.message.refusal&&!o.refusal_done&&(o.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!o.logprobs_content_done&&(o.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!o.logprobs_refusal_done&&(o.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Ss=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,ft,"f");if(!r)throw new C("request ended without sending any chunks");return P(this,ft,void 0,"f"),P(this,Dr,[],"f"),th(r,_(this,Ve,"f"))},Ai=function(){let r=_(this,Ve,"f")?.response_format;return yn(r)?r:null},tc=function(r){var o,n,s,a;let i=_(this,ft,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=P(this,ft,{...l,choices:[]},"f");for(let{delta:d,finish_reason:p,index:f,logprobs:x=null,...w}of r.choices){let b=i.choices[f];if(b||(b=i.choices[f]={finish_reason:p,index:f,message:{},logprobs:x,...w}),x)if(!b.logprobs)b.logprobs=Object.assign({},x);else{let{content:q,refusal:G,...H}=x;Object.assign(b.logprobs,H),q&&((o=b.logprobs).content??(o.content=[]),b.logprobs.content.push(...q)),G&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...G))}if(p&&(b.finish_reason=p,_(this,Ve,"f")&&li(_(this,Ve,"f")))){if(p==="length")throw new Pr;if(p==="content_filter")throw new Or}if(Object.assign(b,w),!d)continue;let{content:y,refusal:S,function_call:h,role:I,tool_calls:k,...U}=d;if(Object.assign(b.message,U),S&&(b.message.refusal=(b.message.refusal||"")+S),I&&(b.message.role=I),h&&(b.message.function_call?(h.name&&(b.message.function_call.name=h.name),h.arguments&&((s=b.message.function_call).arguments??(s.arguments=""),b.message.function_call.arguments+=h.arguments)):b.message.function_call=h),y&&(b.message.content=(b.message.content||"")+y,!b.message.refusal&&_(this,re,"m",Ai).call(this)&&(b.message.parsed=b.message.content.trim()?gi(b.message.content):null)),k){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:q,id:G,type:H,function:le,...Q}of k){let ee=(a=b.message.tool_calls)[q]??(a[q]={});Object.assign(ee,Q),G&&(ee.id=G),H&&(ee.type=H),le&&(ee.function??(ee.function={name:le.name??"",arguments:""})),le?.name&&(ee.function.name=le.name),le?.arguments&&(ee.function.arguments+=le.arguments,Wu(_(this,Ve,"f"),ee)&&(ee.function.parsed_arguments=gi(ee.function.arguments)))}}}return i},Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("chunk",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function th(t,e){let{id:r,choices:o,created:n,model:s,system_fingerprint:a,...i}=t,u={...i,id:r,choices:o.map(({message:l,finish_reason:d,index:p,logprobs:f,...x})=>{if(!d)throw new C(`missing finish_reason for choice ${p}`);let{content:w=null,function_call:b,tool_calls:y,...S}=l,h=l.role;if(!h)throw new C(`missing role for choice ${p}`);if(b){let{arguments:I,name:k}=b;if(I==null)throw new C(`missing function_call.arguments for choice ${p}`);if(!k)throw new C(`missing function_call.name for choice ${p}`);return{...x,message:{content:w,function_call:{arguments:I,name:k},role:h,refusal:l.refusal??null},finish_reason:d,index:p,logprobs:f}}return y?{...x,index:p,finish_reason:d,logprobs:f,message:{...S,role:h,content:w,refusal:l.refusal??null,tool_calls:y.map((I,k)=>{let{function:U,type:q,id:G,...H}=I,{arguments:le,name:Q,...ee}=U||{};if(G==null)throw new C(`missing choices[${p}].tool_calls[${k}].id
|
|
52
52
|
${Cs(t)}`);if(q==null)throw new C(`missing choices[${p}].tool_calls[${k}].type
|
|
53
53
|
${Cs(t)}`);if(Q==null)throw new C(`missing choices[${p}].tool_calls[${k}].function.name
|
|
54
54
|
${Cs(t)}`);if(le==null)throw new C(`missing choices[${p}].tool_calls[${k}].function.arguments
|
|
55
|
-
${Cs(t)}`);return{...H,id:G,type:q,function:{...ee,name:Q,arguments:le}}})}}:{...x,message:{...S,content:w,role:h,refusal:l.refusal??null},finish_reason:d,index:p,logprobs:f}}),created:n,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Vu(u,e)}function Cs(t){return JSON.stringify(t)}var vn=class t extends Dt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,o){let n=new t(r),s={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,s)),n}};var We=class extends g{constructor(){super(...arguments),this.messages=new Lt(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(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/chat/completions/${e}`,{body:r,...o,__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(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Ju(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(o=>_n(o,e))}runTools(e,r){return e.stream?vn.runTools(this._client,e,r):In.runTools(this._client,e,r)}stream(e,r){return Dt.createChatCompletion(this._client,e,r)}};We.Messages=Lt;var ht=class extends g{constructor(){super(...arguments),this.completions=new We(this._client)}};ht.Completions=We;var Fr=class extends g{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/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(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},o){return this._client.get(m`/organization/certificates/${e}`,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/certificates/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends g{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends g{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends g{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/roles/${e}`,{body:r,...o,__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(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends g{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/spend_alerts/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends g{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}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{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}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends g{create(e,r,o){return this._client.post(m`/organization/groups/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{group_id:n}=r;return this._client.get(m`/organization/groups/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/groups/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{group_id:n}=r;return this._client.delete(m`/organization/groups/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{create(e,r,o){return this._client.post(m`/organization/groups/${e}/users`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{group_id:n}=r;return this._client.get(m`/organization/groups/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/groups/${e}/users`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{group_id:n}=r;return this._client.delete(m`/organization/groups/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var gt=class extends g{constructor(){super(...arguments),this.users=new Jr(this._client),this.roles=new Hr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/groups/${e}`,{body:r,...o,__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(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};gt.Users=Jr;gt.Roles=Hr;var Zr=class extends g{retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/api_keys/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/api_keys`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/api_keys/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends g{list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/certificates`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}activate(e,r,o){return this._client.getAPIList(m`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,o){return this._client.getAPIList(m`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/data_retention`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}};var eo=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/model_permissions`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var to=class extends g{listRateLimits(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/rate_limits`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/rate_limits/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}};var ro=class extends g{create(e,r,o){return this._client.post(m`/projects/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/projects/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/roles/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/projects/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/projects/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var oo=class extends g{create(e,r,o){return this._client.post(m`/organization/projects/${e}/service_accounts`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/service_accounts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/service_accounts/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/service_accounts`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/service_accounts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var no=class extends g{create(e,r,o){return this._client.post(m`/organization/projects/${e}/spend_alerts`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/spend_alerts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/spend_alerts/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/spend_alerts`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/spend_alerts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var so=class extends g{create(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/groups/${e}/roles`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,group_id:s}=r;return this._client.get(m`/projects/${n}/groups/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r,o){let{project_id:n,...s}=r;return this._client.getAPIList(m`/projects/${n}/groups/${e}/roles`,X,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n,group_id:s}=r;return this._client.delete(m`/projects/${n}/groups/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends g{constructor(){super(...arguments),this.roles=new so(this._client)}create(e,r,o){return this._client.post(m`/organization/projects/${e}/groups`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,...s}=r;return this._client.get(m`/organization/projects/${n}/groups/${e}`,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/groups`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/groups/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};Ft.Roles=so;var ao=class extends g{create(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/users/${e}/roles`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,user_id:s}=r;return this._client.get(m`/projects/${n}/users/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r,o){let{project_id:n,...s}=r;return this._client.getAPIList(m`/projects/${n}/users/${e}/roles`,X,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n,user_id:s}=r;return this._client.delete(m`/projects/${n}/users/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends g{constructor(){super(...arguments),this.roles=new ao(this._client)}create(e,r,o){return this._client.post(m`/organization/projects/${e}/users`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/users/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/users`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};Ut.Roles=ao;var se=class extends g{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new oo(this._client),this.apiKeys=new Zr(this._client),this.rateLimits=new to(this._client),this.modelPermissions=new eo(this._client),this.hostedToolPermissions=new Xr(this._client),this.groups=new Ft(this._client),this.roles=new ro(this._client),this.dataRetention=new Yr(this._client),this.spendAlerts=new no(this._client),this.certificates=new Qr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(m`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};se.Users=Ut;se.ServiceAccounts=oo;se.APIKeys=Zr;se.RateLimits=to;se.ModelPermissions=eo;se.HostedToolPermissions=Xr;se.Groups=Ft;se.Roles=ro;se.DataRetention=Yr;se.SpendAlerts=no;se.Certificates=Qr;var io=class extends g{create(e,r,o){return this._client.post(m`/organization/users/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{user_id:n}=r;return this._client.get(m`/organization/users/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/users/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{user_id:n}=r;return this._client.delete(m`/organization/users/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends g{constructor(){super(...arguments),this.roles=new io(this._client)}retrieve(e,r){return this._client.get(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/users/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=io;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new Ur(this._client),this.adminAPIKeys=new Fr(this._client),this.usage=new Wr(this._client),this.invites=new Kr(this._client),this.users=new qt(this._client),this.groups=new gt(this._client),this.roles=new Gr(this._client),this.dataRetention=new Br(this._client),this.spendAlerts=new Vr(this._client),this.certificates=new qr(this._client),this.projects=new se(this._client)}};ae.AuditLogs=Ur;ae.AdminAPIKeys=Fr;ae.Usage=Wr;ae.Invites=Kr;ae.Users=qt;ae.Groups=gt;ae.Roles=Gr;ae.DataRetention=Br;ae.SpendAlerts=Vr;ae.Certificates=qr;ae.Projects=se;var yt=class extends g{constructor(){super(...arguments),this.organization=new ae(this._client)}};yt.Organization=ae;var rc=Symbol("brand.privateNullableHeaders");function*Ph(t){if(!t)return;if(rc in t){let{values:o,nulls:n}=t;yield*o.entries();for(let s of n)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Ba(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let o of r){let n=o[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let s=Ba(o[1])?o[1]:[o[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,i])}}var T=t=>{let e=new Headers,r=new Set;for(let o of t){let n=new Set;for(let[s,a]of Ph(o)){let i=s.toLowerCase();n.has(i)||(e.delete(s),n.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[rc]:!0,values:e,nulls:r}};var lo=class extends g{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:T([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var uo=class extends g{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var co=class extends g{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var De=class extends g{constructor(){super(...arguments),this.transcriptions=new uo(this._client),this.translations=new co(this._client),this.speech=new lo(this._client)}};De.Transcriptions=uo;De.Translations=co;De.Speech=lo;var Bt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/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(m`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var po=class extends g{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/assistants/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",N,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var mo=class extends g{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var fo=class extends g{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var _t=class extends g{constructor(){super(...arguments),this.sessions=new mo(this._client),this.transcriptionSessions=new fo(this._client)}};_t.Sessions=mo;_t.TranscriptionSessions=fo;var ho=class extends g{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var go=class extends g{retrieve(e,r){return this._client.get(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",L,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},o){return this._client.getAPIList(m`/chatkit/threads/${e}/items`,L,{query:r,...o,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},o?.headers]),__security:{bearerAuth:!0}})}};var wt=class extends g{constructor(){super(...arguments),this.sessions=new ho(this._client),this.threads=new go(this._client)}};wt.Sessions=ho;wt.Threads=go;var yo=class extends g{create(e,r,o){return this._client.post(m`/threads/${e}/messages`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{thread_id:n}=r;return this._client.get(m`/threads/${n}/messages/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/messages/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/threads/${e}/messages`,N,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r,o){let{thread_id:n}=r;return this._client.delete(m`/threads/${n}/messages/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var _o=class extends g{retrieve(e,r,o){let{thread_id:n,run_id:s,...a}=r;return this._client.get(m`/threads/${n}/runs/${s}/steps/${e}`,{query:a,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r,o){let{thread_id:n,...s}=r;return this._client.getAPIList(m`/threads/${n}/runs/${e}/steps`,N,{query:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var oc=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,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=e.charCodeAt(n);return Array.from(new Float32Array(o.buffer))}};var Te=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 ie,Gt,xi,Fe,ks,Se,Vt,wo,Kt,Ps,we,Es,Ms,Cn,Tn,Sn,nc,sc,ac,ic,lc,uc,cc,He=class extends mt{constructor(){super(...arguments),ie.add(this),xi.set(this,[]),Fe.set(this,{}),ks.set(this,{}),Se.set(this,void 0),Vt.set(this,void 0),wo.set(this,void 0),Kt.set(this,void 0),Ps.set(this,void 0),we.set(this,void 0),Es.set(this,void 0),Ms.set(this,void 0),Cn.set(this,void 0)}[(xi=new WeakMap,Fe=new WeakMap,ks=new WeakMap,Se=new WeakMap,Vt=new WeakMap,wo=new WeakMap,Kt=new WeakMap,Ps=new WeakMap,we=new WeakMap,Es=new WeakMap,Ms=new WeakMap,Cn=new WeakMap,ie=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("event",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).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 Gt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let o=je.fromReadableStream(e,this.controller);for await(let n of o)_(this,ie,"m",Tn).call(this,n);if(o.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,o,n){let s=new Gt;return s._run(()=>s._runToolAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,o,n){this._listenForAbort(n?.signal);let s={...o,stream:!0},a=await e.submitToolOutputs(r,s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ie,"m",Tn).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}static createThreadAssistantStream(e,r,o){let n=new Gt;return n._run(()=>n._threadAssistantStream(e,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,r,o,n){let s=new Gt;return s._run(()=>s._runAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Es,"f")}currentRun(){return _(this,Ms,"f")}currentMessageSnapshot(){return _(this,Se,"f")}currentRunStepSnapshot(){return _(this,Cn,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ks,"f"))}async finalRun(){if(await this.done(),!_(this,Vt,"f"))throw Error("Final run was not received.");return _(this,Vt,"f")}async _createThreadAssistantStream(e,r,o){this._listenForAbort(o?.signal);let n={...r,stream:!0},s=await e.createAndRun(n,{...o,signal:this.controller.signal});this._connected();for await(let a of s)_(this,ie,"m",Tn).call(this,a);if(s.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}async _createAssistantStream(e,r,o,n){this._listenForAbort(n?.signal);let s={...o,stream:!0},a=await e.create(r,s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ie,"m",Tn).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}static accumulateDelta(e,r){for(let[o,n]of Object.entries(r)){if(!e.hasOwnProperty(o)){e[o]=n;continue}let s=e[o];if(s==null){e[o]=n;continue}if(o==="index"||o==="type"){e[o]=n;continue}if(typeof s=="string"&&typeof n=="string")s+=n;else if(typeof s=="number"&&typeof n=="number")s+=n;else if(un(s)&&un(n))s=this.accumulateDelta(s,n);else if(Array.isArray(s)&&Array.isArray(n)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...n);continue}for(let a of n){if(!un(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);let u=s[i];u==null?s.push(a):s[i]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${o}, deltaValue: ${n}, accValue: ${s}`);e[o]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,o){return await this._createThreadAssistantStream(r,e,o)}async _runAssistantStream(e,r,o,n){return await this._createAssistantStream(r,e,o,n)}async _runToolAssistantStream(e,r,o,n){return await this._createToolAssistantStream(r,e,o,n)}};Gt=He,Tn=function(e){if(!this.ended)switch(P(this,Es,e,"f"),_(this,ie,"m",ac).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":_(this,ie,"m",cc).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":_(this,ie,"m",sc).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":_(this,ie,"m",nc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Sn=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Vt,"f"))throw Error("Final run has not been received");return _(this,Vt,"f")},nc=function(e){let[r,o]=_(this,ie,"m",lc).call(this,e,_(this,Se,"f"));P(this,Se,r,"f"),_(this,ks,"f")[r.id]=r;for(let n of o){let s=r.content[n.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 n of e.data.delta.content){if(n.type=="text"&&n.text){let s=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",s,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=_(this,wo,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Se,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Se,"f"));break}P(this,wo,n.index,"f")}P(this,Kt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,wo,"f")!==void 0){let n=e.data.content[_(this,wo,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,_(this,Se,"f"));break;case"text":this._emit("textDone",n.text,_(this,Se,"f"));break}}_(this,Se,"f")&&this._emit("messageDone",e.data),P(this,Se,void 0,"f")}},sc=function(e){let r=_(this,ie,"m",ic).call(this,e);switch(P(this,Cn,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let o=e.data.delta;if(o.step_details&&o.step_details.type=="tool_calls"&&o.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of o.step_details.tool_calls)s.index==_(this,Ps,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),P(this,Ps,s.index,"f"),P(this,we,r.step_details.tool_calls[s.index],"f"),_(this,we,"f")&&this._emit("toolCallCreated",_(this,we,"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":P(this,Cn,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),P(this,we,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},ac=function(e){_(this,xi,"f").push(e),this._emit("event",e)},ic=function(e){switch(e.event){case"thread.run.step.created":return _(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Fe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let o=e.data;if(o.delta){let n=Gt.accumulateDelta(r,o.delta);_(this,Fe,"f")[e.data.id]=n}return _(this,Fe,"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":_(this,Fe,"f")[e.data.id]=e.data;break}if(_(this,Fe,"f")[e.data.id])return _(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},lc=function(e,r){let o=[];switch(e.event){case"thread.message.created":return[e.data,o];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let s of n.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=_(this,ie,"m",uc).call(this,s,a)}else r.content[s.index]=s,o.push(s);return[r,o];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,o];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},uc=function(e,r){return Gt.accumulateDelta(r,e)},cc=function(e){switch(P(this,Ms,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":P(this,Vt,e.data,"f"),_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),P(this,we,void 0,"f"));break;case"thread.run.cancelling":break}};var Wt=class extends g{constructor(){super(...arguments),this.steps=new _o(this._client)}create(e,r,o){let{include:n,...s}=r;return this._client.post(m`/threads/${e}/runs`,{query:{include:n},body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{thread_id:n}=r;return this._client.get(m`/threads/${n}/runs/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/runs/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/threads/${e}/runs`,N,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,o){let{thread_id:n}=r;return this._client.post(m`/threads/${n}/runs/${e}/cancel`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r,o);return await this.poll(n.id,{thread_id:e},o)}createAndStream(e,r,o){return He.createAssistantStream(e,this._client.beta.threads.runs,r,o)}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...o,headers:{...o?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,o){return He.createAssistantStream(e,this._client.beta.threads.runs,r,o)}submitToolOutputs(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,o){let n=await this.submitToolOutputs(e,r,o);return await this.poll(n.id,r,o)}submitToolOutputsStream(e,r,o){return He.createToolAssistantStream(e,this._client.beta.threads.runs,r,o)}};Wt.Steps=_o;var bt=class extends g{constructor(){super(...arguments),this.runs=new Wt(this._client),this.messages=new yo(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/threads/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let o=await this.createAndRun(e,r);return await this.runs.poll(o.id,{thread_id:o.thread_id},r)}createAndRunStream(e,r){return He.createThreadAssistantStream(e,this._client.beta.threads,r)}};bt.Runs=Wt;bt.Messages=yo;var Ce=class extends g{constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new wt(this._client),this.assistants=new po(this._client),this.threads=new bt(this._client)}};Ce.Realtime=_t;Ce.ChatKit=wt;Ce.Assistants=po;Ce.Threads=bt;var Ht=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var bo=class extends g{retrieve(e,r,o){let{container_id:n}=r;return this._client.get(m`/containers/${n}/files/${e}/content`,{...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Jt=class extends g{constructor(){super(...arguments),this.content=new bo(this._client)}create(e,r,o){return this._client.post(m`/containers/${e}/files`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,o){let{container_id:n}=r;return this._client.get(m`/containers/${n}/files/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/containers/${e}/files`,N,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{container_id:n}=r;return this._client.delete(m`/containers/${n}/files/${e}`,{...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}};Jt.Content=bo;var At=class extends g{constructor(){super(...arguments),this.files=new Jt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/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(m`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};At.Files=Jt;var Ao=class extends g{create(e,r,o){let{include:n,...s}=r;return this._client.post(m`/conversations/${e}/items`,{query:{include:n},body:s,...o,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{conversation_id:n,...s}=r;return this._client.get(m`/conversations/${n}/items/${e}`,{query:s,...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/conversations/${e}/items`,L,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{conversation_id:n}=r;return this._client.delete(m`/conversations/${n}/items/${e}`,{...o,__security:{bearerAuth:!0}})}};var xt=class extends g{constructor(){super(...arguments),this.items=new Ao(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/conversations/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};xt.Items=Ao;var Zt=class extends g{create(e,r){let o=!!e.encoding_format,n=o?e.encoding_format:"base64";o&&Z(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:n},...r,__security:{bearerAuth:!0}});return o?s:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let u=i.embedding;i.embedding=oc(u)}),a)))}};var xo=class extends g{retrieve(e,r,o){let{eval_id:n,run_id:s}=r;return this._client.get(m`/evals/${n}/runs/${s}/output_items/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r,o){let{eval_id:n,...s}=r;return this._client.getAPIList(m`/evals/${n}/runs/${e}/output_items`,N,{query:s,...o,__security:{bearerAuth:!0}})}};var Qt=class extends g{constructor(){super(...arguments),this.outputItems=new xo(this._client)}create(e,r,o){return this._client.post(m`/evals/${e}/runs`,{body:r,...o,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{eval_id:n}=r;return this._client.get(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/evals/${e}/runs`,N,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{eval_id:n}=r;return this._client.delete(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}cancel(e,r,o){let{eval_id:n}=r;return this._client.post(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}};Qt.OutputItems=xo;var It=class extends g{constructor(){super(...arguments),this.runs=new Qt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/evals/${e}`,{body:r,...o,__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(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};It.Runs=Qt;var Yt=class extends g{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/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(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(m`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:o=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await ze(r),a=await this.retrieve(e),Date.now()-s>o)throw new Ne({message:`Giving up on waiting for file ${e} to finish processing after ${o} milliseconds.`});return a}};var Io=class extends g{};var vo=class extends g{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 Xt=class extends g{constructor(){super(...arguments),this.graders=new vo(this._client)}};Xt.Graders=vo;var To=class extends g{create(e,r,o){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},o){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{fine_tuned_model_checkpoint:n}=r;return this._client.delete(m`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var er=class extends g{constructor(){super(...arguments),this.permissions=new To(this._client)}};er.Permissions=To;var So=class extends g{list(e,r={},o){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,N,{query:r,...o,__security:{bearerAuth:!0}})}};var tr=class extends g{constructor(){super(...arguments),this.checkpoints=new So(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(m`/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(m`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},o){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,N,{query:r,...o,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};tr.Checkpoints=So;var ke=class extends g{constructor(){super(...arguments),this.methods=new Io(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};ke.Methods=Io;ke.Jobs=tr;ke.Checkpoints=er;ke.Alpha=Xt;var Co=class extends g{};var vt=class extends g{constructor(){super(...arguments),this.graderModels=new Co(this._client)}};vt.GraderModels=Co;var rr=class extends g{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({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 g{retrieve(e,r){return this._client.get(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var nr=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var ko=class extends g{accept(e,r,o){return this._client.post(m`/realtime/calls/${e}/accept`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(m`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,o){return this._client.post(m`/realtime/calls/${e}/refer`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},o){return this._client.post(m`/realtime/calls/${e}/reject`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}};var Eo=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Je=class extends g{constructor(){super(...arguments),this.clientSecrets=new Eo(this._client),this.calls=new ko(this._client)}};Je.ClientSecrets=Eo;Je.Calls=ko;function dc(t,e){if(!e||!lg(e)){let r={...t,output_parsed:null,output:t.output.map(o=>o.type==="function_call"?{...o,parsed_arguments:null}:o.type==="message"?{...o,content:o.content.map(n=>({...n,parsed:null}))}:o)};return pc(t,r)&&be(r),r}return Ii(t,e)}function Ii(t,e){let r=!t.status||t.status==="completed",o=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?dg(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?ig(e,i.text):null}:i);return{...s,content:a}}return s}),n=Object.assign({},t,{output:o});return pc(t,n)&&be(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function ig(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function lg(t){return!!yn(t.text?.format)}function ug(t){return t?.$brand==="auto-parseable-tool"}function cg(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function dg(t,e){let r=cg(t.tools??[],e.name);return{...e,...e,parsed_arguments:ug(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function pc(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function be(t){let e=[];for(let r of t.output)if(r.type==="message")for(let o of r.content)o.type==="output_text"&&e.push(o.text);t.output_text=e.join("")}function fc(t,e){if(!e){if(t.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return mc(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&be(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&be(e);break}case"response.content_part.added":{let r=z(e,t.output_index),o=r.type,n=t.part;o==="message"&&n.type!=="reasoning_text"?(r.content.push(structuredClone(n)),n.type==="output_text"&&be(e)):o==="reasoning"&&n.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(n)));break}case"response.content_part.done":{let r=z(e,t.output_index),o=t.part;if(r.type==="message"&&o.type!=="reasoning_text")Ae(r.content,t.content_index),r.content[t.content_index]=structuredClone(o),o.type==="output_text"&&be(e);else if(r.type==="reasoning"&&o.type==="reasoning_text"){let n=r.content;if(!n)throw new C(`missing content at index ${t.content_index}`);Ae(n,t.content_index),n[t.content_index]=structuredClone(o)}break}case"response.output_text.delta":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.text=t.text,be(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="refusal")throw new C(`expected content to be 'refusal', got ${o.type}`);o.refusal+=t.delta}break}case"response.refusal.done":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="refusal")throw new C(`expected content to be 'refusal', got ${o.type}`);o.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=z(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=z(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=z(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let o=Ae(r.content,t.content_index);if(o.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.reasoning_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let o=Ae(r.content,t.content_index);if(o.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${o.type}`);o.text=t.text}break}case"response.reasoning_summary_part.added":{let r=z(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=z(e,t.output_index);r.type==="reasoning"&&(Ae(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=z(e,t.output_index);if(r.type==="reasoning"){let o=Ae(r.summary,t.summary_index);o.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){let o=Ae(r.summary,t.summary_index);o.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=z(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=z(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=mc(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:pg(t)}return e}function mc(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&be(e),e}function z(t,e){let r=t.output[e];if(!r)throw new C(`missing output at index ${e}`);return r}function Ae(t,e){let r=t[e];if(!r)throw new C(`missing content at index ${e}`);return r}function pg(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var kn,Os,sr,Rs,hc,gc,yc,Ns=class t extends mt{constructor(e){super(),kn.add(this),Os.set(this,void 0),sr.set(this,void 0),Rs.set(this,void 0),P(this,Os,e,"f")}static createResponse(e,r,o){let n=new t(r);return n._run(()=>n._createOrRetrieveResponse(e,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,r,o){this._listenForAbort(o?.signal),_(this,kn,"m",hc).call(this);let n,s=null;"response_id"in r?(n=await e.responses.retrieve(r.response_id,{stream:!0},{...o,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):n=await e.responses.create({...r,stream:!0},{...o,signal:this.controller.signal}),this._connected();for await(let a of n)_(this,kn,"m",gc).call(this,a,s);if(n.controller.signal?.aborted)throw new W;return _(this,kn,"m",yc).call(this)}[(Os=new WeakMap,sr=new WeakMap,Rs=new WeakMap,kn=new WeakSet,hc=function(){this.ended||P(this,sr,void 0,"f")},gc=function(r,o){if(this.ended)return;let n=(a,i)=>{(o==null||i.sequence_number>o)&&this._emit(a,i)},s=fc(r,_(this,sr,"f"));switch(P(this,sr,s,"f"),n("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new C(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new C(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new C(`expected content to be 'output_text', got ${i.type}`);n("response.output_text.delta",{...r,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=s.output[r.output_index];if(!a)throw new C(`missing output at index ${r.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:n(r.type,r);break}},yc=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,sr,"f");if(!r)throw new C("request ended without sending any events");P(this,sr,void 0,"f");let o=mg(r,_(this,Os,"f"));return P(this,Rs,o,"f"),o},Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("event",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).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=_(this,Rs,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function mg(t,e){return dc(t,e)}var Mo=class extends g{list(e,r={},o){return this._client.getAPIList(m`/responses/${e}/input_items`,N,{query:r,...o,__security:{bearerAuth:!0}})}};var Po=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Ue=class extends g{constructor(){super(...arguments),this.inputItems=new Mo(this._client),this.inputTokens=new Po(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&be(o),o))}retrieve(e,r={},o){return this._client.get(m`/responses/${e}`,{query:r,...o,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&be(n),n))}delete(e,r){return this._client.delete(m`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(o=>Ii(o,e))}stream(e,r){return Ns.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(m`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};Ue.InputItems=Mo;Ue.InputTokens=Po;var Oo=class extends g{retrieve(e,r){return this._client.get(m`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Ro=class extends g{retrieve(e,r,o){let{skill_id:n}=r;return this._client.get(m`/skills/${n}/versions/${e}/content`,{...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ar=class extends g{constructor(){super(...arguments),this.content=new Ro(this._client)}create(e,r={},o){return this._client.post(m`/skills/${e}/versions`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,o){let{skill_id:n}=r;return this._client.get(m`/skills/${n}/versions/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/skills/${e}/versions`,N,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{skill_id:n}=r;return this._client.delete(m`/skills/${n}/versions/${e}`,{...o,__security:{bearerAuth:!0}})}};ar.Content=Ro;var Ze=class extends g{constructor(){super(...arguments),this.content=new Oo(this._client),this.versions=new ar(this._client)}create(e={},r){return this._client.post("/skills",pt({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/skills/${e}`,{body:r,...o,__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(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Ze.Content=Oo;Ze.Versions=ar;var No=class extends g{create(e,r,o){return this._client.post(m`/uploads/${e}/parts`,me({body:r,...o,__security:{bearerAuth:!0}},this._client))}};var Tt=class extends g{constructor(){super(...arguments),this.parts=new No(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,o){return this._client.post(m`/uploads/${e}/complete`,{body:r,...o,__security:{bearerAuth:!0}})}};Tt.Parts=No;var _c=async t=>{let e=await Promise.allSettled(t),r=e.filter(n=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let o=[];for(let n of e)n.status==="fulfilled"&&o.push(n.value);return o};var $o=class extends g{create(e,r,o){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{vector_store_id:n}=r;return this._client.get(m`/vector_stores/${n}/file_batches/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,o){let{vector_store_id:n}=r;return this._client.post(m`/vector_stores/${n}/file_batches/${e}/cancel`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r);return await this.poll(e,n.id,o)}listFiles(e,r,o){let{vector_store_id:n,...s}=r;return this._client.getAPIList(m`/vector_stores/${n}/file_batches/${e}/files`,N,{query:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...o,headers:n}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:o=[]},n){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=n?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...o];async function d(f){for(let x of f){let w=await i.files.create({file:x,purpose:"assistants"},n);l.push(w.id)}}let p=Array(a).fill(u).map(d);return await _c(p),await this.createAndPoll(e,{file_ids:l})}};var zo=class extends g{create(e,r,o){return this._client.post(m`/vector_stores/${e}/files`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{vector_store_id:n}=r;return this._client.get(m`/vector_stores/${n}/files/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{vector_store_id:n,...s}=r;return this._client.post(m`/vector_stores/${n}/files/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/vector_stores/${e}/files`,N,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r,o){let{vector_store_id:n}=r;return this._client.delete(m`/vector_stores/${n}/files/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r,o);return await this.poll(e,n.id,o)}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...o,headers:n}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"failed":case"completed":return a}}}async upload(e,r,o){let n=await this._client.files.create({file:r,purpose:"assistants"},o);return this.create(e,{file_id:n.id},o)}async uploadAndPoll(e,r,o){let n=await this.upload(e,r,o);return await this.poll(e,n.id,o)}content(e,r,o){let{vector_store_id:n}=r;return this._client.getAPIList(m`/vector_stores/${n}/files/${e}/content`,pe,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var Qe=class extends g{constructor(){super(...arguments),this.files=new zo(this._client),this.fileBatches=new $o(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/vector_stores/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",N,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,o){return this._client.getAPIList(m`/vector_stores/${e}/search`,pe,{body:r,method:"post",...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};Qe.Files=zo;Qe.FileBatches=$o;var ir=class extends g{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",L,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},o){return this._client.get(m`/videos/${e}/content`,{query:r,...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(m`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,o){return this._client.post(m`/videos/${e}/remix`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}};var Lo,wc,$s,lr=class extends g{constructor(){super(...arguments),Lo.add(this)}async unwrap(e,r,o=this._client.webhookSecret,n=300){return await this.verifySignature(e,r,o,n),JSON.parse(e)}async verifySignature(e,r,o=this._client.webhookSecret,n=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");_(this,Lo,"m",wc).call(this,o);let s=T([r]).values,a=_(this,Lo,"m",$s).call(this,s,"webhook-signature"),i=_(this,Lo,"m",$s).call(this,s,"webhook-timestamp"),u=_(this,Lo,"m",$s).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new $e("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>n)throw new $e("Webhook timestamp is too old");if(l>d+n)throw new $e("Webhook timestamp is too new");let p=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=o.startsWith("whsec_")?Buffer.from(o.replace("whsec_",""),"base64"):Buffer.from(o,"utf-8"),x=u?`${u}.${i}.${e}`:`${i}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of p)try{let y=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,y,new TextEncoder().encode(x)))return}catch{continue}throw new $e("The given webhook signature does not match the expected signature")}};Lo=new WeakSet,wc=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")},$s=function(e,r){if(!e)throw new Error("Headers are required");let o=e.get(r);if(o==null)throw new Error(`Missing required header: ${r}`);return o};var Ac=Symbol.for("openai.node.providerDefinitions.v1"),xc=globalThis,Ic=xc[Ac],vc=Ic??new WeakMap;Ic||Object.defineProperty(xc,Ac,{value:vc});function Tc(t){let e=vc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var vi,Ti,En,Sc,xg="workload-identity-auth",O=class{constructor(e={}){vi.add(this),En.set(this,void 0),this.completions=new Ht(this),this.chat=new ht(this),this.embeddings=new Zt(this),this.files=new Yt(this),this.images=new rr(this),this.audio=new De(this),this.moderations=new nr(this),this.models=new or(this),this.fineTuning=new ke(this),this.graders=new vt(this),this.vectorStores=new Qe(this),this.webhooks=new lr(this),this.beta=new Ce(this),this.batches=new Bt(this),this.uploads=new Tt(this),this.admin=new yt(this),this.responses=new Ue(this),this.realtime=new Je(this),this.conversations=new xt(this),this.evals=new It(this),this.containers=new At(this),this.skills=new Ze(this),this.videos=new ir(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(b.length)throw new C(`The \`provider\` option cannot be used with ${b.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:o=r?null:Te("OPENAI_BASE_URL"),apiKey:n=r?null:Te("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Te("OPENAI_ADMIN_KEY")??null,organization:a=r?null:Te("OPENAI_ORG_ID")??null,project:i=r?null:Te("OPENAI_PROJECT_ID")??null,webhookSecret:u=Te("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,p=r?Tc(r):void 0,f={apiKey:n,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...d,baseURL:p?.baseURL??(o||"https://api.openai.com/v1")};if(n&&l)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!n&&!s&&!l)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&bu())throw new C(`It looks like you're running in a browser-like environment.
|
|
55
|
+
${Cs(t)}`);return{...H,id:G,type:q,function:{...ee,name:Q,arguments:le}}})}}:{...x,message:{...S,content:w,role:h,refusal:l.refusal??null},finish_reason:d,index:p,logprobs:f}}),created:n,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Vu(u,e)}function Cs(t){return JSON.stringify(t)}var vn=class t extends Dt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,o){let n=new t(r),s={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,s)),n}};var We=class extends g{constructor(){super(...arguments),this.messages=new Lt(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(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/chat/completions/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Ju(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(o=>_n(o,e))}runTools(e,r){return e.stream?vn.runTools(this._client,e,r):In.runTools(this._client,e,r)}stream(e,r){return Dt.createChatCompletion(this._client,e,r)}};We.Messages=Lt;var ht=class extends g{constructor(){super(...arguments),this.completions=new We(this._client)}};ht.Completions=We;var Fr=class extends g{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},o){return this._client.get(m`/organization/certificates/${e}`,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/certificates/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends g{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends g{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends g{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/roles/${e}`,{body:r,...o,__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(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends g{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/spend_alerts/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends g{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}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{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}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends g{create(e,r,o){return this._client.post(m`/organization/groups/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{group_id:n}=r;return this._client.get(m`/organization/groups/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/groups/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{group_id:n}=r;return this._client.delete(m`/organization/groups/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{create(e,r,o){return this._client.post(m`/organization/groups/${e}/users`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{group_id:n}=r;return this._client.get(m`/organization/groups/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/groups/${e}/users`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{group_id:n}=r;return this._client.delete(m`/organization/groups/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var gt=class extends g{constructor(){super(...arguments),this.users=new Jr(this._client),this.roles=new Hr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/groups/${e}`,{body:r,...o,__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(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};gt.Users=Jr;gt.Roles=Hr;var Zr=class extends g{retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/api_keys/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/api_keys`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/api_keys/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends g{list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/certificates`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}activate(e,r,o){return this._client.getAPIList(m`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,o){return this._client.getAPIList(m`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/data_retention`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}};var eo=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}/model_permissions`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var to=class extends g{listRateLimits(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/rate_limits`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/rate_limits/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}};var ro=class extends g{create(e,r,o){return this._client.post(m`/projects/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/projects/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/roles/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/projects/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/projects/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var oo=class extends g{create(e,r,o){return this._client.post(m`/organization/projects/${e}/service_accounts`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/service_accounts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/service_accounts/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/service_accounts`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/service_accounts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var no=class extends g{create(e,r,o){return this._client.post(m`/organization/projects/${e}/spend_alerts`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/spend_alerts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/spend_alerts/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/spend_alerts`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/spend_alerts/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var so=class extends g{create(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/groups/${e}/roles`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,group_id:s}=r;return this._client.get(m`/projects/${n}/groups/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r,o){let{project_id:n,...s}=r;return this._client.getAPIList(m`/projects/${n}/groups/${e}/roles`,X,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n,group_id:s}=r;return this._client.delete(m`/projects/${n}/groups/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends g{constructor(){super(...arguments),this.roles=new so(this._client)}create(e,r,o){return this._client.post(m`/organization/projects/${e}/groups`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,...s}=r;return this._client.get(m`/organization/projects/${n}/groups/${e}`,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/groups`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/groups/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};Ft.Roles=so;var ao=class extends g{create(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/projects/${n}/users/${e}/roles`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n,user_id:s}=r;return this._client.get(m`/projects/${n}/users/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r,o){let{project_id:n,...s}=r;return this._client.getAPIList(m`/projects/${n}/users/${e}/roles`,X,{query:s,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n,user_id:s}=r;return this._client.delete(m`/projects/${n}/users/${s}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends g{constructor(){super(...arguments),this.roles=new ao(this._client)}create(e,r,o){return this._client.post(m`/organization/projects/${e}/users`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{project_id:n}=r;return this._client.get(m`/organization/projects/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){let{project_id:n,...s}=r;return this._client.post(m`/organization/projects/${n}/users/${e}`,{body:s,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/projects/${e}/users`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{project_id:n}=r;return this._client.delete(m`/organization/projects/${n}/users/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};Ut.Roles=ao;var se=class extends g{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new oo(this._client),this.apiKeys=new Zr(this._client),this.rateLimits=new to(this._client),this.modelPermissions=new eo(this._client),this.hostedToolPermissions=new Xr(this._client),this.groups=new Ft(this._client),this.roles=new ro(this._client),this.dataRetention=new Yr(this._client),this.spendAlerts=new no(this._client),this.certificates=new Qr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/projects/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(m`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};se.Users=Ut;se.ServiceAccounts=oo;se.APIKeys=Zr;se.RateLimits=to;se.ModelPermissions=eo;se.HostedToolPermissions=Xr;se.Groups=Ft;se.Roles=ro;se.DataRetention=Yr;se.SpendAlerts=no;se.Certificates=Qr;var io=class extends g{create(e,r,o){return this._client.post(m`/organization/users/${e}/roles`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,o){let{user_id:n}=r;return this._client.get(m`/organization/users/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/organization/users/${e}/roles`,X,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{user_id:n}=r;return this._client.delete(m`/organization/users/${n}/roles/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends g{constructor(){super(...arguments),this.roles=new io(this._client)}retrieve(e,r){return this._client.get(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,o){return this._client.post(m`/organization/users/${e}`,{body:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=io;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new Ur(this._client),this.adminAPIKeys=new Fr(this._client),this.usage=new Wr(this._client),this.invites=new Kr(this._client),this.users=new qt(this._client),this.groups=new gt(this._client),this.roles=new Gr(this._client),this.dataRetention=new Br(this._client),this.spendAlerts=new Vr(this._client),this.certificates=new qr(this._client),this.projects=new se(this._client)}};ae.AuditLogs=Ur;ae.AdminAPIKeys=Fr;ae.Usage=Wr;ae.Invites=Kr;ae.Users=qt;ae.Groups=gt;ae.Roles=Gr;ae.DataRetention=Br;ae.SpendAlerts=Vr;ae.Certificates=qr;ae.Projects=se;var yt=class extends g{constructor(){super(...arguments),this.organization=new ae(this._client)}};yt.Organization=ae;var rc=Symbol("brand.privateNullableHeaders");function*Ph(t){if(!t)return;if(rc in t){let{values:o,nulls:n}=t;yield*o.entries();for(let s of n)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Ba(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let o of r){let n=o[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let s=Ba(o[1])?o[1]:[o[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,i])}}var T=t=>{let e=new Headers,r=new Set;for(let o of t){let n=new Set;for(let[s,a]of Ph(o)){let i=s.toLowerCase();n.has(i)||(e.delete(s),n.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[rc]:!0,values:e,nulls:r}};var lo=class extends g{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:T([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var uo=class extends g{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var co=class extends g{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var De=class extends g{constructor(){super(...arguments),this.transcriptions=new uo(this._client),this.translations=new co(this._client),this.speech=new lo(this._client)}};De.Transcriptions=uo;De.Translations=co;De.Speech=lo;var Bt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",$,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var po=class extends g{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/assistants/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",$,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var mo=class extends g{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var fo=class extends g{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var _t=class extends g{constructor(){super(...arguments),this.sessions=new mo(this._client),this.transcriptionSessions=new fo(this._client)}};_t.Sessions=mo;_t.TranscriptionSessions=fo;var ho=class extends g{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var go=class extends g{retrieve(e,r){return this._client.get(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",L,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},o){return this._client.getAPIList(m`/chatkit/threads/${e}/items`,L,{query:r,...o,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},o?.headers]),__security:{bearerAuth:!0}})}};var wt=class extends g{constructor(){super(...arguments),this.sessions=new ho(this._client),this.threads=new go(this._client)}};wt.Sessions=ho;wt.Threads=go;var yo=class extends g{create(e,r,o){return this._client.post(m`/threads/${e}/messages`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{thread_id:n}=r;return this._client.get(m`/threads/${n}/messages/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/messages/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/threads/${e}/messages`,$,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r,o){let{thread_id:n}=r;return this._client.delete(m`/threads/${n}/messages/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var _o=class extends g{retrieve(e,r,o){let{thread_id:n,run_id:s,...a}=r;return this._client.get(m`/threads/${n}/runs/${s}/steps/${e}`,{query:a,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r,o){let{thread_id:n,...s}=r;return this._client.getAPIList(m`/threads/${n}/runs/${e}/steps`,$,{query:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var oc=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,o=new Uint8Array(r);for(let n=0;n<r;n++)o[n]=e.charCodeAt(n);return Array.from(new Float32Array(o.buffer))}};var Te=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 ie,Gt,xi,Fe,ks,Se,Vt,wo,Kt,Ps,we,Es,Ms,Cn,Tn,Sn,nc,sc,ac,ic,lc,uc,cc,He=class extends mt{constructor(){super(...arguments),ie.add(this),xi.set(this,[]),Fe.set(this,{}),ks.set(this,{}),Se.set(this,void 0),Vt.set(this,void 0),wo.set(this,void 0),Kt.set(this,void 0),Ps.set(this,void 0),we.set(this,void 0),Es.set(this,void 0),Ms.set(this,void 0),Cn.set(this,void 0)}[(xi=new WeakMap,Fe=new WeakMap,ks=new WeakMap,Se=new WeakMap,Vt=new WeakMap,wo=new WeakMap,Kt=new WeakMap,Ps=new WeakMap,we=new WeakMap,Es=new WeakMap,Ms=new WeakMap,Cn=new WeakMap,ie=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("event",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).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 Gt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let o=je.fromReadableStream(e,this.controller);for await(let n of o)_(this,ie,"m",Tn).call(this,n);if(o.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,o,n){let s=new Gt;return s._run(()=>s._runToolAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,o,n){this._listenForAbort(n?.signal);let s={...o,stream:!0},a=await e.submitToolOutputs(r,s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ie,"m",Tn).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}static createThreadAssistantStream(e,r,o){let n=new Gt;return n._run(()=>n._threadAssistantStream(e,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,r,o,n){let s=new Gt;return s._run(()=>s._runAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Es,"f")}currentRun(){return _(this,Ms,"f")}currentMessageSnapshot(){return _(this,Se,"f")}currentRunStepSnapshot(){return _(this,Cn,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ks,"f"))}async finalRun(){if(await this.done(),!_(this,Vt,"f"))throw Error("Final run was not received.");return _(this,Vt,"f")}async _createThreadAssistantStream(e,r,o){this._listenForAbort(o?.signal);let n={...r,stream:!0},s=await e.createAndRun(n,{...o,signal:this.controller.signal});this._connected();for await(let a of s)_(this,ie,"m",Tn).call(this,a);if(s.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}async _createAssistantStream(e,r,o,n){this._listenForAbort(n?.signal);let s={...o,stream:!0},a=await e.create(r,s,{...n,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ie,"m",Tn).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ie,"m",Sn).call(this))}static accumulateDelta(e,r){for(let[o,n]of Object.entries(r)){if(!e.hasOwnProperty(o)){e[o]=n;continue}let s=e[o];if(s==null){e[o]=n;continue}if(o==="index"||o==="type"){e[o]=n;continue}if(typeof s=="string"&&typeof n=="string")s+=n;else if(typeof s=="number"&&typeof n=="number")s+=n;else if(un(s)&&un(n))s=this.accumulateDelta(s,n);else if(Array.isArray(s)&&Array.isArray(n)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...n);continue}for(let a of n){if(!un(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);let u=s[i];u==null?s.push(a):s[i]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${o}, deltaValue: ${n}, accValue: ${s}`);e[o]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,o){return await this._createThreadAssistantStream(r,e,o)}async _runAssistantStream(e,r,o,n){return await this._createAssistantStream(r,e,o,n)}async _runToolAssistantStream(e,r,o,n){return await this._createToolAssistantStream(r,e,o,n)}};Gt=He,Tn=function(e){if(!this.ended)switch(P(this,Es,e,"f"),_(this,ie,"m",ac).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":_(this,ie,"m",cc).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":_(this,ie,"m",sc).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":_(this,ie,"m",nc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Sn=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Vt,"f"))throw Error("Final run has not been received");return _(this,Vt,"f")},nc=function(e){let[r,o]=_(this,ie,"m",lc).call(this,e,_(this,Se,"f"));P(this,Se,r,"f"),_(this,ks,"f")[r.id]=r;for(let n of o){let s=r.content[n.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 n of e.data.delta.content){if(n.type=="text"&&n.text){let s=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",s,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=_(this,wo,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Se,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Se,"f"));break}P(this,wo,n.index,"f")}P(this,Kt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,wo,"f")!==void 0){let n=e.data.content[_(this,wo,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,_(this,Se,"f"));break;case"text":this._emit("textDone",n.text,_(this,Se,"f"));break}}_(this,Se,"f")&&this._emit("messageDone",e.data),P(this,Se,void 0,"f")}},sc=function(e){let r=_(this,ie,"m",ic).call(this,e);switch(P(this,Cn,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let o=e.data.delta;if(o.step_details&&o.step_details.type=="tool_calls"&&o.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of o.step_details.tool_calls)s.index==_(this,Ps,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),P(this,Ps,s.index,"f"),P(this,we,r.step_details.tool_calls[s.index],"f"),_(this,we,"f")&&this._emit("toolCallCreated",_(this,we,"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":P(this,Cn,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),P(this,we,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},ac=function(e){_(this,xi,"f").push(e),this._emit("event",e)},ic=function(e){switch(e.event){case"thread.run.step.created":return _(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Fe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let o=e.data;if(o.delta){let n=Gt.accumulateDelta(r,o.delta);_(this,Fe,"f")[e.data.id]=n}return _(this,Fe,"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":_(this,Fe,"f")[e.data.id]=e.data;break}if(_(this,Fe,"f")[e.data.id])return _(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},lc=function(e,r){let o=[];switch(e.event){case"thread.message.created":return[e.data,o];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let s of n.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=_(this,ie,"m",uc).call(this,s,a)}else r.content[s.index]=s,o.push(s);return[r,o];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,o];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},uc=function(e,r){return Gt.accumulateDelta(r,e)},cc=function(e){switch(P(this,Ms,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":P(this,Vt,e.data,"f"),_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),P(this,we,void 0,"f"));break;case"thread.run.cancelling":break}};var Wt=class extends g{constructor(){super(...arguments),this.steps=new _o(this._client)}create(e,r,o){let{include:n,...s}=r;return this._client.post(m`/threads/${e}/runs`,{query:{include:n},body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{thread_id:n}=r;return this._client.get(m`/threads/${n}/runs/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/runs/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/threads/${e}/runs`,$,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,o){let{thread_id:n}=r;return this._client.post(m`/threads/${n}/runs/${e}/cancel`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r,o);return await this.poll(n.id,{thread_id:e},o)}createAndStream(e,r,o){return He.createAssistantStream(e,this._client.beta.threads.runs,r,o)}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...o,headers:{...o?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,o){return He.createAssistantStream(e,this._client.beta.threads.runs,r,o)}submitToolOutputs(e,r,o){let{thread_id:n,...s}=r;return this._client.post(m`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,o){let n=await this.submitToolOutputs(e,r,o);return await this.poll(n.id,r,o)}submitToolOutputsStream(e,r,o){return He.createToolAssistantStream(e,this._client.beta.threads.runs,r,o)}};Wt.Steps=_o;var bt=class extends g{constructor(){super(...arguments),this.runs=new Wt(this._client),this.messages=new yo(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/threads/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let o=await this.createAndRun(e,r);return await this.runs.poll(o.id,{thread_id:o.thread_id},r)}createAndRunStream(e,r){return He.createThreadAssistantStream(e,this._client.beta.threads,r)}};bt.Runs=Wt;bt.Messages=yo;var Ce=class extends g{constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new wt(this._client),this.assistants=new po(this._client),this.threads=new bt(this._client)}};Ce.Realtime=_t;Ce.ChatKit=wt;Ce.Assistants=po;Ce.Threads=bt;var Ht=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var bo=class extends g{retrieve(e,r,o){let{container_id:n}=r;return this._client.get(m`/containers/${n}/files/${e}/content`,{...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Jt=class extends g{constructor(){super(...arguments),this.content=new bo(this._client)}create(e,r,o){return this._client.post(m`/containers/${e}/files`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,o){let{container_id:n}=r;return this._client.get(m`/containers/${n}/files/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/containers/${e}/files`,$,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{container_id:n}=r;return this._client.delete(m`/containers/${n}/files/${e}`,{...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}};Jt.Content=bo;var At=class extends g{constructor(){super(...arguments),this.files=new Jt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};At.Files=Jt;var Ao=class extends g{create(e,r,o){let{include:n,...s}=r;return this._client.post(m`/conversations/${e}/items`,{query:{include:n},body:s,...o,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{conversation_id:n,...s}=r;return this._client.get(m`/conversations/${n}/items/${e}`,{query:s,...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/conversations/${e}/items`,L,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{conversation_id:n}=r;return this._client.delete(m`/conversations/${n}/items/${e}`,{...o,__security:{bearerAuth:!0}})}};var xt=class extends g{constructor(){super(...arguments),this.items=new Ao(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/conversations/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};xt.Items=Ao;var Zt=class extends g{create(e,r){let o=!!e.encoding_format,n=o?e.encoding_format:"base64";o&&Z(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:n},...r,__security:{bearerAuth:!0}});return o?s:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let u=i.embedding;i.embedding=oc(u)}),a)))}};var xo=class extends g{retrieve(e,r,o){let{eval_id:n,run_id:s}=r;return this._client.get(m`/evals/${n}/runs/${s}/output_items/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r,o){let{eval_id:n,...s}=r;return this._client.getAPIList(m`/evals/${n}/runs/${e}/output_items`,$,{query:s,...o,__security:{bearerAuth:!0}})}};var Qt=class extends g{constructor(){super(...arguments),this.outputItems=new xo(this._client)}create(e,r,o){return this._client.post(m`/evals/${e}/runs`,{body:r,...o,__security:{bearerAuth:!0}})}retrieve(e,r,o){let{eval_id:n}=r;return this._client.get(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/evals/${e}/runs`,$,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{eval_id:n}=r;return this._client.delete(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}cancel(e,r,o){let{eval_id:n}=r;return this._client.post(m`/evals/${n}/runs/${e}`,{...o,__security:{bearerAuth:!0}})}};Qt.OutputItems=xo;var It=class extends g{constructor(){super(...arguments),this.runs=new Qt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/evals/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};It.Runs=Qt;var Yt=class extends g{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(m`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:o=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await ze(r),a=await this.retrieve(e),Date.now()-s>o)throw new $e({message:`Giving up on waiting for file ${e} to finish processing after ${o} milliseconds.`});return a}};var Io=class extends g{};var vo=class extends g{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 Xt=class extends g{constructor(){super(...arguments),this.graders=new vo(this._client)}};Xt.Graders=vo;var To=class extends g{create(e,r,o){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,pe,{body:r,method:"post",...o,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},o){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,L,{query:r,...o,__security:{adminAPIKeyAuth:!0}})}delete(e,r,o){let{fine_tuned_model_checkpoint:n}=r;return this._client.delete(m`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...o,__security:{adminAPIKeyAuth:!0}})}};var er=class extends g{constructor(){super(...arguments),this.permissions=new To(this._client)}};er.Permissions=To;var So=class extends g{list(e,r={},o){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,$,{query:r,...o,__security:{bearerAuth:!0}})}};var tr=class extends g{constructor(){super(...arguments),this.checkpoints=new So(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(m`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",$,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},o){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,$,{query:r,...o,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};tr.Checkpoints=So;var ke=class extends g{constructor(){super(...arguments),this.methods=new Io(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};ke.Methods=Io;ke.Jobs=tr;ke.Checkpoints=er;ke.Alpha=Xt;var Co=class extends g{};var vt=class extends g{constructor(){super(...arguments),this.graderModels=new Co(this._client)}};vt.GraderModels=Co;var rr=class extends g{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({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 g{retrieve(e,r){return this._client.get(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var nr=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var ko=class extends g{accept(e,r,o){return this._client.post(m`/realtime/calls/${e}/accept`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(m`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,o){return this._client.post(m`/realtime/calls/${e}/refer`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},o){return this._client.post(m`/realtime/calls/${e}/reject`,{body:r,...o,headers:T([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})}};var Eo=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Je=class extends g{constructor(){super(...arguments),this.clientSecrets=new Eo(this._client),this.calls=new ko(this._client)}};Je.ClientSecrets=Eo;Je.Calls=ko;function dc(t,e){if(!e||!lg(e)){let r={...t,output_parsed:null,output:t.output.map(o=>o.type==="function_call"?{...o,parsed_arguments:null}:o.type==="message"?{...o,content:o.content.map(n=>({...n,parsed:null}))}:o)};return pc(t,r)&&be(r),r}return Ii(t,e)}function Ii(t,e){let r=!t.status||t.status==="completed",o=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?dg(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?ig(e,i.text):null}:i);return{...s,content:a}}return s}),n=Object.assign({},t,{output:o});return pc(t,n)&&be(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function ig(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function lg(t){return!!yn(t.text?.format)}function ug(t){return t?.$brand==="auto-parseable-tool"}function cg(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function dg(t,e){let r=cg(t.tools??[],e.name);return{...e,...e,parsed_arguments:ug(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function pc(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function be(t){let e=[];for(let r of t.output)if(r.type==="message")for(let o of r.content)o.type==="output_text"&&e.push(o.text);t.output_text=e.join("")}function fc(t,e){if(!e){if(t.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return mc(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&be(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&be(e);break}case"response.content_part.added":{let r=z(e,t.output_index),o=r.type,n=t.part;o==="message"&&n.type!=="reasoning_text"?(r.content.push(structuredClone(n)),n.type==="output_text"&&be(e)):o==="reasoning"&&n.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(n)));break}case"response.content_part.done":{let r=z(e,t.output_index),o=t.part;if(r.type==="message"&&o.type!=="reasoning_text")Ae(r.content,t.content_index),r.content[t.content_index]=structuredClone(o),o.type==="output_text"&&be(e);else if(r.type==="reasoning"&&o.type==="reasoning_text"){let n=r.content;if(!n)throw new C(`missing content at index ${t.content_index}`);Ae(n,t.content_index),n[t.content_index]=structuredClone(o)}break}case"response.output_text.delta":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.text=t.text,be(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="output_text")throw new C(`expected content to be 'output_text', got ${o.type}`);o.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="refusal")throw new C(`expected content to be 'refusal', got ${o.type}`);o.refusal+=t.delta}break}case"response.refusal.done":{let r=z(e,t.output_index);if(r.type==="message"){let o=Ae(r.content,t.content_index);if(o.type!=="refusal")throw new C(`expected content to be 'refusal', got ${o.type}`);o.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=z(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=z(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=z(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let o=Ae(r.content,t.content_index);if(o.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.reasoning_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let o=Ae(r.content,t.content_index);if(o.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${o.type}`);o.text=t.text}break}case"response.reasoning_summary_part.added":{let r=z(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=z(e,t.output_index);r.type==="reasoning"&&(Ae(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=z(e,t.output_index);if(r.type==="reasoning"){let o=Ae(r.summary,t.summary_index);o.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){let o=Ae(r.summary,t.summary_index);o.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=z(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=z(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=z(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=z(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=z(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=z(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=z(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=mc(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:pg(t)}return e}function mc(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&be(e),e}function z(t,e){let r=t.output[e];if(!r)throw new C(`missing output at index ${e}`);return r}function Ae(t,e){let r=t[e];if(!r)throw new C(`missing content at index ${e}`);return r}function pg(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var kn,Os,sr,Rs,hc,gc,yc,$s=class t extends mt{constructor(e){super(),kn.add(this),Os.set(this,void 0),sr.set(this,void 0),Rs.set(this,void 0),P(this,Os,e,"f")}static createResponse(e,r,o){let n=new t(r);return n._run(()=>n._createOrRetrieveResponse(e,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,r,o){this._listenForAbort(o?.signal),_(this,kn,"m",hc).call(this);let n,s=null;"response_id"in r?(n=await e.responses.retrieve(r.response_id,{stream:!0},{...o,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):n=await e.responses.create({...r,stream:!0},{...o,signal:this.controller.signal}),this._connected();for await(let a of n)_(this,kn,"m",gc).call(this,a,s);if(n.controller.signal?.aborted)throw new W;return _(this,kn,"m",yc).call(this)}[(Os=new WeakMap,sr=new WeakMap,Rs=new WeakMap,kn=new WeakSet,hc=function(){this.ended||P(this,sr,void 0,"f")},gc=function(r,o){if(this.ended)return;let n=(a,i)=>{(o==null||i.sequence_number>o)&&this._emit(a,i)},s=fc(r,_(this,sr,"f"));switch(P(this,sr,s,"f"),n("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new C(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new C(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new C(`expected content to be 'output_text', got ${i.type}`);n("response.output_text.delta",{...r,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=s.output[r.output_index];if(!a)throw new C(`missing output at index ${r.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:n(r.type,r);break}},yc=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,sr,"f");if(!r)throw new C("request ended without sending any events");P(this,sr,void 0,"f");let o=mg(r,_(this,Os,"f"));return P(this,Rs,o,"f"),o},Symbol.asyncIterator)](){let e=[],r=[],o=!1;return this.on("event",n=>{let s=r.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{o=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),this.on("error",n=>{o=!0;for(let s of r)s.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:o?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).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=_(this,Rs,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function mg(t,e){return dc(t,e)}var Mo=class extends g{list(e,r={},o){return this._client.getAPIList(m`/responses/${e}/input_items`,$,{query:r,...o,__security:{bearerAuth:!0}})}};var Po=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Ue=class extends g{constructor(){super(...arguments),this.inputItems=new Mo(this._client),this.inputTokens=new Po(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&be(o),o))}retrieve(e,r={},o){return this._client.get(m`/responses/${e}`,{query:r,...o,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&be(n),n))}delete(e,r){return this._client.delete(m`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(o=>Ii(o,e))}stream(e,r){return $s.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(m`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};Ue.InputItems=Mo;Ue.InputTokens=Po;var Oo=class extends g{retrieve(e,r){return this._client.get(m`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Ro=class extends g{retrieve(e,r,o){let{skill_id:n}=r;return this._client.get(m`/skills/${n}/versions/${e}/content`,{...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ar=class extends g{constructor(){super(...arguments),this.content=new Ro(this._client)}create(e,r={},o){return this._client.post(m`/skills/${e}/versions`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,o){let{skill_id:n}=r;return this._client.get(m`/skills/${n}/versions/${e}`,{...o,__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/skills/${e}/versions`,$,{query:r,...o,__security:{bearerAuth:!0}})}delete(e,r,o){let{skill_id:n}=r;return this._client.delete(m`/skills/${n}/versions/${e}`,{...o,__security:{bearerAuth:!0}})}};ar.Content=Ro;var Ze=class extends g{constructor(){super(...arguments),this.content=new Oo(this._client),this.versions=new ar(this._client)}create(e={},r){return this._client.post("/skills",pt({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/skills/${e}`,{body:r,...o,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Ze.Content=Oo;Ze.Versions=ar;var $o=class extends g{create(e,r,o){return this._client.post(m`/uploads/${e}/parts`,me({body:r,...o,__security:{bearerAuth:!0}},this._client))}};var Tt=class extends g{constructor(){super(...arguments),this.parts=new $o(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,o){return this._client.post(m`/uploads/${e}/complete`,{body:r,...o,__security:{bearerAuth:!0}})}};Tt.Parts=$o;var _c=async t=>{let e=await Promise.allSettled(t),r=e.filter(n=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let o=[];for(let n of e)n.status==="fulfilled"&&o.push(n.value);return o};var No=class extends g{create(e,r,o){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{vector_store_id:n}=r;return this._client.get(m`/vector_stores/${n}/file_batches/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,o){let{vector_store_id:n}=r;return this._client.post(m`/vector_stores/${n}/file_batches/${e}/cancel`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r);return await this.poll(e,n.id,o)}listFiles(e,r,o){let{vector_store_id:n,...s}=r;return this._client.getAPIList(m`/vector_stores/${n}/file_batches/${e}/files`,$,{query:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...o,headers:n}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:o=[]},n){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=n?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...o];async function d(f){for(let x of f){let w=await i.files.create({file:x,purpose:"assistants"},n);l.push(w.id)}}let p=Array(a).fill(u).map(d);return await _c(p),await this.createAndPoll(e,{file_ids:l})}};var zo=class extends g{create(e,r,o){return this._client.post(m`/vector_stores/${e}/files`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,o){let{vector_store_id:n}=r;return this._client.get(m`/vector_stores/${n}/files/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){let{vector_store_id:n,...s}=r;return this._client.post(m`/vector_stores/${n}/files/${e}`,{body:s,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e,r={},o){return this._client.getAPIList(m`/vector_stores/${e}/files`,$,{query:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}delete(e,r,o){let{vector_store_id:n}=r;return this._client.delete(m`/vector_stores/${n}/files/${e}`,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,o){let n=await this.create(e,r,o);return await this.poll(e,n.id,o)}async poll(e,r,o){let n=T([o?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":o?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...o,headers:n}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(o?.pollIntervalMs)i=o.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await ze(i);break;case"failed":case"completed":return a}}}async upload(e,r,o){let n=await this._client.files.create({file:r,purpose:"assistants"},o);return this.create(e,{file_id:n.id},o)}async uploadAndPoll(e,r,o){let n=await this.upload(e,r,o);return await this.poll(e,n.id,o)}content(e,r,o){let{vector_store_id:n}=r;return this._client.getAPIList(m`/vector_stores/${n}/files/${e}/content`,pe,{...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};var Qe=class extends g{constructor(){super(...arguments),this.files=new zo(this._client),this.fileBatches=new No(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,o){return this._client.post(m`/vector_stores/${e}`,{body:r,...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",$,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,o){return this._client.getAPIList(m`/vector_stores/${e}/search`,pe,{body:r,method:"post",...o,headers:T([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})}};Qe.Files=zo;Qe.FileBatches=No;var ir=class extends g{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",L,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},o){return this._client.get(m`/videos/${e}/content`,{query:r,...o,headers:T([{Accept:"application/binary"},o?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(m`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,o){return this._client.post(m`/videos/${e}/remix`,pt({body:r,...o,__security:{bearerAuth:!0}},this._client))}};var Lo,wc,Ns,lr=class extends g{constructor(){super(...arguments),Lo.add(this)}async unwrap(e,r,o=this._client.webhookSecret,n=300){return await this.verifySignature(e,r,o,n),JSON.parse(e)}async verifySignature(e,r,o=this._client.webhookSecret,n=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");_(this,Lo,"m",wc).call(this,o);let s=T([r]).values,a=_(this,Lo,"m",Ns).call(this,s,"webhook-signature"),i=_(this,Lo,"m",Ns).call(this,s,"webhook-timestamp"),u=_(this,Lo,"m",Ns).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Ne("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>n)throw new Ne("Webhook timestamp is too old");if(l>d+n)throw new Ne("Webhook timestamp is too new");let p=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=o.startsWith("whsec_")?Buffer.from(o.replace("whsec_",""),"base64"):Buffer.from(o,"utf-8"),x=u?`${u}.${i}.${e}`:`${i}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of p)try{let y=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,y,new TextEncoder().encode(x)))return}catch{continue}throw new Ne("The given webhook signature does not match the expected signature")}};Lo=new WeakSet,wc=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")},Ns=function(e,r){if(!e)throw new Error("Headers are required");let o=e.get(r);if(o==null)throw new Error(`Missing required header: ${r}`);return o};var Ac=Symbol.for("openai.node.providerDefinitions.v1"),xc=globalThis,Ic=xc[Ac],vc=Ic??new WeakMap;Ic||Object.defineProperty(xc,Ac,{value:vc});function Tc(t){let e=vc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var vi,Ti,En,Sc,xg="workload-identity-auth",O=class{constructor(e={}){vi.add(this),En.set(this,void 0),this.completions=new Ht(this),this.chat=new ht(this),this.embeddings=new Zt(this),this.files=new Yt(this),this.images=new rr(this),this.audio=new De(this),this.moderations=new nr(this),this.models=new or(this),this.fineTuning=new ke(this),this.graders=new vt(this),this.vectorStores=new Qe(this),this.webhooks=new lr(this),this.beta=new Ce(this),this.batches=new Bt(this),this.uploads=new Tt(this),this.admin=new yt(this),this.responses=new Ue(this),this.realtime=new Je(this),this.conversations=new xt(this),this.evals=new It(this),this.containers=new At(this),this.skills=new Ze(this),this.videos=new ir(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(b.length)throw new C(`The \`provider\` option cannot be used with ${b.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:o=r?null:Te("OPENAI_BASE_URL"),apiKey:n=r?null:Te("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Te("OPENAI_ADMIN_KEY")??null,organization:a=r?null:Te("OPENAI_ORG_ID")??null,project:i=r?null:Te("OPENAI_PROJECT_ID")??null,webhookSecret:u=Te("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,p=r?Tc(r):void 0,f={apiKey:n,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...d,baseURL:p?.baseURL??(o||"https://api.openai.com/v1")};if(n&&l)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!n&&!s&&!l)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&bu())throw new C(`It looks like you're running in a browser-like environment.
|
|
56
56
|
|
|
57
57
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
58
58
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -62,19 +62,19 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
62
62
|
|
|
63
63
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
64
64
|
`);this.baseURL=f.baseURL,this.timeout=f.timeout??Ti.DEFAULT_TIMEOUT,this.logger=f.logger??console;let x="warn";this.logLevel=x,this.logLevel=ti(f.logLevel,"ClientOptions.logLevel",this)??ti(Te("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??x,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??ls(),P(this,En,Iu,"f");let w=r?void 0:Te("OPENAI_CUSTOM_HEADERS");if(w){let b={};for(let y of w.split(`
|
|
65
|
-
`)){let S=y.indexOf(":");S>=0&&(b[y.substring(0,S).trim()]=y.substring(S+1).trim())}f.defaultHeaders=T([b,f.defaultHeaders])}this._options=f,this._provider=p,l&&(this._workloadIdentityAuth=new hs(l,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,o=e.provider??r,n={...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};return o&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,o!==r&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:o})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&o.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 T([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return T([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return T([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return T([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ou(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${qa()}`}makeStatusError(e,r,o,n){return V.generate(e,r,o,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(o){throw o instanceof C?o:new C(`Failed to get token from 'apiKey' function: ${o.message}`,{cause:o})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,o){let n=!_(this,vi,"m",Sc).call(this)&&o||this.baseURL,s=mu(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Ka(a)||!Ka(i))&&(r={...i,...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:o}){}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,o){return this.request(Promise.resolve(o).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new zt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,o){let n=await e,s=n.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(n);let{req:a,url:i,timeout:u}=await this.buildRequest(n,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:n}),await this._provider?.prepareRequest?.(a,{url:i,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=o===void 0?"":`, retryOf: ${o}`,p=Date.now();if(Z(this).debug(`[${l}] sending request`,Ke({retryOfRequestLogID:o,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new W;let f=n.__security??{bearerAuth:!0},x=new AbortController,w=await this.fetchWithAuth(i,a,u,x,f).catch(an),b=Date.now();if(w instanceof globalThis.Error){let h=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new W;let I=sn(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Z(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${h}`),Z(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${h})`,Ke({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),this.retryRequest(n,r,o??l);throw Z(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ke({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),w instanceof Nt||w instanceof ln?w:I?new Ne:new ct({message:Ig(w),cause:w})}let y=[...w.headers.entries()].filter(([h])=>h==="x-request-id").map(([h,I])=>", "+h+": "+JSON.stringify(I)).join(""),S=`[${l}${d}${y}] ${a.method} ${i} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-p}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Wa(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,o??l);let h=await this.shouldRetry(w);if(r&&h){let H=`retrying, ${r} attempts remaining`;return await Wa(w.body),Z(this).info(`${S} - ${H}`),Z(this).debug(`[${l}] response error (${H})`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:b-p})),this.retryRequest(n,r,o??l,w.headers)}let I=h?"error; no more retries left":"error; not retryable";Z(this).info(`${S} - ${I}`);let k=await w.text().catch(H=>an(H).message),U=gu(k),q=U?void 0:k;throw Z(this).debug(`[${l}] response error (${I})`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,message:q,durationMs:Date.now()-p})),this.makeStatusError(w.status,U,q,w.headers)}return Z(this).info(S),Z(this).debug(`[${l}] response start`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:b-p})),{response:w,options:n,controller:x,requestLogID:l,retryOfRequestLogID:o,startTime:p}}getAPIList(e,r,o){return this.requestAPIList(r,o&&"then"in o?o.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...o})}requestAPIList(e,r){let o=this.makeRequest(r,null,void 0);return new mn(this,o,e)}async fetchWithAuth(e,r,o,n,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${xg}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,o,n)}async fetchWithTimeout(e,r,o,n){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(n);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,o),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,p={signal:n.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,p)}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,o,n){let s,a=n?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=n?.get("retry-after");if(i&&!s){let u=parseFloat(i);Number.isNaN(u)?s=Date.parse(i)-Date.now():s=u*1e3}if(s===void 0){let u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,u)}return await ze(s),this.makeRequest(e,r-1,o)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,a=Math.min(.5*Math.pow(2,s),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(e,{retryCount:r=0}={}){let o={...e},{method:n,path:s,query:a,defaultBaseURL:i}=o,u=this.buildURL(s,a,i);"timeout"in o&&hu("timeout",o.timeout),o.timeout=o.timeout??this.timeout;let{bodyHeaders:l,body:d,isStreamingBody:p}=this.buildBody({options:o});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:r});return{req:{method:n,headers:f,...o.signal&&{signal:o.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...o.fetchOptions??{}},url:u,timeout:o.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:o,retryCount:n}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Au(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,o,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:o}=e;if(!r)return r===void 0&&"body"in e?{..._(this,En,"f").call(this,{body:r,headers:T([o])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=T([o]),s=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,a=!s&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&n.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||s?{bodyHeaders:void 0,body:r,isStreamingBody:!a}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:us(r),isStreamingBody:!0}:typeof r=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,En,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ti=O,En=new WeakMap,vi=new WeakSet,Sc=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=Ti;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=C;O.APIError=V;O.APIConnectionError=ct;O.APIConnectionTimeoutError=Ne;O.APIUserAbortError=W;O.NotFoundError=Sr;O.ConflictError=Cr;O.RateLimitError=Er;O.BadRequestError=Ir;O.AuthenticationError=vr;O.InternalServerError=Mr;O.PermissionDeniedError=Tr;O.UnprocessableEntityError=kr;O.InvalidWebhookSignatureError=$e;O.toFile=hn;O.Completions=Ht;O.Chat=ht;O.Embeddings=Zt;O.Files=Yt;O.Images=rr;O.Audio=De;O.Moderations=nr;O.Models=or;O.FineTuning=ke;O.Graders=vt;O.VectorStores=Qe;O.Webhooks=lr;O.Beta=Ce;O.Batches=Bt;O.Uploads=Tt;O.Admin=yt;O.Responses=Ue;O.Realtime=Je;O.Conversations=xt;O.Evals=It;O.Containers=At;O.Skills=Ze;O.Videos=ir;function Ig(t){if(vg(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function vg(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let o=e;if(o.code==="UND_ERR_INVALID_ARG"&&typeof o.message=="string"&&o.message.includes("invalid onRequestStart method"))return!0;e=o.cause}return!1}function Tg(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 xe(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Ne.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError",Et(e,!0)):t.constructor.name===W.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",Et(e,!1)):Tg(t)?e=Il.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Et(nn(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=Et(nn(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=Et(nn(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=Et(nn(t,"MODEL_NOT_FOUND"),!1):e=t,e}var Ee=t=>t();function Ye(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Sg(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 zs(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Cg="LC_AUTOGENERATED";function ur(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'."),Cg)}function Xe(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(!Gn.isInstance(t))throw new Error("Invalid generic chat message");return Sg(t);default:throw new Error(`Unknown message type: ${e}`)}}function Cc(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function et(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:o,azureOpenAIBasePath:n,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((o||a)&&n&&e)return`${n}/${e}`;if((o||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(o||a){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 Ci(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function kc(t){let e=Ee(()=>{if(Ci(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ci(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,o])=>typeof o=="string").map(([o,n])=>[o,n]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function Ec(){let t=Al();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function tt(t,e=!1,r="1.0.0"){let o=kc(t),n=Ec(),s=`langchainjs${e?"-azure":""}-openai`;return{...o,"User-Agent":o["User-Agent"]?`${s}/${r} (${n})${o["User-Agent"]}`:`${s}/${r} (${n})`}}function Mc(t,e){let r;return Ar(t)?r=va(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function kg(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Pc(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(Oc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
65
|
+
`)){let S=y.indexOf(":");S>=0&&(b[y.substring(0,S).trim()]=y.substring(S+1).trim())}f.defaultHeaders=T([b,f.defaultHeaders])}this._options=f,this._provider=p,l&&(this._workloadIdentityAuth=new hs(l,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,o=e.provider??r,n={...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};return o&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,o!==r&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:o})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&o.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 T([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return T([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return T([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return T([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ou(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${qa()}`}makeStatusError(e,r,o,n){return V.generate(e,r,o,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(o){throw o instanceof C?o:new C(`Failed to get token from 'apiKey' function: ${o.message}`,{cause:o})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,o){let n=!_(this,vi,"m",Sc).call(this)&&o||this.baseURL,s=mu(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Ka(a)||!Ka(i))&&(r={...i,...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:o}){}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,o){return this.request(Promise.resolve(o).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new zt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,o){let n=await e,s=n.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(n);let{req:a,url:i,timeout:u}=await this.buildRequest(n,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:n}),await this._provider?.prepareRequest?.(a,{url:i,options:n});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=o===void 0?"":`, retryOf: ${o}`,p=Date.now();if(Z(this).debug(`[${l}] sending request`,Ke({retryOfRequestLogID:o,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new W;let f=n.__security??{bearerAuth:!0},x=new AbortController,w=await this.fetchWithAuth(i,a,u,x,f).catch(an),b=Date.now();if(w instanceof globalThis.Error){let h=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new W;let I=sn(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Z(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${h}`),Z(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${h})`,Ke({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),this.retryRequest(n,r,o??l);throw Z(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ke({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),w instanceof $t||w instanceof ln?w:I?new $e:new ct({message:Ig(w),cause:w})}let y=[...w.headers.entries()].filter(([h])=>h==="x-request-id").map(([h,I])=>", "+h+": "+JSON.stringify(I)).join(""),S=`[${l}${d}${y}] ${a.method} ${i} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-p}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Wa(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,o??l);let h=await this.shouldRetry(w);if(r&&h){let H=`retrying, ${r} attempts remaining`;return await Wa(w.body),Z(this).info(`${S} - ${H}`),Z(this).debug(`[${l}] response error (${H})`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:b-p})),this.retryRequest(n,r,o??l,w.headers)}let I=h?"error; no more retries left":"error; not retryable";Z(this).info(`${S} - ${I}`);let k=await w.text().catch(H=>an(H).message),U=gu(k),q=U?void 0:k;throw Z(this).debug(`[${l}] response error (${I})`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,message:q,durationMs:Date.now()-p})),this.makeStatusError(w.status,U,q,w.headers)}return Z(this).info(S),Z(this).debug(`[${l}] response start`,Ke({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:b-p})),{response:w,options:n,controller:x,requestLogID:l,retryOfRequestLogID:o,startTime:p}}getAPIList(e,r,o){return this.requestAPIList(r,o&&"then"in o?o.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...o})}requestAPIList(e,r){let o=this.makeRequest(r,null,void 0);return new mn(this,o,e)}async fetchWithAuth(e,r,o,n,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${xg}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,o,n)}async fetchWithTimeout(e,r,o,n){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(n);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,o),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,p={signal:n.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,p)}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,o,n){let s,a=n?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=n?.get("retry-after");if(i&&!s){let u=parseFloat(i);Number.isNaN(u)?s=Date.parse(i)-Date.now():s=u*1e3}if(s===void 0){let u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,u)}return await ze(s),this.makeRequest(e,r-1,o)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,a=Math.min(.5*Math.pow(2,s),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(e,{retryCount:r=0}={}){let o={...e},{method:n,path:s,query:a,defaultBaseURL:i}=o,u=this.buildURL(s,a,i);"timeout"in o&&hu("timeout",o.timeout),o.timeout=o.timeout??this.timeout;let{bodyHeaders:l,body:d,isStreamingBody:p}=this.buildBody({options:o});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:r});return{req:{method:n,headers:f,...o.signal&&{signal:o.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...o.fetchOptions??{}},url:u,timeout:o.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:o,retryCount:n}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Au(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,o,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:o}=e;if(!r)return r===void 0&&"body"in e?{..._(this,En,"f").call(this,{body:r,headers:T([o])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=T([o]),s=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,a=!s&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&n.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||s?{bodyHeaders:void 0,body:r,isStreamingBody:!a}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:us(r),isStreamingBody:!0}:typeof r=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,En,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ti=O,En=new WeakMap,vi=new WeakSet,Sc=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=Ti;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=C;O.APIError=V;O.APIConnectionError=ct;O.APIConnectionTimeoutError=$e;O.APIUserAbortError=W;O.NotFoundError=Sr;O.ConflictError=Cr;O.RateLimitError=Er;O.BadRequestError=Ir;O.AuthenticationError=vr;O.InternalServerError=Mr;O.PermissionDeniedError=Tr;O.UnprocessableEntityError=kr;O.InvalidWebhookSignatureError=Ne;O.toFile=hn;O.Completions=Ht;O.Chat=ht;O.Embeddings=Zt;O.Files=Yt;O.Images=rr;O.Audio=De;O.Moderations=nr;O.Models=or;O.FineTuning=ke;O.Graders=vt;O.VectorStores=Qe;O.Webhooks=lr;O.Beta=Ce;O.Batches=Bt;O.Uploads=Tt;O.Admin=yt;O.Responses=Ue;O.Realtime=Je;O.Conversations=xt;O.Evals=It;O.Containers=At;O.Skills=Ze;O.Videos=ir;function Ig(t){if(vg(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function vg(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let o=e;if(o.code==="UND_ERR_INVALID_ARG"&&typeof o.message=="string"&&o.message.includes("invalid onRequestStart method"))return!0;e=o.cause}return!1}function Tg(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 xe(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===$e.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError",Et(e,!0)):t.constructor.name===W.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",Et(e,!1)):Tg(t)?e=Il.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Et(nn(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=Et(nn(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=Et(nn(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=Et(nn(t,"MODEL_NOT_FOUND"),!1):e=t,e}var Ee=t=>t();function Ye(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Sg(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 zs(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Cg="LC_AUTOGENERATED";function ur(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'."),Cg)}function Xe(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(!Gn.isInstance(t))throw new Error("Invalid generic chat message");return Sg(t);default:throw new Error(`Unknown message type: ${e}`)}}function Cc(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function et(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:o,azureOpenAIBasePath:n,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((o||a)&&n&&e)return`${n}/${e}`;if((o||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(o||a){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 Ci(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function kc(t){let e=Ee(()=>{if(Ci(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ci(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,o])=>typeof o=="string").map(([o,n])=>[o,n]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function Ec(){let t=Al();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function tt(t,e=!1,r="1.0.0"){let o=kc(t),n=Ec(),s=`langchainjs${e?"-azure":""}-openai`;return{...o,"User-Agent":o["User-Agent"]?`${s}/${r} (${n})${o["User-Agent"]}`:`${s}/${r} (${n})`}}function Mc(t,e){let r;return Ar(t)?r=va(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function kg(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Pc(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(Oc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
66
66
|
`)}function Oc(t,e){let r=[];for(let[o,n]of Object.entries(t.properties??{}))n.description&&e<2&&r.push(`// ${n.description}`),t.required?.includes(o)?r.push(`${o}: ${Ls(n,e)},`):r.push(`${o}?: ${Ls(n,e)},`);return r.map(o=>" ".repeat(e)+o).join(`
|
|
67
67
|
`)}function Ls(t,e){if(kg(t))return t.anyOf.map(r=>Ls(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["{",Oc(t,e+2),"}"].join(`
|
|
68
|
-
`);case"array":return t.items?`${Ls(t.items,e)}[]`:"any[]";default:return""}}function js(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 jo(t){return"type"in t&&t.type!=="function"}function Rc(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 Nc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function cr(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 Ds(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function $c(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 zc(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 Lc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function jc(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function Dc(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 Fc(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 qc=Symbol("Let zodToJsonSchema decide on which parser to use"),Uc={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"},Bc=t=>typeof t=="string"?{...Uc,basePath:["#"],definitions:{},name:t}:{...Uc,basePath:["#"],definitions:{},...t};var Mn=t=>"_def"in t?t._def:t;function Kc(t){if(!t)return!0;for(let e in t)return!1;return!0}var Gc=t=>{let e=Bc(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(([o,n])=>[Mn(n),{def:Mn(n),path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function ki(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function j(t,e,r,o,n){t[e]=r,ki(t,e,o,n)}function Vc(){return{}}function Wc(t,e){let r={type:"array"};return t.type?._def?.typeName!==$.ZodAny&&(r.items=R(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&j(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&j(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(j(r,"minItems",t.exactLength.value,t.exactLength.message,e),j(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Hc(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":e.target==="jsonSchema7"?o.inclusive?j(r,"minimum",o.value,o.message,e):j(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?j(r,"maximum",o.value,o.message,e):j(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",o.value,o.message,e));break;case"multipleOf":j(r,"multipleOf",o.value,o.message,e);break}return r}function Jc(){return{type:"boolean"}}function Zc(t,e,r){return R(t.type._def,e,r)}var Qc=(t,e,r)=>R(t.innerType._def,e,r);function Ei(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,s)=>Ei(t,e,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Eg(t,e)}}var Eg=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":j(r,"minimum",o.value,o.message,e);break;case"max":j(r,"maximum",o.value,o.message,e);break}return r};function Yc(t,e,r){return{...R(t.innerType._def,e,r),default:t.defaultValue()}}function Xc(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function ed(t){return{type:"string",enum:[...t.values]}}var Mg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function td(t,e){let r=[R(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),R(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),o=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(s=>{if(Mg(s))n.push(...s.allOf),s.unevaluatedProperties===void 0&&(o=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else o=void 0;n.push(a)}}),n.length?{allOf:n,...o}:void 0}function rd(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 Mi,dr={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:()=>(Mi===void 0&&(Mi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mi),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 Fs(t,e){let r={type:"string"};function o(n){return e.patternStrategy==="escape"?Pg(n):n}if(t.checks)for(let n of t.checks)switch(n.kind){case"min":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Me(r,"email",n.message,e);break;case"format:idn-email":Me(r,"idn-email",n.message,e);break;case"pattern:zod":Pe(r,dr.email,n.message,e);break}break;case"url":Me(r,"uri",n.message,e);break;case"uuid":Me(r,"uuid",n.message,e);break;case"regex":Pe(r,n.regex,n.message,e);break;case"cuid":Pe(r,dr.cuid,n.message,e);break;case"cuid2":Pe(r,dr.cuid2,n.message,e);break;case"startsWith":Pe(r,RegExp(`^${o(n.value)}`),n.message,e);break;case"endsWith":Pe(r,RegExp(`${o(n.value)}$`),n.message,e);break;case"datetime":Me(r,"date-time",n.message,e);break;case"date":Me(r,"date",n.message,e);break;case"time":Me(r,"time",n.message,e);break;case"duration":Me(r,"duration",n.message,e);break;case"length":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Pe(r,RegExp(o(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&Me(r,"ipv4",n.message,e),n.version!=="v4"&&Me(r,"ipv6",n.message,e);break}case"emoji":Pe(r,dr.emoji,n.message,e);break;case"ulid":{Pe(r,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Me(r,"binary",n.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Pe(r,dr.base64,n.message,e);break}}break}case"nanoid":Pe(r,dr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Pg=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Me=(t,e,r,o)=>{t.format||t.anyOf?.some(n=>n.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&o.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&&o.errorMessages&&{errorMessage:{format:r}}})):j(t,"format",e,r,o)},Pe=(t,e,r,o)=>{t.pattern||t.allOf?.some(n=>n.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.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:od(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):j(t,"pattern",od(e,o),r,o)},od=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let o={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=o.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<n.length;l++){if(a){s+=n[l],a=!1;continue}if(o.i){if(i){if(n[l].match(/[a-z]/)){u?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),u=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],u=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(o.m){if(n[l]==="^"){s+=`(^|(?<=[\r
|
|
68
|
+
`);case"array":return t.items?`${Ls(t.items,e)}[]`:"any[]";default:return""}}function js(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 jo(t){return"type"in t&&t.type!=="function"}function Rc(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 $c(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function cr(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 Ds(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Nc(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 zc(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 Lc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function jc(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function Dc(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 Fc(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 qc=Symbol("Let zodToJsonSchema decide on which parser to use"),Uc={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"},Bc=t=>typeof t=="string"?{...Uc,basePath:["#"],definitions:{},name:t}:{...Uc,basePath:["#"],definitions:{},...t};var Mn=t=>"_def"in t?t._def:t;function Kc(t){if(!t)return!0;for(let e in t)return!1;return!0}var Gc=t=>{let e=Bc(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(([o,n])=>[Mn(n),{def:Mn(n),path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function ki(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function j(t,e,r,o,n){t[e]=r,ki(t,e,o,n)}function Vc(){return{}}function Wc(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=R(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&j(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&j(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(j(r,"minItems",t.exactLength.value,t.exactLength.message,e),j(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Hc(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":e.target==="jsonSchema7"?o.inclusive?j(r,"minimum",o.value,o.message,e):j(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?j(r,"maximum",o.value,o.message,e):j(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",o.value,o.message,e));break;case"multipleOf":j(r,"multipleOf",o.value,o.message,e);break}return r}function Jc(){return{type:"boolean"}}function Zc(t,e,r){return R(t.type._def,e,r)}var Qc=(t,e,r)=>R(t.innerType._def,e,r);function Ei(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,s)=>Ei(t,e,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Eg(t,e)}}var Eg=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":j(r,"minimum",o.value,o.message,e);break;case"max":j(r,"maximum",o.value,o.message,e);break}return r};function Yc(t,e,r){return{...R(t.innerType._def,e,r),default:t.defaultValue()}}function Xc(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function ed(t){return{type:"string",enum:[...t.values]}}var Mg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function td(t,e){let r=[R(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),R(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),o=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(s=>{if(Mg(s))n.push(...s.allOf),s.unevaluatedProperties===void 0&&(o=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else o=void 0;n.push(a)}}),n.length?{allOf:n,...o}:void 0}function rd(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 Mi,dr={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:()=>(Mi===void 0&&(Mi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mi),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 Fs(t,e){let r={type:"string"};function o(n){return e.patternStrategy==="escape"?Pg(n):n}if(t.checks)for(let n of t.checks)switch(n.kind){case"min":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Me(r,"email",n.message,e);break;case"format:idn-email":Me(r,"idn-email",n.message,e);break;case"pattern:zod":Pe(r,dr.email,n.message,e);break}break;case"url":Me(r,"uri",n.message,e);break;case"uuid":Me(r,"uuid",n.message,e);break;case"regex":Pe(r,n.regex,n.message,e);break;case"cuid":Pe(r,dr.cuid,n.message,e);break;case"cuid2":Pe(r,dr.cuid2,n.message,e);break;case"startsWith":Pe(r,RegExp(`^${o(n.value)}`),n.message,e);break;case"endsWith":Pe(r,RegExp(`${o(n.value)}$`),n.message,e);break;case"datetime":Me(r,"date-time",n.message,e);break;case"date":Me(r,"date",n.message,e);break;case"time":Me(r,"time",n.message,e);break;case"duration":Me(r,"duration",n.message,e);break;case"length":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Pe(r,RegExp(o(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&Me(r,"ipv4",n.message,e),n.version!=="v4"&&Me(r,"ipv6",n.message,e);break}case"emoji":Pe(r,dr.emoji,n.message,e);break;case"ulid":{Pe(r,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Me(r,"binary",n.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Pe(r,dr.base64,n.message,e);break}}break}case"nanoid":Pe(r,dr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Pg=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Me=(t,e,r,o)=>{t.format||t.anyOf?.some(n=>n.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&o.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&&o.errorMessages&&{errorMessage:{format:r}}})):j(t,"format",e,r,o)},Pe=(t,e,r,o)=>{t.pattern||t.allOf?.some(n=>n.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.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:od(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):j(t,"pattern",od(e,o),r,o)},od=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let o={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=o.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<n.length;l++){if(a){s+=n[l],a=!1;continue}if(o.i){if(i){if(n[l].match(/[a-z]/)){u?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),u=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],u=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(o.m){if(n[l]==="^"){s+=`(^|(?<=[\r
|
|
69
69
|
]))`;continue}else if(n[l]==="$"){s+=`($|(?=[\r
|
|
70
70
|
]))`;continue}}if(o.s&&n[l]==="."){s+=i?`${n[l]}\r
|
|
71
71
|
`:`[${n[l]}\r
|
|
72
|
-
]`;continue}s+=n[l],n[l]==="\\"?a=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!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 Us(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,n)=>({...o,[n]:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===$.ZodString&&t.keyType._def.checks?.length){let o=Object.entries(Fs(t.keyType._def,e)).reduce((n,[s,a])=>s==="type"?n:{...n,[s]:a},{});return{...r,propertyNames:o}}else if(t.keyType?._def.typeName===$.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function nd(t,e){if(e.mapStrategy==="record")return Us(t,e);let r=R(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},o=R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function sd(t){let e=t.values,o=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(o.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function ad(){return{not:{}}}function id(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Pn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ud(t,e){if(e.target==="openApi3")return ld(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in Pn&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,s)=>{let a=Pn[s._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){let n=o.filter((s,a,i)=>i.indexOf(s)===a);return{type:n.length>1?n:n[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(s=>!o.includes(s))],[])};return ld(t,e)}var ld=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>R(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function cd(t,e,r){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:Pn[t.innerType._def.typeName],nullable:!0}:{type:[Pn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function dd(t,e){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",ki(r,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?j(r,"minimum",o.value,o.message,e):j(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?j(r,"maximum",o.value,o.message,e):j(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",o.value,o.message,e));break;case"multipleOf":j(r,"multipleOf",o.value,o.message,e);break}return r}function Og(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function pd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((o,[n,s])=>{if(s===void 0||s._def===void 0)return o;let a=[...e.currentPath,"properties",n],i=R(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return o;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.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:{...o.properties,[n]:i},required:s.isOptional()&&!e.openaiStrictMode?o.required:[...o.required,n]}},{properties:{},required:[]}),additionalProperties:Og(t,e)};return r.required.length||delete r.required,r}var md=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return R(t.innerType._def,{...e,currentPath:e.currentPath},r);let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return o?{anyOf:[{not:{}},o]}:{}};var fd=(t,e,r)=>{if(e.pipeStrategy==="input")return R(t.in._def,e,r);if(e.pipeStrategy==="output")return R(t.out._def,e,r);let o=R(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=R(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,n].filter(s=>s!==void 0)}};function hd(t,e,r){return R(t.type._def,e,r)}function gd(t,e){let o={type:"array",uniqueItems:!0,items:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&j(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&j(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function yd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:R(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function _d(){return{not:{}}}function wd(){return{}}var bd=(t,e,r)=>R(t.innerType._def,e,r);function R(t,e,r=!1){let o=e.seen.get(t);if(e.override){let s=e.override?.(t,e,o,r);if(s!==qc)return s}if(o&&!r){let s=Rg(o,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let s=zg(t,t.typeName,e,r);return s&&Lg(t,e,s),n.jsonSchema=s,s}finally{r&&o&&e.seen.set(t,o)}}var Rg=(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).map((o,n)=>n===0?o:Ng(o)).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:$g(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((o,n)=>e.currentPath[n]===o)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ad="_x_",Ng=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Ad))return t;let e=Ad;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},$g=(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("/")},zg=(t,e,r,o)=>{switch(e){case $.ZodString:return Fs(t,r);case $.ZodNumber:return dd(t,r);case $.ZodObject:return pd(t,r);case $.ZodBigInt:return Hc(t,r);case $.ZodBoolean:return Jc();case $.ZodDate:return Ei(t,r);case $.ZodUndefined:return _d();case $.ZodNull:return id(r);case $.ZodArray:return Wc(t,r);case $.ZodUnion:case $.ZodDiscriminatedUnion:return ud(t,r);case $.ZodIntersection:return td(t,r);case $.ZodTuple:return yd(t,r);case $.ZodRecord:return Us(t,r);case $.ZodLiteral:return rd(t,r);case $.ZodEnum:return ed(t);case $.ZodNativeEnum:return sd(t);case $.ZodNullable:return cd(t,r,o);case $.ZodOptional:return md(t,r,o);case $.ZodMap:return nd(t,r);case $.ZodSet:return gd(t,r);case $.ZodLazy:return R(t.getter()._def,r,o);case $.ZodPromise:return hd(t,r,o);case $.ZodNaN:case $.ZodNever:return ad();case $.ZodEffects:return Xc(t,r,o);case $.ZodAny:return Vc();case $.ZodUnknown:return wd();case $.ZodDefault:return Yc(t,r,o);case $.ZodBranded:return Zc(t,r,o);case $.ZodReadonly:return bd(t,r,o);case $.ZodCatch:return Qc(t,r,o);case $.ZodPipeline:return fd(t,r,o);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(n=>{})(e)}},Lg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Pi=(t,e)=>{let r=Gc(e),o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=R(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(n.title=s);let a=(()=>{if(Kc(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let p=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(p.length===0)break;for(let[f,x]of p)u[f]=R(Mn(x),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=o===void 0?a?{...n,[r.definitionPath]:a}:n:r.nameStrategy==="duplicate-ref"?{...n,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[o]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...a,[o]:n}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function xd(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 rt(e,[],e)}function Oi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Oi(e))return!0;for(let e of t.anyOf??[])if(Oi(e))return!0;return!1}function rt(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 o=t.$defs;if(pr(o))for(let[f,x]of Object.entries(o))rt(x,[...e,"$defs",f],r);let n=t.definitions;if(pr(n))for(let[f,x]of Object.entries(n))rt(x,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(pr(i)){for(let[f,x]of Object.entries(i))if(!Oi(x)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].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(i),t.properties=Object.fromEntries(Object.entries(i).map(([f,x])=>[f,rt(x,[...e,"properties",f],r)]))}let u=t.items;pr(u)&&(t.items=rt(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,x)=>rt(f,[...e,"anyOf",String(x)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=rt(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,x)=>rt(f,[...e,"allOf",String(x)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Dg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=jg(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!pr(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,rt(t,e,r)}return t}function jg(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),o=t;for(let n of r){if(!pr(o))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(o)}`);let s=o[n];if(s===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);o=s}return o}function pr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Dg(t,e){let r=0;for(let o in t)if(r++,r>e)return!0;return!1}function Fg(t,e){return Pi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Ug(t){return xd(Ml(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let o=e._zod.def;if(o.type==="union"&&"discriminator"in o&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function qg(t){return"_zod"in t}function Id(t,e,r){return Gu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:qg(t)?Ug(t):Fg(t,{name:e})}},o=>t.parse(JSON.parse(o)))}var vd=["jsonSchema","functionCalling","jsonMode"];function Td(t,e){if(typeof e<"u"&&!vd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${vd.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 Bg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Sd(t,e,r){if(Pl(t))return Id(t,e,r);if(Hn(t))return Bg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Pt(t,{cycles:"ref",reused:"ref",override(o){o.jsonSchema.title=e}})}},o=>kl(t,JSON.parse(o)));throw new Error("Unsupported schema response format")}function Cd(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(o=>typeof o?.image_url?.url=="string").map(o=>({type:"image",url:o.image_url.url}));return[{type:"text",text:t},...r]}return t}var kd={"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},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-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}};var qs="**REDACTED**";function Do(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var mr=class extends Yn{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}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=qs),"authorization"in o&&(o.authorization=qs),o})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=qs),"authorization"in o&&(o.authorization=qs),o})}:t}_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,r=Ta({baseURL:t?.configuration?.baseURL??(ge("OPENAI_API_BASE")||ge("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??r.apiKey??ge("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ge("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,baseURL:r.baseURL},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.5.8")}_getReasoningParams(t){if(!Ye(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&&Mt(t.json_schema.schema)?Sd(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=et({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=tt(r.defaultHeaders),this.client=new O(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return cr(t)?Fc(t.metadata.customTool):Zn(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Mc(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(o=>{if(jo(o)||cr(o))return o;if(Rc(o))return o.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(o,{strict:r});return Ar(o)&&o.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...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,o=0;this.model==="gpt-3.5-turbo-0301"?(r=4,o=-1):(r=3,o=1);let n=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Xe(s))]),u=s.name!==void 0?o+await this.getNumTokens(s.name):0,l=a+r+i+u,d=s;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:n}}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 o=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Pc(e);o+=await this.getNumTokens(n),o+=9}return e&&t.find(n=>n._getType()==="system")&&(o-=4),r==="none"?o+=1:typeof r=="object"&&(o+=await this.getNumTokens(r.name)+4),o}async moderateContent(t,e){let r=this._getClientOptions(e?.options),o={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(o,r)}catch(n){throw xe(n)}})}get profile(){return kd[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,o,{schema:n,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Td(this.model,e?.method);if(i==="jsonMode"){o=xa(n);let u=Pt(n);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(i==="jsonSchema"){let u=Pt(n),l={name:s??"extract",description:ba(u),schema:Mt(n)?n: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}}}),Mt(n)||Wn(n)){let d=xa(n);o=it.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:d.invoke(p.content))}else o=new Nl}else{let u=s??"extract",l=Pt(n),d;Mt(n)||Wn(n)?d={name:u,description:l.description,parameters:l}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,u=n.name):(u=n.title??u,d={name:u,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],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}:{}}),o=$l(n,u)}return zl(r,o,a)}};var On={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=ya({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||"",o;try{o=ga(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(o.type!=="audio"||o.subtype!=="wav"&&o.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:o.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=ga(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=ya({dataUrl:t.url}),r=ur(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=ur(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`)}},Bs=({message:t,rawResponse:e,includeRawResponse:r})=>{let o=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of o??[])try{s.push(Qn(l,{returnId:!0}))}catch(d){a.push(wr(l,d.message))}let i={function_call:t.function_call,tool_calls:o};r!==void 0&&(i.__raw_response=e),n!==void 0&&(i.reasoning_content=n);let u={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new F({content:Cd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new Gn(t.content||"",t.role??"unknown")}},Ks=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:o})=>{let n=t.role??o,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new wa({content:s,response_metadata:i});if(n==="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 at({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return n==="system"?new Vn({content:s,response_metadata:i}):n==="developer"?new Vn({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new Tl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):n==="tool"?new _a({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new vl({content:s,role:n,response_metadata:i})},Ri=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=Sl(()=>{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=ur(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}}}},Ni=({message:t,model:e})=>{let r=Xe(t);if(r==="system"&&Ye(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return F.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Aa):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&B.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*o(n){for(let s of n){s.type==="text"&&(yield{type:"text",text:s.text});let a=Ri(s);a&&(yield a)}}return{role:"user",content:Array.from(o(t.contentBlocks))}},fr=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Ni({message:r});let o=Xe(r);o==="system"&&Ye(e)&&(o="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(a=>Bn(a)?Kn(a,On):typeof a=="object"&&a!==null&&"type"in a&&(a.type==="tool_use"||a.type==="tool_call"||a.type==="reasoning"||a.type==="reasoning_content"||a.type==="thinking")?[]:a),s={role:o,content:n};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),F.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Aa):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),B.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 Gs=class extends mr{constructor(t,e){super(Do(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let o={};t?.stream_options!==void 0?o={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(o={stream_options:{include_usage:!0}});let n={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(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:js(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...o,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&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(n.reasoning_effort=s.effort),Ye(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let o={},n=this.invocationParams(e),s=fr({messages:t,model:this.model});if(n.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let x of a){x.message.response_metadata={...x.generationInfo,...x.message.response_metadata};let w=x.generationInfo?.completion??0;i[w]===void 0?i[w]=x:i[w]=i[w].concat(x)}let u=Object.entries(i).sort(([x],[w])=>parseInt(x,10)-parseInt(w,10)).map(([x,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return o.input_tokens=p,o.output_tokens=f,o.total_tokens=p+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}else{let a=await this.completionWithRetry({...n,stream:!1,messages:s},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:p}=a?.usage??{};i&&(o.output_tokens=(o.output_tokens??0)+i),u&&(o.input_tokens=(o.input_tokens??0)+u),l&&(o.total_tokens=(o.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(o.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(o.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let x of a?.choices??[]){let w={text:x.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(x.message??{role:"assistant"},a)};w.generationInfo={...x.finish_reason?{finish_reason:x.finish_reason}:{},...x.logprobs?{logprobs:x.logprobs}:{}},st(w.message)&&(w.message.usage_metadata=o),w.message=new F(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let o=fr({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:o,stream:!0},s=await this.completionWithRetry(n,e),a=this.streamUsage??e.streamUsage;yield*Xn(async function*(u,l){for await(let d of u){if(l?.aborted)return;yield d}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let o=fr({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:o,stream:!0},s,a=await this.completionWithRetry(n,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:d}=l;if(!d)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let x={...f};l.finish_reason!=null&&(x.finish_reason=l.finish_reason,x.system_fingerprint=u.system_fingerprint,x.model_name=u.model,x.service_tier=u.service_tier),this.logprobs&&(x.logprobs=l.logprobs);let w=new rn({message:p,text:p.content,generationInfo:x});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},d=new rn({message:new at({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield d,await r?.handleLLMNewToken(d.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:d})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:r,...o}=e??{},n=this._getClientOptions(o),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(a){throw xe(a)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Ks({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Bs({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Vs="__openai_function_call_ids__",Ws="__openai_custom_tool_call_ids__";function $d(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 Gg(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 Fo=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}},Rn=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],o=[],n=t.output.map(i=>{if(i.type==="function_call"&&"parsed_arguments"in i){let u={...i};return delete u.parsed_arguments,u}return i}),s={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:n,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let i of t.output)if(i.type==="message")e.push(...i.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map($d),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(Qn(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),o.push(wr(u,d))}a[Vs]??={},i.id&&(a[Vs][i.call_id]=i.id)}else if(i.type==="reasoning"){a.reasoning=i;let u=i.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(i.type==="custom_tool_call"){let u=$c(i);u?(r.push(u),a[Ws]??={},i.id&&i.call_id&&(a[Ws][i.call_id]=i.id)):o.push(wr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=zc(i);u?r.push(u):o.push(wr(i,"Malformed computer call"))}else i.type==="image_generation_call"?(i.result&&e.push({type:"image",mimeType:"image/png",data:i.result,id:i.id,metadata:{status:i.status}}),a.tool_outputs??=[],a.tool_outputs.push(i)):(a.tool_outputs??=[],a.tool_outputs.push(i));return new F({id:t.id,content:e,tool_calls:r,invalid_tool_calls:o,usage_metadata:Fo(t.usage),additional_kwargs:a,response_metadata:s})},$i=t=>{let e=(t.summary.length>1?t.summary.reduce((r,o)=>{let n=r[r.length-1];return n.index===o.index?n.text+=o.text:r.push(o),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([o])=>o!=="index")));return{...t,summary:e}},Hs=t=>{let e=[],r={},o,n=[],s={model_provider:"openai"},a={},i;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:[$d(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){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")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Vs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Ws]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.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}}),a.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))a.tool_outputs=[t.item];else if(t.type==="response.created")i=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){i=t.response.id;let u=Rn(t.response);if(o=Fo(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{a.parsed??=JSON.parse(u.text)}catch{}for(let[l,d]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=d)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,u,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:u,status:l}}}else if(t.type==="response.refusal.done")a.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((d,p)=>({...d,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(d=>d.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new rn({text:e.map(u=>u.text).join(""),message:new at({id:i,content:e,tool_call_chunks:n,usage_metadata:o,additional_kwargs:a,response_metadata:s}),generationInfo:r})},zi=t=>{let e=F.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let o=Ee(()=>{try{let h=Xe(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),n=h=>o==="assistant"?{type:"output_text",text:h,annotations:[]}:{type:"input_text",text:h},s,a=new Set,i=new Set,u=new Map,l=new Map;function*d(){if(!s)return;let h=s.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield s),s=void 0}let p=(h,I)=>{s||(s={type:"message",role:o,content:[],...I?{phase:I}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[n(s.content),...h]:[...h]:s.content.push(...h)},f=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},x=h=>{let I=Ee(()=>{let k=h.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(h.fileId)return{type:"input_image",detail:I,file_id:h.fileId};if(h.url)return{type:"input_image",detail:I,image_url:h.url};if(h.data){let k=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:I,image_url:`data:${h.mimeType??"image/png"};base64,${k}`}}},w=h=>{if(h.fileId){let I=zs(h);return{type:"input_file",file_id:h.fileId,...I?{filename:I}:{}}}if(h.url){let I=zs(h);return{...I?{filename:I}:{},type:"input_file",file_url:h.url}}if(h.data){let I=ur(h),k=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${k}`,filename:I}}},b=h=>{let I=Ee(()=>{if(Array.isArray(h.summary)){let U=h.summary?.map(q=>q?.text).filter(q=>typeof q=="string")??[];if(U.length>0)return U}return h.reasoning?[h.reasoning]:[]}),k=I.length>0?I.map(U=>({type:"summary_text",text:U})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:k}},y=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:f(h.args)}),S=h=>{let I=f(h.output),k=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:I,...k?{status:k}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let I=Ee(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});p([n(h.text)],I)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*d(),yield b(h);else if(h.type==="tool_call"){yield*d();let I=h.id??"";I&&(a.add(I),u.delete(I)),yield y(h)}else if(h.type==="tool_call_chunk"){if(h.id){let I=u.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),u.set(h.id,I)}}else if(h.type==="server_tool_call"){yield*d();let I=h.id??"";I&&(i.add(I),l.delete(I)),yield y(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let I=l.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),l.set(h.id,I)}}else if(h.type==="server_tool_call_result")yield*d(),yield S(h);else if(h.type!=="audio")if(h.type==="file"){let I=w(h);I&&p([I])}else if(h.type==="image"){let I=x(h);I&&p([I])}else if(h.type==="video"){let I=w(h);I&&p([I])}else h.type==="text-plain"?h.text&&p([n(h.text)]):h.type==="non_standard"&&e&&(yield*d(),yield h.value)}yield*d();for(let[h,I]of u){if(!h||a.has(h))continue;let k=I.args.join("");!I.name&&!k||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:k})}for(let[h,I]of l){if(!h||i.has(h))continue;let k=I.args.join("");!I.name&&!k||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:k})}}return Array.from(r())},Uo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(o=>{let n=o.response_metadata;if(n?.output_version==="v1")return zi(o);let s=o.additional_kwargs,a=Xe(o);if(a==="system"&&Ye(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=o;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(f=>f.type==="input_image");if(l)return l;let d=i.content.find(f=>f.type==="computer_screenshot");if(d)return d;let p=i.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.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:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(b=>"type"in b))return n?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=$i(u);i.push(b)}let{content:d}=o;if(s?.refusal&&(typeof d=="string"&&(d=[{type:"output_text",text:d,annotations:[]}]),d=[...d,{type:"refusal",refusal:s.refusal}]),typeof d=="string"||d.length>0){let b={type:"message",role:"assistant",...o.id&&!e&&o.id.startsWith("msg_")?{id:o.id}:{},content:Ee(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let S=y;return{type:"output_text",text:S.text,annotations:(S.annotations??[]).map(Gg)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Ee(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let p=s?.[Vs],f=s?.[Ws];F.isInstance(o)&&o.tool_calls?.length?i.push(...o.tool_calls.map(b=>jc(b,f)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:f?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:Lc(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:p?.[b.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:p?.[b.id]}})));let x=n?.output?.length?n?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(x!=null){let b=x?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof o.content=="string")return{type:"message",role:a,content:o.content};let i=[],u=o.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Bn(l)){if(l.type==="file"){let d=zs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...d?{filename:d}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...d?{filename:d}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:ur(l)}}return Kn(l,On)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ee(()=>{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:Ee(()=>{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&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*Li(t,e={}){let r=e.streamUsage??!0,o=e.provider??"openai",n=new Map,s=new Map,a=0,i=!1,u,l,d,p,f=new Set,x=(y,S)=>{let h=s.get(y);if(h!==void 0)return{index:h,isNew:!1};let I=a++;return s.set(y,I),n.set(I,{...S}),{index:I,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let S=n.get(y);S&&(f.add(y),yield{event:"content-block-finish",index:y,content:Ll(S)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:o,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:S,isNew:h}=x(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});h&&(yield{event:"content-block-start",index:S,content:{type:"text",text:""}});let I=n.get(S);I.text=(I.text??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:S,isNew:h}=x(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});h&&(yield{event:"content-block-start",index:S,content:{type:"reasoning",reasoning:""}});let I=n.get(S);I.reasoning=(I.reasoning??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"reasoning-delta",reasoning:y.delta}};continue}if(y.type==="response.output_item.added"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let S=`tool:${y.output_index}`,h=y.item.type==="custom_tool_call",I=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:k,isNew:U}=x(S,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:I,index:y.output_index,...h?{isCustomTool:!0}:{}});if(U&&(yield{event:"content-block-start",index:k,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:I,index:y.output_index}}),I){let q=n.get(k);yield{event:"content-block-delta",index:k,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...q.id!=null?{id:q.id}:{},...q.name!=null?{name:q.name}:{},args:q.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:S,isNew:h}=x(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});h&&(yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let I=n.get(S);I.args=(I.args??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...I.id!=null?{id:I.id}:{},...I.name!=null?{name:I.name}:{},args:I.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let S=`tool:${y.output_index}`,h=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:I,isNew:k}=x(S,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:h,index:y.output_index});if(k)yield{event:"content-block-start",index:I,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:h,index:y.output_index}};else{let U=n.get(I);U.args=h,U.id=y.item.call_id,U.name=y.item.name}yield*b(I);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=Vg(y.response.status,y.type),p={model_provider:o,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=Fo(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:o,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of n)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function Vg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Js=class extends mr{constructor(t,e){super(Do(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:Nc(t?.tool_choice)?t?.tool_choice:(()=>{let n=js(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,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},o=this._getReasoningParams(t);return o!==void 0&&(r.reasoning=o),r}async _generate(t,e,r){e.signal?.throwIfAborted();let o=this.invocationParams(e);if(o.stream){let n=this._streamResponseChunks(t,e,r),s;for await(let a of n)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...o,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:n.output_text,message:Rn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let o=await this.completionWithRetry({...this.invocationParams(e),input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Li(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(o,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let o=await this.completionWithRetry({...this.invocationParams(e),input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of o){if(e.signal?.aborted)return;let s=Hs(n);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(n){throw xe(n)}}async completionWithRetry(t,e){let{maxRetries:r,...o}=e??{},n=this._getClientOptions(o);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw xe(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let o of t)if(jo(o))o.type==="image_generation"&&e?.stream&&(o.partial_images=1),r.push(o);else if(cr(o)){let n=o.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Zn(o)){let n={};for(let[s,a]of Object.entries(o))s!=="type"&&s!=="function"&&(n[s]=a);r.push({type:"function",name:o.function.name,parameters:o.function.parameters,description:o.function.description,strict:e?.strict??null,...n})}else Ds(o)&&r.push(Dc(o));return r}};var Zs=class zd 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 o=Do(e,r);super(o),this.fields=o,this.useResponsesApi=o?.useResponsesApi??!1,this.responses=o?.responses??new Js(o),this.completions=o?.completions??new Gs(o)}_useResponsesApi(e){let r=e?.tools?.some(jo),o=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(Ds)||e?.tools?.some(cr);return this.useResponsesApi||r||o||n||Cc(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,o){return this._useResponsesApi(r)?this.responses._generate(e,r,o):this.completions._generate(e,r,o)}async*_streamChatModelEvents(e,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),o);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),o)}async*_streamResponseChunks(e,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),o);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),o)}withConfig(e){let r=new zd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Qs=class extends Ol{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??ge("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ge("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=Ia(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let a={model:this.model,input:s};return this.dimensions&&(a.dimensions=this.dimensions),this.encodingFormat&&(a.encoding_format=this.encodingFormat),this.embeddingWithRetry(a)}),o=await Promise.all(r),n=[];for(let s=0;s<o.length;s+=1){let a=e[s],{data:i}=o[s];for(let u=0;u<a.length;u+=1)n.push(i[u].embedding)}return n}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=et({baseURL:this.clientConfig.baseURL}),o={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=tt(o.defaultHeaders),this.client=new O(o)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw xe(r)}})}};var Zg=v.object({type:v.literal("screenshot")}),Qg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Yg=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Xg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),ey=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),ty=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),ry=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),oy=v.object({type:v.literal("type"),text:v.string()}),ny=v.object({type:v.literal("wait"),duration:v.number().optional()}),sy=v.union([Zg,Qg,Yg,Xg,ey,ty,ry,oy,ny]),sG=v.object({action:sy});var ay=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),uG=v.union([ay]);var mG=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var iy=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),ly=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),uy=v.object({type:v.literal("delete_file"),path:v.string()}),yG=v.union([iy,ly,uy]);var Dd={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Di={default:"text-embedding-ada-002"},ji=new Map,Ys=null,fy=()=>{let t=Ld.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},Fd=async t=>{let e=fy();ji.size===0&&(Ys||(Ys=(async()=>{try{(await jd(`${e}/models`)).data.models.forEach(o=>ji.set(o.name,o))}catch(o){throw Ys=null,o}})()),await Ys);let r=ji.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},hy=async(t="default")=>await Fd(Dd[t]),Ud=async(t="default")=>await Fd(Di[t]),gy=M.Root({agentExecutionContext:M({default:ka,reducer:Sa}),currentIntent:M({default:()=>"none",reducer:lt}),routing:M({default:()=>({mode:"auto"}),reducer:lt}),lastExecutedAgent:M({default:()=>"",reducer:lt}),requiresFollowUp:M({default:()=>!0,reducer:lt}),stepCount:M({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:M({default:()=>"",reducer:Ca})});var yy=t=>typeof t=="string"&&t.length>0?t:void 0,_y=()=>hl(),wy=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,by=t=>{let e=t?.configurable;return{conversationId:yy(e?.thread_id),abortSignal:t?.signal,requestId:_y(),requestSource:wy(my.applicationName)}},Ay=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},qd=async({config:t})=>{let e=Ld.getDefault(),r=(await py.getCredential(`${e.url}/sharing`))?.token;return async(o,n)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=by(t),l=new Headers(n?.headers);for(let p of[...l.keys()]){let f=p.toLowerCase();(f==="authorization"||f==="api-key"||f.startsWith("x-stainless-"))&&l.delete(p)}r&&r.length>0&&l.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(u&&u.length>0&&l.set("X-Esri-Request-Source",u),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i));let d=a&&n?.signal?AbortSignal.any([a,n.signal]):n?.signal??a;return(await jd(o instanceof Request?o.url:o.toString(),{body:Ay(n?.body),headers:Object.fromEntries(l),responseType:"native",signal:d})).data}},Fi=async(t={})=>{let{modelTier:e="default",config:r}=t,o=Dd[e],n=await hy(e);return new Zs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await qd({config:r})}})},Bd=async(t={})=>{let{tier:e="default",config:r}=t,o=Di[e],n=await Ud(e);return new Qs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await qd({config:r})},batchSize:2048,maxConcurrency:10})},xy=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(xy);var Kd="0.1",qo=1536,Gd="openai",Vd=Di.default,Wd=`Name: {name}
|
|
72
|
+
]`;continue}s+=n[l],n[l]==="\\"?a=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!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 Us(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,n)=>({...o,[n]:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let o=Object.entries(Fs(t.keyType._def,e)).reduce((n,[s,a])=>s==="type"?n:{...n,[s]:a},{});return{...r,propertyNames:o}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function nd(t,e){if(e.mapStrategy==="record")return Us(t,e);let r=R(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},o=R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function sd(t){let e=t.values,o=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(o.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function ad(){return{not:{}}}function id(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Pn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ud(t,e){if(e.target==="openApi3")return ld(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in Pn&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,s)=>{let a=Pn[s._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){let n=o.filter((s,a,i)=>i.indexOf(s)===a);return{type:n.length>1?n:n[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(s=>!o.includes(s))],[])};return ld(t,e)}var ld=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>R(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function cd(t,e,r){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:Pn[t.innerType._def.typeName],nullable:!0}:{type:[Pn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function dd(t,e){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",ki(r,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?j(r,"minimum",o.value,o.message,e):j(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?j(r,"maximum",o.value,o.message,e):j(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",o.value,o.message,e));break;case"multipleOf":j(r,"multipleOf",o.value,o.message,e);break}return r}function Og(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function pd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((o,[n,s])=>{if(s===void 0||s._def===void 0)return o;let a=[...e.currentPath,"properties",n],i=R(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return o;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.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:{...o.properties,[n]:i},required:s.isOptional()&&!e.openaiStrictMode?o.required:[...o.required,n]}},{properties:{},required:[]}),additionalProperties:Og(t,e)};return r.required.length||delete r.required,r}var md=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return R(t.innerType._def,{...e,currentPath:e.currentPath},r);let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return o?{anyOf:[{not:{}},o]}:{}};var fd=(t,e,r)=>{if(e.pipeStrategy==="input")return R(t.in._def,e,r);if(e.pipeStrategy==="output")return R(t.out._def,e,r);let o=R(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=R(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,n].filter(s=>s!==void 0)}};function hd(t,e,r){return R(t.type._def,e,r)}function gd(t,e){let o={type:"array",uniqueItems:!0,items:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&j(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&j(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function yd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:R(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function _d(){return{not:{}}}function wd(){return{}}var bd=(t,e,r)=>R(t.innerType._def,e,r);function R(t,e,r=!1){let o=e.seen.get(t);if(e.override){let s=e.override?.(t,e,o,r);if(s!==qc)return s}if(o&&!r){let s=Rg(o,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let s=zg(t,t.typeName,e,r);return s&&Lg(t,e,s),n.jsonSchema=s,s}finally{r&&o&&e.seen.set(t,o)}}var Rg=(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).map((o,n)=>n===0?o:$g(o)).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:Ng(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((o,n)=>e.currentPath[n]===o)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ad="_x_",$g=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Ad))return t;let e=Ad;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Ng=(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("/")},zg=(t,e,r,o)=>{switch(e){case N.ZodString:return Fs(t,r);case N.ZodNumber:return dd(t,r);case N.ZodObject:return pd(t,r);case N.ZodBigInt:return Hc(t,r);case N.ZodBoolean:return Jc();case N.ZodDate:return Ei(t,r);case N.ZodUndefined:return _d();case N.ZodNull:return id(r);case N.ZodArray:return Wc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return ud(t,r);case N.ZodIntersection:return td(t,r);case N.ZodTuple:return yd(t,r);case N.ZodRecord:return Us(t,r);case N.ZodLiteral:return rd(t,r);case N.ZodEnum:return ed(t);case N.ZodNativeEnum:return sd(t);case N.ZodNullable:return cd(t,r,o);case N.ZodOptional:return md(t,r,o);case N.ZodMap:return nd(t,r);case N.ZodSet:return gd(t,r);case N.ZodLazy:return R(t.getter()._def,r,o);case N.ZodPromise:return hd(t,r,o);case N.ZodNaN:case N.ZodNever:return ad();case N.ZodEffects:return Xc(t,r,o);case N.ZodAny:return Vc();case N.ZodUnknown:return wd();case N.ZodDefault:return Yc(t,r,o);case N.ZodBranded:return Zc(t,r,o);case N.ZodReadonly:return bd(t,r,o);case N.ZodCatch:return Qc(t,r,o);case N.ZodPipeline:return fd(t,r,o);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(n=>{})(e)}},Lg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Pi=(t,e)=>{let r=Gc(e),o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=R(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(n.title=s);let a=(()=>{if(Kc(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let p=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(p.length===0)break;for(let[f,x]of p)u[f]=R(Mn(x),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=o===void 0?a?{...n,[r.definitionPath]:a}:n:r.nameStrategy==="duplicate-ref"?{...n,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[o]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...a,[o]:n}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function xd(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 rt(e,[],e)}function Oi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Oi(e))return!0;for(let e of t.anyOf??[])if(Oi(e))return!0;return!1}function rt(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 o=t.$defs;if(pr(o))for(let[f,x]of Object.entries(o))rt(x,[...e,"$defs",f],r);let n=t.definitions;if(pr(n))for(let[f,x]of Object.entries(n))rt(x,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(pr(i)){for(let[f,x]of Object.entries(i))if(!Oi(x)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].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(i),t.properties=Object.fromEntries(Object.entries(i).map(([f,x])=>[f,rt(x,[...e,"properties",f],r)]))}let u=t.items;pr(u)&&(t.items=rt(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,x)=>rt(f,[...e,"anyOf",String(x)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=rt(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,x)=>rt(f,[...e,"allOf",String(x)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Dg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=jg(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!pr(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,rt(t,e,r)}return t}function jg(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),o=t;for(let n of r){if(!pr(o))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(o)}`);let s=o[n];if(s===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);o=s}return o}function pr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Dg(t,e){let r=0;for(let o in t)if(r++,r>e)return!0;return!1}function Fg(t,e){return Pi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Ug(t){return xd(Ml(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let o=e._zod.def;if(o.type==="union"&&"discriminator"in o&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function qg(t){return"_zod"in t}function Id(t,e,r){return Gu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:qg(t)?Ug(t):Fg(t,{name:e})}},o=>t.parse(JSON.parse(o)))}var vd=["jsonSchema","functionCalling","jsonMode"];function Td(t,e){if(typeof e<"u"&&!vd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${vd.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 Bg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Sd(t,e,r){if(Pl(t))return Id(t,e,r);if(Hn(t))return Bg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Pt(t,{cycles:"ref",reused:"ref",override(o){o.jsonSchema.title=e}})}},o=>kl(t,JSON.parse(o)));throw new Error("Unsupported schema response format")}function Cd(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(o=>typeof o?.image_url?.url=="string").map(o=>({type:"image",url:o.image_url.url}));return[{type:"text",text:t},...r]}return t}var kd={"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},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-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}};var qs="**REDACTED**";function Do(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var mr=class extends Yn{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}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=qs),"authorization"in o&&(o.authorization=qs),o})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=qs),"authorization"in o&&(o.authorization=qs),o})}:t}_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,r=Ta({baseURL:t?.configuration?.baseURL??(ge("OPENAI_API_BASE")||ge("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??r.apiKey??ge("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ge("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,baseURL:r.baseURL},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.5.8")}_getReasoningParams(t){if(!Ye(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&&Mt(t.json_schema.schema)?Sd(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=et({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=tt(r.defaultHeaders),this.client=new O(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return cr(t)?Fc(t.metadata.customTool):Zn(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Mc(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(o=>{if(jo(o)||cr(o))return o;if(Rc(o))return o.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(o,{strict:r});return Ar(o)&&o.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...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,o=0;this.model==="gpt-3.5-turbo-0301"?(r=4,o=-1):(r=3,o=1);let n=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Xe(s))]),u=s.name!==void 0?o+await this.getNumTokens(s.name):0,l=a+r+i+u,d=s;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:n}}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 o=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Pc(e);o+=await this.getNumTokens(n),o+=9}return e&&t.find(n=>n._getType()==="system")&&(o-=4),r==="none"?o+=1:typeof r=="object"&&(o+=await this.getNumTokens(r.name)+4),o}async moderateContent(t,e){let r=this._getClientOptions(e?.options),o={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(o,r)}catch(n){throw xe(n)}})}get profile(){return kd[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,o,{schema:n,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Td(this.model,e?.method);if(i==="jsonMode"){o=xa(n);let u=Pt(n);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(i==="jsonSchema"){let u=Pt(n),l={name:s??"extract",description:ba(u),schema:Mt(n)?n: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}}}),Mt(n)||Wn(n)){let d=xa(n);o=it.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:d.invoke(p.content))}else o=new $l}else{let u=s??"extract",l=Pt(n),d;Mt(n)||Wn(n)?d={name:u,description:l.description,parameters:l}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,u=n.name):(u=n.title??u,d={name:u,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],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}:{}}),o=Nl(n,u)}return zl(r,o,a)}};var On={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=ya({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||"",o;try{o=ga(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(o.type!=="audio"||o.subtype!=="wav"&&o.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:o.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=ga(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=ya({dataUrl:t.url}),r=ur(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=ur(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`)}},Bs=({message:t,rawResponse:e,includeRawResponse:r})=>{let o=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of o??[])try{s.push(Qn(l,{returnId:!0}))}catch(d){a.push(wr(l,d.message))}let i={function_call:t.function_call,tool_calls:o};r!==void 0&&(i.__raw_response=e),n!==void 0&&(i.reasoning_content=n);let u={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new F({content:Cd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new Gn(t.content||"",t.role??"unknown")}},Ks=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:o})=>{let n=t.role??o,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new wa({content:s,response_metadata:i});if(n==="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 at({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return n==="system"?new Vn({content:s,response_metadata:i}):n==="developer"?new Vn({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new Tl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):n==="tool"?new _a({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new vl({content:s,role:n,response_metadata:i})},Ri=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=Sl(()=>{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=ur(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}}}},$i=({message:t,model:e})=>{let r=Xe(t);if(r==="system"&&Ye(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return F.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Aa):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&B.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*o(n){for(let s of n){s.type==="text"&&(yield{type:"text",text:s.text});let a=Ri(s);a&&(yield a)}}return{role:"user",content:Array.from(o(t.contentBlocks))}},fr=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return $i({message:r});let o=Xe(r);o==="system"&&Ye(e)&&(o="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(a=>Bn(a)?Kn(a,On):typeof a=="object"&&a!==null&&"type"in a&&(a.type==="tool_use"||a.type==="tool_call"||a.type==="reasoning"||a.type==="reasoning_content"||a.type==="thinking")?[]:a),s={role:o,content:n};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),F.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Aa):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),B.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 Gs=class extends mr{constructor(t,e){super(Do(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let o={};t?.stream_options!==void 0?o={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(o={stream_options:{include_usage:!0}});let n={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(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:js(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...o,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&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(n.reasoning_effort=s.effort),Ye(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let o={},n=this.invocationParams(e),s=fr({messages:t,model:this.model});if(n.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let x of a){x.message.response_metadata={...x.generationInfo,...x.message.response_metadata};let w=x.generationInfo?.completion??0;i[w]===void 0?i[w]=x:i[w]=i[w].concat(x)}let u=Object.entries(i).sort(([x],[w])=>parseInt(x,10)-parseInt(w,10)).map(([x,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return o.input_tokens=p,o.output_tokens=f,o.total_tokens=p+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}else{let a=await this.completionWithRetry({...n,stream:!1,messages:s},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:p}=a?.usage??{};i&&(o.output_tokens=(o.output_tokens??0)+i),u&&(o.input_tokens=(o.input_tokens??0)+u),l&&(o.total_tokens=(o.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(o.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(o.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let x of a?.choices??[]){let w={text:x.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(x.message??{role:"assistant"},a)};w.generationInfo={...x.finish_reason?{finish_reason:x.finish_reason}:{},...x.logprobs?{logprobs:x.logprobs}:{}},st(w.message)&&(w.message.usage_metadata=o),w.message=new F(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:o.input_tokens,completionTokens:o.output_tokens,totalTokens:o.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let o=fr({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:o,stream:!0},s=await this.completionWithRetry(n,e),a=this.streamUsage??e.streamUsage;yield*Xn(async function*(u,l){for await(let d of u){if(l?.aborted)return;yield d}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let o=fr({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:o,stream:!0},s,a=await this.completionWithRetry(n,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:d}=l;if(!d)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let x={...f};l.finish_reason!=null&&(x.finish_reason=l.finish_reason,x.system_fingerprint=u.system_fingerprint,x.model_name=u.model,x.service_tier=u.service_tier),this.logprobs&&(x.logprobs=l.logprobs);let w=new rn({message:p,text:p.content,generationInfo:x});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},d=new rn({message:new at({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield d,await r?.handleLLMNewToken(d.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:d})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:r,...o}=e??{},n=this._getClientOptions(o),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(a){throw xe(a)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Ks({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Bs({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Vs="__openai_function_call_ids__",Ws="__openai_custom_tool_call_ids__";function Nd(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 Gg(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 Fo=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}},Rn=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],o=[],n=t.output.map(i=>{if(i.type==="function_call"&&"parsed_arguments"in i){let u={...i};return delete u.parsed_arguments,u}return i}),s={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:n,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let i of t.output)if(i.type==="message")e.push(...i.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(Nd),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(Qn(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),o.push(wr(u,d))}a[Vs]??={},i.id&&(a[Vs][i.call_id]=i.id)}else if(i.type==="reasoning"){a.reasoning=i;let u=i.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(i.type==="custom_tool_call"){let u=Nc(i);u?(r.push(u),a[Ws]??={},i.id&&i.call_id&&(a[Ws][i.call_id]=i.id)):o.push(wr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=zc(i);u?r.push(u):o.push(wr(i,"Malformed computer call"))}else i.type==="image_generation_call"?(i.result&&e.push({type:"image",mimeType:"image/png",data:i.result,id:i.id,metadata:{status:i.status}}),a.tool_outputs??=[],a.tool_outputs.push(i)):(a.tool_outputs??=[],a.tool_outputs.push(i));return new F({id:t.id,content:e,tool_calls:r,invalid_tool_calls:o,usage_metadata:Fo(t.usage),additional_kwargs:a,response_metadata:s})},Ni=t=>{let e=(t.summary.length>1?t.summary.reduce((r,o)=>{let n=r[r.length-1];return n.index===o.index?n.text+=o.text:r.push(o),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([o])=>o!=="index")));return{...t,summary:e}},Hs=t=>{let e=[],r={},o,n=[],s={model_provider:"openai"},a={},i;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:[Nd(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){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")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Vs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Ws]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.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}}),a.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))a.tool_outputs=[t.item];else if(t.type==="response.created")i=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){i=t.response.id;let u=Rn(t.response);if(o=Fo(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{a.parsed??=JSON.parse(u.text)}catch{}for(let[l,d]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=d)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,u,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:u,status:l}}}else if(t.type==="response.refusal.done")a.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((d,p)=>({...d,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(d=>d.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new rn({text:e.map(u=>u.text).join(""),message:new at({id:i,content:e,tool_call_chunks:n,usage_metadata:o,additional_kwargs:a,response_metadata:s}),generationInfo:r})},zi=t=>{let e=F.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let o=Ee(()=>{try{let h=Xe(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),n=h=>o==="assistant"?{type:"output_text",text:h,annotations:[]}:{type:"input_text",text:h},s,a=new Set,i=new Set,u=new Map,l=new Map;function*d(){if(!s)return;let h=s.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield s),s=void 0}let p=(h,I)=>{s||(s={type:"message",role:o,content:[],...I?{phase:I}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[n(s.content),...h]:[...h]:s.content.push(...h)},f=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},x=h=>{let I=Ee(()=>{let k=h.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(h.fileId)return{type:"input_image",detail:I,file_id:h.fileId};if(h.url)return{type:"input_image",detail:I,image_url:h.url};if(h.data){let k=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:I,image_url:`data:${h.mimeType??"image/png"};base64,${k}`}}},w=h=>{if(h.fileId){let I=zs(h);return{type:"input_file",file_id:h.fileId,...I?{filename:I}:{}}}if(h.url){let I=zs(h);return{...I?{filename:I}:{},type:"input_file",file_url:h.url}}if(h.data){let I=ur(h),k=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${k}`,filename:I}}},b=h=>{let I=Ee(()=>{if(Array.isArray(h.summary)){let U=h.summary?.map(q=>q?.text).filter(q=>typeof q=="string")??[];if(U.length>0)return U}return h.reasoning?[h.reasoning]:[]}),k=I.length>0?I.map(U=>({type:"summary_text",text:U})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:k}},y=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:f(h.args)}),S=h=>{let I=f(h.output),k=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:I,...k?{status:k}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let I=Ee(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});p([n(h.text)],I)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*d(),yield b(h);else if(h.type==="tool_call"){yield*d();let I=h.id??"";I&&(a.add(I),u.delete(I)),yield y(h)}else if(h.type==="tool_call_chunk"){if(h.id){let I=u.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),u.set(h.id,I)}}else if(h.type==="server_tool_call"){yield*d();let I=h.id??"";I&&(i.add(I),l.delete(I)),yield y(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let I=l.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),l.set(h.id,I)}}else if(h.type==="server_tool_call_result")yield*d(),yield S(h);else if(h.type!=="audio")if(h.type==="file"){let I=w(h);I&&p([I])}else if(h.type==="image"){let I=x(h);I&&p([I])}else if(h.type==="video"){let I=w(h);I&&p([I])}else h.type==="text-plain"?h.text&&p([n(h.text)]):h.type==="non_standard"&&e&&(yield*d(),yield h.value)}yield*d();for(let[h,I]of u){if(!h||a.has(h))continue;let k=I.args.join("");!I.name&&!k||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:k})}for(let[h,I]of l){if(!h||i.has(h))continue;let k=I.args.join("");!I.name&&!k||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:k})}}return Array.from(r())},Uo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(o=>{let n=o.response_metadata;if(n?.output_version==="v1")return zi(o);let s=o.additional_kwargs,a=Xe(o);if(a==="system"&&Ye(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=o;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(f=>f.type==="input_image");if(l)return l;let d=i.content.find(f=>f.type==="computer_screenshot");if(d)return d;let p=i.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.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:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(b=>"type"in b))return n?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=Ni(u);i.push(b)}let{content:d}=o;if(s?.refusal&&(typeof d=="string"&&(d=[{type:"output_text",text:d,annotations:[]}]),d=[...d,{type:"refusal",refusal:s.refusal}]),typeof d=="string"||d.length>0){let b={type:"message",role:"assistant",...o.id&&!e&&o.id.startsWith("msg_")?{id:o.id}:{},content:Ee(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let S=y;return{type:"output_text",text:S.text,annotations:(S.annotations??[]).map(Gg)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Ee(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let p=s?.[Vs],f=s?.[Ws];F.isInstance(o)&&o.tool_calls?.length?i.push(...o.tool_calls.map(b=>jc(b,f)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:f?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:Lc(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:p?.[b.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:p?.[b.id]}})));let x=n?.output?.length?n?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(x!=null){let b=x?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof o.content=="string")return{type:"message",role:a,content:o.content};let i=[],u=o.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Bn(l)){if(l.type==="file"){let d=zs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...d?{filename:d}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...d?{filename:d}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:ur(l)}}return Kn(l,On)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ee(()=>{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:Ee(()=>{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&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*Li(t,e={}){let r=e.streamUsage??!0,o=e.provider??"openai",n=new Map,s=new Map,a=0,i=!1,u,l,d,p,f=new Set,x=(y,S)=>{let h=s.get(y);if(h!==void 0)return{index:h,isNew:!1};let I=a++;return s.set(y,I),n.set(I,{...S}),{index:I,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let S=n.get(y);S&&(f.add(y),yield{event:"content-block-finish",index:y,content:Ll(S)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:o,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:S,isNew:h}=x(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});h&&(yield{event:"content-block-start",index:S,content:{type:"text",text:""}});let I=n.get(S);I.text=(I.text??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:S,isNew:h}=x(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});h&&(yield{event:"content-block-start",index:S,content:{type:"reasoning",reasoning:""}});let I=n.get(S);I.reasoning=(I.reasoning??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"reasoning-delta",reasoning:y.delta}};continue}if(y.type==="response.output_item.added"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let S=`tool:${y.output_index}`,h=y.item.type==="custom_tool_call",I=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:k,isNew:U}=x(S,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:I,index:y.output_index,...h?{isCustomTool:!0}:{}});if(U&&(yield{event:"content-block-start",index:k,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:I,index:y.output_index}}),I){let q=n.get(k);yield{event:"content-block-delta",index:k,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...q.id!=null?{id:q.id}:{},...q.name!=null?{name:q.name}:{},args:q.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:S,isNew:h}=x(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});h&&(yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let I=n.get(S);I.args=(I.args??"")+y.delta,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...I.id!=null?{id:I.id}:{},...I.name!=null?{name:I.name}:{},args:I.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let S=`tool:${y.output_index}`,h=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:I,isNew:k}=x(S,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:h,index:y.output_index});if(k)yield{event:"content-block-start",index:I,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:h,index:y.output_index}};else{let U=n.get(I);U.args=h,U.id=y.item.call_id,U.name=y.item.name}yield*b(I);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=Vg(y.response.status,y.type),p={model_provider:o,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=Fo(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:o,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of n)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function Vg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Js=class extends mr{constructor(t,e){super(Do(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:$c(t?.tool_choice)?t?.tool_choice:(()=>{let n=js(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,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},o=this._getReasoningParams(t);return o!==void 0&&(r.reasoning=o),r}async _generate(t,e,r){e.signal?.throwIfAborted();let o=this.invocationParams(e);if(o.stream){let n=this._streamResponseChunks(t,e,r),s;for await(let a of n)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...o,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:n.output_text,message:Rn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let o=await this.completionWithRetry({...this.invocationParams(e),input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Li(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(o,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let o=await this.completionWithRetry({...this.invocationParams(e),input:Uo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of o){if(e.signal?.aborted)return;let s=Hs(n);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(n){throw xe(n)}}async completionWithRetry(t,e){let{maxRetries:r,...o}=e??{},n=this._getClientOptions(o);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw xe(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let o of t)if(jo(o))o.type==="image_generation"&&e?.stream&&(o.partial_images=1),r.push(o);else if(cr(o)){let n=o.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Zn(o)){let n={};for(let[s,a]of Object.entries(o))s!=="type"&&s!=="function"&&(n[s]=a);r.push({type:"function",name:o.function.name,parameters:o.function.parameters,description:o.function.description,strict:e?.strict??null,...n})}else Ds(o)&&r.push(Dc(o));return r}};var Zs=class zd 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 o=Do(e,r);super(o),this.fields=o,this.useResponsesApi=o?.useResponsesApi??!1,this.responses=o?.responses??new Js(o),this.completions=o?.completions??new Gs(o)}_useResponsesApi(e){let r=e?.tools?.some(jo),o=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(Ds)||e?.tools?.some(cr);return this.useResponsesApi||r||o||n||Cc(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,o){return this._useResponsesApi(r)?this.responses._generate(e,r,o):this.completions._generate(e,r,o)}async*_streamChatModelEvents(e,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),o);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),o)}async*_streamResponseChunks(e,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),o);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),o)}withConfig(e){let r=new zd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Qs=class extends Ol{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??ge("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ge("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=Ia(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let a={model:this.model,input:s};return this.dimensions&&(a.dimensions=this.dimensions),this.encodingFormat&&(a.encoding_format=this.encodingFormat),this.embeddingWithRetry(a)}),o=await Promise.all(r),n=[];for(let s=0;s<o.length;s+=1){let a=e[s],{data:i}=o[s];for(let u=0;u<a.length;u+=1)n.push(i[u].embedding)}return n}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=et({baseURL:this.clientConfig.baseURL}),o={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=tt(o.defaultHeaders),this.client=new O(o)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw xe(r)}})}};var Zg=v.object({type:v.literal("screenshot")}),Qg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Yg=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Xg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),ey=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),ty=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),ry=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),oy=v.object({type:v.literal("type"),text:v.string()}),ny=v.object({type:v.literal("wait"),duration:v.number().optional()}),sy=v.union([Zg,Qg,Yg,Xg,ey,ty,ry,oy,ny]),sG=v.object({action:sy});var ay=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),uG=v.union([ay]);var mG=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var iy=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),ly=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),uy=v.object({type:v.literal("delete_file"),path:v.string()}),yG=v.union([iy,ly,uy]);var Dd={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Di={default:"text-embedding-ada-002"},ji=new Map,Ys=null,fy=()=>{let t=Ld.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},Fd=async t=>{let e=fy();ji.size===0&&(Ys||(Ys=(async()=>{try{(await jd(`${e}/models`)).data.models.forEach(o=>ji.set(o.name,o))}catch(o){throw Ys=null,o}})()),await Ys);let r=ji.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},hy=async(t="default")=>await Fd(Dd[t]),Ud=async(t="default")=>await Fd(Di[t]),gy=M.Root({agentExecutionContext:M({default:ka,reducer:Sa}),currentIntent:M({default:()=>"none",reducer:lt}),routing:M({default:()=>({mode:"auto"}),reducer:lt}),lastExecutedAgent:M({default:()=>"",reducer:lt}),requiresFollowUp:M({default:()=>!0,reducer:lt}),stepCount:M({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:M({default:()=>"",reducer:Ca})});var yy=t=>typeof t=="string"&&t.length>0?t:void 0,_y=()=>hl(),wy=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,by=t=>{let e=t?.configurable;return{conversationId:yy(e?.thread_id),abortSignal:t?.signal,requestId:_y(),requestSource:wy(my.applicationName)}},Ay=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},qd=async({config:t})=>{let e=Ld.getDefault(),r=(await py.getCredential(`${e.url}/sharing`))?.token;return async(o,n)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=by(t),l=new Headers(n?.headers);for(let p of[...l.keys()]){let f=p.toLowerCase();(f==="authorization"||f==="api-key"||f.startsWith("x-stainless-"))&&l.delete(p)}r&&r.length>0&&l.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(u&&u.length>0&&l.set("X-Esri-Request-Source",u),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i));let d=a&&n?.signal?AbortSignal.any([a,n.signal]):n?.signal??a;return(await jd(o instanceof Request?o.url:o.toString(),{body:Ay(n?.body),headers:Object.fromEntries(l),responseType:"native",signal:d})).data}},Fi=async(t={})=>{let{modelTier:e="default",config:r}=t,o=Dd[e],n=await hy(e);return new Zs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await qd({config:r})}})},Bd=async(t={})=>{let{tier:e="default",config:r}=t,o=Di[e],n=await Ud(e);return new Qs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await qd({config:r})},batchSize:2048,maxConcurrency:10})},xy=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(xy);var Kd="0.1",qo=1536,Gd="openai",Vd=Di.default,Wd=`Name: {name}
|
|
73
73
|
Title: {title}
|
|
74
74
|
Description: {description}`,Hd=`Name: {name}
|
|
75
75
|
Alias: {alias}
|
|
76
|
-
Description: {description}`,Jd=v.object({schemaVersion:v.literal(Kd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Gd),model:v.literal(Vd),dimensions:v.literal(qo),templates:v.object({layer:v.string().default(Wd),field:v.string().default(Hd)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(qo,{message:`Layer vector must be exactly ${qo} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(qo,{message:`Field vector must be exactly ${qo} dimensions`})}))})).default([])});var Iy=(t,e)=>{let r=jl.fromTemplate(t);return br.fromMessages([r,...e])};var
|
|
77
|
-
Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Cy(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(Yd(t))s=t;else if(Sy(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(st(l)){i=l;break}}if(i==null||!st(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(kt))return Array.isArray(t)?r:{messages:r};let o=[],n=null;for(let s of r)kt(s)?s.graph===Be.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>bl(a))?n?n.goto.push(...s.goto):n=new Be({graph:Be.PARENT,goto:s.goto}):o.push(s):o.push(Array.isArray(t)?[s]:{messages:[s]});return n&&o.push(n),o}};var qW=M.Root({llmInputMessages:M({reducer:(t,e)=>on([],e),default:()=>[]})});function D(t,e){let r=t?.configurable?.context;if(!r||typeof r!="object")throw new Error("Agent context missing");let o=e.filter(n=>!(n in r));if(o.length)throw new Error(`Agent context missing: ${o.join(", ")}`);return r}var Ey=t=>{let e=t.map?.allLayers.filter(o=>o.type==="feature"),r=0;return e?.forEach(o=>{let n=o;n.featureEffect&&(n.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},My=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return Ey(r)},Py=E(My,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:c.object({})});var Oy=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},Ry=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return await Oy(r)},Ny=E(Ry,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:c.object({})});var Xd=750;function Bo(t){return"point"in t&&t.point!==void 0}function hr(t){return"layerId"in t&&t.layerId!==void 0}var St=async(t,e)=>{if(Bo(t)){let{point:r}=t;return{geometry:new $y({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(hr(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let o=r.title??r.id,n=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:n,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Xd+1});if(!s.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${n}`};if(s.features.length>Xd)return{error:`Geometry filter for layer "${o}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:ep.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},zy=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Ie=c.enum(zy);var Dy=async(t,e,r,o,n,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",o&&(i.geometry=o,i.spatialRelationship="intersects",n&&(i.distance=n),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${o?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},Fy=async(t,e,r,o,n,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(n){let p=await St(n,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Ly({filter:new jy({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:n?.distance,units:n?.units}),includedEffect:r,excludedEffect:o}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await Dy(e,t.layerId,u,i,n?.distance,n?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${n&&"layerId"in n?` using geometry from layer "${n.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},Uy=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:n="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=D(s,["mapView"]);return await Fy(t,a,o,n,e,r)},qy=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:Ie.optional().describe("The units for the distance buffer.")}),By=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:Ie.optional().describe("The units for the distance buffer.")}),Ky=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer on which to set a feature effect."),where:c.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:c.array(c.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:c.union([qy,By]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:c.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:c.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:c.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),Gy=E(Uy,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Ky});var Hy=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),rp=t=>{if(!t)return!1;let e=t.toLowerCase();return Hy.has(e)},Ui=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},Jy=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Zy=t=>{if(typeof t=="string"&&t)return t;let e=Ui(t);return e?e.toISOString().slice(0,10):null};var Qy=(t,e,r)=>{let o=e?.toLowerCase();if(o&&!rp(o))return t;if(o==="date-only"){let s=Zy(t);return s?Vy(s,Xs("short-date")):t}if(o==="time-only"){if(typeof t=="string"&&t)return Wy(t,Xs("long-time"));let s=Ui(t);return s?tp(s,{...Xs("long-time"),timeZone:"UTC"}):t}let n=Ui(t);return n?tp(n,{...Xs("short-date-short-time"),timeZone:Jy(r)}):t},op=(t,e,r)=>{if(t&&typeof t!="function"){let o="getField"in r&&r.getField?.(t),n=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(n?.type==="coded-value"){let s=n.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},Yy=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Xy=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},e_=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},t_=(t,e,r)=>{let o=Xy(t);if(!o)return t;let n={};e.dateStyle?n.dateStyle=e.dateStyle:(e.year&&(n.year=e.year),e.month&&(n.month=e.month)),e.timeStyle&&(n.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?n.hour12=!0:e.timeStyle&&e.hour12==="never"&&(n.hour12=!1),n.timeZone=Yy(r);try{return new Intl.DateTimeFormat(void 0,n).format(o)}catch{return t}},np=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,sp=(t,e,r,o,n)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?e_(r,s):s?.type==="date-time"?!o||rp(o)?t_(r,s,n):r:Qy(r,o,n)},ap=(t,e,r,o)=>{let n=t.fieldsIndex?.get(e),s=op(e,r,t)??r;return sp(t,e,s,n?.type,o)},ip=(t,e)=>np(t,e),ea=(t,e,r)=>{let o=t.objectIdField,n=e.features.map(a=>a.attributes[o]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let d=i[l.name];if(l.name===o){u[l.name]=d;return}let p=op(l.name,d,t)??d,f=np(t,l.name);u[f]=sp(t,l.name,p,l.type,r)}),u});return{objectIds:n,attributes:s}};var r_=(t,e,r)=>{let o=t.createQuery();return o.outFields=[e],o.where=r||"1=1",o.num=1,o},o_=async(t,e,r,o)=>{let n=o.map?.allLayers.find(d=>d.id===t),s=r_(n,e,r.where),a=(await n.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=ap(n,e,i,o.timeZone),l=ip(n,e);return{tool:"getAttribute",layerName:n.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function n_({layerId:t,fieldName:e,query:r},o){let{mapView:n}=D(o,["mapView"]),s=await o_(t,e,r,n);return JSON.stringify(s,null,2)}var s_=c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:c.string().describe("The name of the field/attribute from which to get a field value."),query:c.object({where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),lp=E(n_,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:s_});var Ko=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let o=new Set((t.availableFields??[]).map(n=>n.toLowerCase()));return o.has("*")?!0:e.every(n=>o.has(n.toLowerCase()))};function gr(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Ct=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};var u_=async t=>{let{targetLayer:e,fieldName:r,statisticType:o,mapView:n,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=n.map?.allLayers.find(S=>S.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await n.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,f;if(a){let S=await St(a,n);if("error"in S)throw new Error(S.error);if(!S.geometry)throw hr(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(hr(a)){let h=n.map?.allLayers.find(I=>I.id===a.layerId);p={geometryLayerName:h?.title??h?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else Bo(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new l_({geometry:S.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let x=Ko(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let S={layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:gr(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[o]}};w=await a_(S);let h=["string","small-integer","integer"],I=l.domain?.type==="coded-value"?l.domain:null;(h.includes(l.type)||I)&&(b=(await i_({layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:gr(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((k,U)=>U.count-k.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(k=>({...k,value:I?I.getName(k.value)??k.value:k.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${o} = ${typeof w?.[o]=="number"?w[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:w?.[o]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:p}}};async function c_({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:o},n){let s=Ct(n,"layersAndFieldsRegistry"),{mapView:a}=D(n,["mapView"]),i=await u_({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:o});return JSON.stringify(i,null,2)}var d_=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:Ie.optional().describe("The units for the distance buffer.")}),p_=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:Ie.optional().describe("The units for the distance buffer.")}),m_=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:c.union([d_,p_]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:c.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:c.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),up=E(c_,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
76
|
+
Description: {description}`,Jd=v.object({schemaVersion:v.literal(Kd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Gd),model:v.literal(Vd),dimensions:v.literal(qo),templates:v.object({layer:v.string().default(Wd),field:v.string().default(Hd)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(qo,{message:`Layer vector must be exactly ${qo} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(qo,{message:`Field vector must be exactly ${qo} dimensions`})}))})).default([])});var Iy=(t,e)=>{let r=jl.fromTemplate(t);return br.fromMessages([r,...e])};var $n=async t=>{let{promptText:e,modelTier:r="default",messages:o,inputVariables:n,schema:s,config:a}=t,i=Iy(e,o??[]),u=(await Fi({modelTier:r,config:a})).withStructuredOutput(s);return await i.pipe(u).invoke(n??{},a)};var vy=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),qV=c.object({fields:c.array(vy)});var BV=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var Zd=async t=>{try{return await(await Bd()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var Yd=t=>Array.isArray(t)&&t.every(tn),Sy=t=>typeof t=="object"&&t!=null&&"messages"in t&&Yd(t.messages),Cy=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ot=class extends Dl{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:o,handleToolErrors:n}=e??{};super({name:r,tags:o,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=n??this.handleToolErrors}async runTool(t,e,r){let o=this.tools.find(n=>n.name===t.name);try{if(o===void 0)throw new Error(`Tool "${t.name}" not found.`);let n={...t,type:"tool_call"},s={...e,state:r,toolCallId:t.id??"",config:e,context:e.context,store:e.store??null,writer:e.writer??e.configurable?.writer??null},a=await o.invoke(n,s);return tn(a)&&a.getType()==="tool"||kt(a)?a:new B({status:"success",name:o.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(n){if(!this.handleToolErrors||qn(n))throw n;return new B({status:"error",content:`Error: ${n.message}
|
|
77
|
+
Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Cy(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(Yd(t))s=t;else if(Sy(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(st(l)){i=l;break}}if(i==null||!st(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(kt))return Array.isArray(t)?r:{messages:r};let o=[],n=null;for(let s of r)kt(s)?s.graph===Be.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>bl(a))?n?n.goto.push(...s.goto):n=new Be({graph:Be.PARENT,goto:s.goto}):o.push(s):o.push(Array.isArray(t)?[s]:{messages:[s]});return n&&o.push(n),o}};var KW=M.Root({llmInputMessages:M({reducer:(t,e)=>on([],e),default:()=>[]})});function D(t,e){let r=t?.configurable?.context;if(!r||typeof r!="object")throw new Error("Agent context missing");let o=e.filter(n=>!(n in r));if(o.length)throw new Error(`Agent context missing: ${o.join(", ")}`);return r}var Ey=t=>{let e=t.map?.allLayers.filter(o=>o.type==="feature"),r=0;return e?.forEach(o=>{let n=o;n.featureEffect&&(n.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},My=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return Ey(r)},Py=E(My,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:c.object({})});var Oy=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},Ry=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return await Oy(r)},$y=E(Ry,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:c.object({})});var Xd=750;function Bo(t){return"point"in t&&t.point!==void 0}function hr(t){return"layerId"in t&&t.layerId!==void 0}var St=async(t,e)=>{if(Bo(t)){let{point:r}=t;return{geometry:new Ny({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(hr(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let o=r.title??r.id,n=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:n,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Xd+1});if(!s.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${n}`};if(s.features.length>Xd)return{error:`Geometry filter for layer "${o}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:ep.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},zy=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Ie=c.enum(zy);var Dy=async(t,e,r,o,n,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",o&&(i.geometry=o,i.spatialRelationship="intersects",n&&(i.distance=n),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${o?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},Fy=async(t,e,r,o,n,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(n){let p=await St(n,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Ly({filter:new jy({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:n?.distance,units:n?.units}),includedEffect:r,excludedEffect:o}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await Dy(e,t.layerId,u,i,n?.distance,n?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${n&&"layerId"in n?` using geometry from layer "${n.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},Uy=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:n="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=D(s,["mapView"]);return await Fy(t,a,o,n,e,r)},qy=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:Ie.optional().describe("The units for the distance buffer.")}),By=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:Ie.optional().describe("The units for the distance buffer.")}),Ky=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer on which to set a feature effect."),where:c.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:c.array(c.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:c.union([qy,By]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:c.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:c.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:c.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),Gy=E(Uy,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Ky});var Hy=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),rp=t=>{if(!t)return!1;let e=t.toLowerCase();return Hy.has(e)},Ui=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},Jy=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Zy=t=>{if(typeof t=="string"&&t)return t;let e=Ui(t);return e?e.toISOString().slice(0,10):null};var Qy=(t,e,r)=>{let o=e?.toLowerCase();if(o&&!rp(o))return t;if(o==="date-only"){let s=Zy(t);return s?Vy(s,Xs("short-date")):t}if(o==="time-only"){if(typeof t=="string"&&t)return Wy(t,Xs("long-time"));let s=Ui(t);return s?tp(s,{...Xs("long-time"),timeZone:"UTC"}):t}let n=Ui(t);return n?tp(n,{...Xs("short-date-short-time"),timeZone:Jy(r)}):t},op=(t,e,r)=>{if(t&&typeof t!="function"){let o="getField"in r&&r.getField?.(t),n=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(n?.type==="coded-value"){let s=n.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},Yy=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Xy=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},e_=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},t_=(t,e,r)=>{let o=Xy(t);if(!o)return t;let n={};e.dateStyle?n.dateStyle=e.dateStyle:(e.year&&(n.year=e.year),e.month&&(n.month=e.month)),e.timeStyle&&(n.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?n.hour12=!0:e.timeStyle&&e.hour12==="never"&&(n.hour12=!1),n.timeZone=Yy(r);try{return new Intl.DateTimeFormat(void 0,n).format(o)}catch{return t}},np=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,sp=(t,e,r,o,n)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?e_(r,s):s?.type==="date-time"?!o||rp(o)?t_(r,s,n):r:Qy(r,o,n)},ap=(t,e,r,o)=>{let n=t.fieldsIndex?.get(e),s=op(e,r,t)??r;return sp(t,e,s,n?.type,o)},ip=(t,e)=>np(t,e),ea=(t,e,r)=>{let o=t.objectIdField,n=e.features.map(a=>a.attributes[o]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let d=i[l.name];if(l.name===o){u[l.name]=d;return}let p=op(l.name,d,t)??d,f=np(t,l.name);u[f]=sp(t,l.name,p,l.type,r)}),u});return{objectIds:n,attributes:s}};var r_=(t,e,r)=>{let o=t.createQuery();return o.outFields=[e],o.where=r||"1=1",o.num=1,o},o_=async(t,e,r,o)=>{let n=o.map?.allLayers.find(d=>d.id===t),s=r_(n,e,r.where),a=(await n.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=ap(n,e,i,o.timeZone),l=ip(n,e);return{tool:"getAttribute",layerName:n.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function n_({layerId:t,fieldName:e,query:r},o){let{mapView:n}=D(o,["mapView"]),s=await o_(t,e,r,n);return JSON.stringify(s,null,2)}var s_=c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:c.string().describe("The name of the field/attribute from which to get a field value."),query:c.object({where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),lp=E(n_,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:s_});var Ko=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let o=new Set((t.availableFields??[]).map(n=>n.toLowerCase()));return o.has("*")?!0:e.every(n=>o.has(n.toLowerCase()))};function gr(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Ct=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};var u_=async t=>{let{targetLayer:e,fieldName:r,statisticType:o,mapView:n,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=n.map?.allLayers.find(S=>S.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await n.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,f;if(a){let S=await St(a,n);if("error"in S)throw new Error(S.error);if(!S.geometry)throw hr(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(hr(a)){let h=n.map?.allLayers.find(I=>I.id===a.layerId);p={geometryLayerName:h?.title??h?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else Bo(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new l_({geometry:S.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let x=Ko(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let S={layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:gr(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[o]}};w=await a_(S);let h=["string","small-integer","integer"],I=l.domain?.type==="coded-value"?l.domain:null;(h.includes(l.type)||I)&&(b=(await i_({layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:gr(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((k,U)=>U.count-k.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(k=>({...k,value:I?I.getName(k.value)??k.value:k.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${o} = ${typeof w?.[o]=="number"?w[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:w?.[o]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:p}}};async function c_({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:o},n){let s=Ct(n,"layersAndFieldsRegistry"),{mapView:a}=D(n,["mapView"]),i=await u_({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:o});return JSON.stringify(i,null,2)}var d_=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:Ie.optional().describe("The units for the distance buffer.")}),p_=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:Ie.optional().describe("The units for the distance buffer.")}),m_=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:c.union([d_,p_]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:c.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:c.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),up=E(c_,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
78
78
|
|
|
79
79
|
USE THIS TOOL FOR:
|
|
80
80
|
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
@@ -95,10 +95,10 @@ USE THIS TOOL FOR:
|
|
|
95
95
|
- Spatial queries \u2014 finding features near/within/intersecting other features
|
|
96
96
|
- Any question where the user wants to SEE or COUNT matching features
|
|
97
97
|
|
|
98
|
-
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:C_});var
|
|
98
|
+
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:C_});var Nn=(t,e)=>e??t,Q_=M.Root({...rs(),intent:M({reducer:Nn}),vectorSearchLayerResults:M({reducer:Nn,default:()=>[]}),vectorSearchFieldResults:M({reducer:Nn}),navigationInternalState:M({reducer:Nn,default:()=>({toolCallMessage:void 0})})}),gp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function nt(t){let e=Object.entries(gp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
99
99
|
Available prompts:
|
|
100
100
|
${Object.keys(gp).join(`
|
|
101
|
-
`)}`);return await e[1]()}var Y_=M.Root({...Ot(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),queryResponse:M(),dataExplorationMessages:M({reducer:on,default:()=>[]})}),wp=[lp,up,cp,dp];var
|
|
101
|
+
`)}`);return await e[1]()}var Y_=M.Root({...Ot(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),queryResponse:M(),dataExplorationMessages:M({reducer:on,default:()=>[]})}),wp=[lp,up,cp,dp];var ZH=new ot(wp,{handleToolErrors:!1});async function X_(t){let{fields:e,layer:r,view:o,styleName:n,colorSchemeTags:s}=t,a;return s?a=E_({basemapTheme:await fp(o),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=M_({basemapTheme:await fp(o),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:o,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:n.includes("Size"),pieChartScheme:a}}async function ew(t){return await k_(t)}async function tw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:o,layer:i,view:a,colorSchemeTags:n};try{let l=await X_(u),d=await ew(l);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var rw=["mapView"];function Oe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=rw.filter(o=>!(o in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function ow({layerId:t,fields:e,colorSchemes:r,includeSize:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await tw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:o})}var nw=c.object({layerId:c.string().describe("The id of the layer to apply the chart renderer to"),fields:c.array(c.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),sw=E(ow,{name:"chart",description:`Label: Charts
|
|
102
102
|
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
103
103
|
Keywords: pie, chart, all categories, breakdown, proportion
|
|
104
104
|
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
@@ -120,7 +120,7 @@ ${Object.keys(gp).join(`
|
|
|
120
120
|
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
121
121
|
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
122
122
|
Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
|
|
123
|
-
Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:xw});function vw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s;return n&&(s
|
|
123
|
+
Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:xw});function vw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s;return n&&(s=N_({includedTags:n,numColors:Math.min(e.length,8)})[0]),{layer:r,view:o,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function Tw(t){return await $_(t)}async function Sw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:o,layer:a,view:s,colorSchemeTags:n};try{let u=vw(i),l=await Tw(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function Cw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Oe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await Sw({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var kw=c.object({layerId:c.string().describe("The id of the layer to apply the dot density renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),Ew=E(Cw,{name:"dot-density",description:`Dot Density
|
|
124
124
|
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
125
125
|
**Use cases:**
|
|
126
126
|
- Population distribution visualization
|
|
@@ -131,11 +131,11 @@ ${Object.keys(gp).join(`
|
|
|
131
131
|
- Visualize distribution of different crops across regions
|
|
132
132
|
- Display demographic patterns within census tracts
|
|
133
133
|
**Fields:** Requires 2-8 number fields.
|
|
134
|
-
**Keywords:** density, how much, how many, total, number, amount`,schema:kw});function Mw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s,a=e[0];return n&&(s=L_({includedTags:n,basemap:o.map?.basemap||"topo"})[0]),{layer:r,view:o,field:a,heatmapScheme:s}}async function Pw(t){return await z_(t)}async function Ow({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:o,layer:a,view:s,colorSchemeTags:n};try{let u=Mw(i),l=await Pw(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function Rw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Oe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await Ow({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var
|
|
134
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:kw});function Mw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s,a=e[0];return n&&(s=L_({includedTags:n,basemap:o.map?.basemap||"topo"})[0]),{layer:r,view:o,field:a,heatmapScheme:s}}async function Pw(t){return await z_(t)}async function Ow({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:o,layer:a,view:s,colorSchemeTags:n};try{let u=Mw(i),l=await Pw(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function Rw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Oe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await Ow({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var $w=c.object({layerId:c.string().describe("The id of the layer to apply the heatmap renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),Nw=E(Rw,{name:"heatmap",description:`Label: Heat Map
|
|
135
135
|
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
136
136
|
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
137
137
|
Example: Create a heatmap
|
|
138
|
-
Fields: This typically requires zero or one field of type number.`,schema
|
|
138
|
+
Fields: This typically requires zero or one field of type number.`,schema:$w});function zw(t){let{fields:e,layer:r,view:o,styleName:n,colorSchemeTags:s}=t,a;return s&&(a=D_({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:o,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:n.includes("Size"),predominanceScheme:a}}async function Lw(t){return await j_(t)}async function jw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:o,layer:i,view:a,colorSchemeTags:n};try{let l=zw(u),d=await Lw(l);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function Dw({layerId:t,fields:e,colorSchemes:r,includeSize:o},n){let{mapView:s}=Oe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await jw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:o})}var Fw=c.object({layerId:c.string().describe("The id of the layer to apply the predominance renderer to"),fields:c.array(c.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),Uw=E(Dw,{name:"predominance",description:`Label: Predominant category
|
|
139
139
|
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
140
140
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
141
141
|
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
@@ -167,7 +167,7 @@ Fields: This typically requires zero or one field of type number.`,schema:Nw});f
|
|
|
167
167
|
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
168
168
|
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
169
169
|
Example: Color each feature based on the region it belongs to
|
|
170
|
-
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:cb}),pb=M.Root({...Ot(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),selectedLayerId:M()}),mb=M.Root({...Ot(),helpInternalState:M({reducer
|
|
170
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:cb}),pb=M.Root({...Ot(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),selectedLayerId:M()}),mb=M.Root({...Ot(),helpInternalState:M({reducer:Nn,default:()=>({toolCallMessage:void 0})})}),fb=M.Root({...Ot(),intent:M({reducer:(t,e)=>e}),arcgisKnowledgeMessages:M({reducer:on,default:()=>[]}),arcgisKnowledgeToolResult:M({reducer:(t,e)=>e,default:()=>null})});function bp(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function Ho(t){return!!t?.map&&"activeLinkChartLayer"in t.map}async function na(t){!Ho(t)||!t.map.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Ln(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&bp(r),{view:r}}async function Jo(t){let e=t?.configurable?.context;if(hb(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await hp(o)}}else{bp(e.view);let o=(e.view.map?.allLayers.find(n=>n.type==="knowledge-graph")).url;if(!o)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await hp(o)}}}}function hb(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var Bi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=oa.fromDataModel(e)}},oa=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let o of e.entityTypes)r.entityTypes.push(zn.fromEntityType(o));for(let o of e.relationshipTypes)r.relationshipTypes.push(Ki.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:gb(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(n=>n.name).join(", "),o=e.relationshipTypes.map(n=>n.name).join(", ");return`Entity Types: ${r}.
|
|
171
171
|
Relationship Types: ${o}.`}},zn=class t{constructor(){this.name="",this.properties=[]}static fromEntityType(e){let r=new t;r.name=e.name,r.alias=e.alias?e.alias:void 0,r.role=yb(e.role);for(let o of e.properties){let n={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:_b(o.role),geometryDef:o.fieldType==="esriFieldTypeGeometry"?{geometryType:o.geometryType??"esriGeometryAny",hasM:o.hasM?o.hasM:void 0,hasZ:o.hasZ?o.hasZ:void 0}:void 0};r.properties.push(n)}return r}},Ki=class extends zn{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=zn.fromEntityType(e);r.observedEndPoints=[];for(let o of e.endPoints)r.observedEndPoints.push({originEntityType:o.originEntityType,destinationEntityType:o.destinationEntityType});return r}},gb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},yb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function _b(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function sa(t){return t?.signal}async function wb(t,e){let r=await nt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
|
|
172
172
|
|
|
173
173
|
Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
|
|
@@ -193,7 +193,7 @@ Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:d,ad
|
|
|
193
193
|
- "expand company x through all the buildings it owns"
|
|
194
194
|
- "connect company x and company y"
|
|
195
195
|
- "connect all buildings on the link chart"
|
|
196
|
-
`,schema:Pb});async function
|
|
196
|
+
`,schema:Pb});async function $b(t,e){return await e.map?.applyLayout(t),await na(e),{appliedLayout:t}}var Gi="applyLayout",Nb=c.object({layout:c.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),zb=async({layout:t},e)=>{let{view:r}=Ln(e);if(Ho(r)){let{appliedLayout:o}=await $b(t,r);return{toolName:Gi,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}else return{toolName:Gi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error}},Lb=E(zb,{name:Gi,description:"Apply a diagram layout to the link chart",schema:Nb});async function jb(t,e){return e.map?.changeNonspatialDataDisplay(t),await na(e),{appliedNonspatialDataDisplayMode:t}}var Vi="changeNonspatialVisibility",Db=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Fb=async({setting:t},e)=>{let{view:r}=Ln(e);if(Ho(r)){let{appliedNonspatialDataDisplayMode:o}=await jb(t,r);return{toolName:Vi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}else return{toolName:Vi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error}},Ub=E(Fb,{name:Vi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Db});async function qb(t,e,r,o,n){let s,a="";for(let i=1;i<=Vo;i++){let{graphQuery:u,explanation:l}=await Qi(t,e.dataModel,r,n,s);try{await J({text:`Attempting to create link chart from derived query: ${u}`},n);let d=await V_.fromCypherQuery(e,new _p({openCypherQuery:u}));await J({text:"Link chart created successfully, loading..."},n),await d.load();let p=o.map;return o.map=d,await o.when(),await yp.whenOnce(()=>!o.updating),d.entityCount===0&&d.relationshipCount===0?(o.map===d&&(o.map=p),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
|
|
197
197
|
${u}
|
|
198
198
|
|
|
199
199
|
Explanation: ${l}`}):(await na(o),{type:"success",graphQuery:u,explanation:l})}catch(d){let p=Zo(d);if(i>=Vo){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await J({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},n)}}return{type:"error",errorMessage:`Failed to create link chart after ${Vo} attempts. Last error: ${a}`}}var ra="createLinkChart",Bb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),Kb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e),{view:o}=Ln(e);if(Ho(o)){let n=Wo.getDefault().helperServices,s=await qb(`${t}
|
|
@@ -227,7 +227,7 @@ ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
|
227
227
|
${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
228
228
|
`)}`;return`${s}
|
|
229
229
|
|
|
230
|
-
${a}`};async function Xb(t,e,r){let o=await nt("arcgis_knowledge_lucene_generation_prompt"),n={inquiry:t,dataModelForSearch:Yb(e)},s=c.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=c.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=c.array(c.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=c.object({query:c.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await
|
|
230
|
+
${a}`};async function Xb(t,e,r){let o=await nt("arcgis_knowledge_lucene_generation_prompt"),n={inquiry:t,dataModelForSearch:Yb(e)},s=c.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=c.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=c.array(c.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=c.object({query:c.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await $n({promptText:o,inputVariables:n,schema:u,config:r})}var Ji="searchGraphData",eA=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),tA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Jo(e);await J({text:"Generating search query for the user inquiry"},e);let o=await Xb(t,r,e);await J({text:"Executing graph search with generated search query"},e);let n=await Eb({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:sa(e),timeout:e?.timeout}});if(n.type!=="success")return{toolName:Ji,status:"error",errorMessage:n.errorMessage,error:"error"in n?n.error:null};for(let i of n.results)Go(i,u=>Ap(u));let s=10,a=n.results.slice(0,s);return{toolName:Ji,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
|
|
231
231
|
Query: ${o.query}
|
|
232
232
|
Type Category Filter: ${o.typeCategoryFilter}
|
|
233
233
|
Named Type Filters: ${o.typeFilters?o.typeFilters.join(", "):"None"}
|
|
@@ -247,7 +247,7 @@ ${a}`};async function Xb(t,e,r){let o=await nt("arcgis_knowledge_lucene_generati
|
|
|
247
247
|
- "Find all references to 'delayed parts shipment'"
|
|
248
248
|
- "Find all reports authored by someone with the title of 'Researcher'"
|
|
249
249
|
- "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
|
|
250
|
-
- "Search for all john smiths and show their global ids`,schema:eA});async function iA(t,e){let r=nA.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let n=o.url,s=`${Yi.assetsPath?.endsWith("/")?Yi.assetsPath:`${Yi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await sA(n,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new aA({url:s,width:24,height:24}),u=new oA({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}async function lA({address:t},e){let{mapView:r}=D(e,["mapView"]);return await iA(t,r)}var uA=c.object({address:c.string().describe("The full address or place name to locate.")}),cA=E(lA,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:uA});async function dA(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(s=>s.name===t);if(!o)throw new Error(`Bookmark with name "${t}" not found.`);let n=o.viewpoint;if(!n)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(n),{text:`Navigated to bookmark: ${t}`}}async function pA({bookmarkName:t},e){let{mapView:r}=D(e,["mapView"]);return await Promise.resolve(dA(t,r))}var mA=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),fA=E(pA,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:mA});async function hA(t,e,r){let o=r.map?.allLayers.find(a=>a.id===t);if(!o)return{text:`Error: Layer with id ${t} not found`};let n=e?.trim()?e:"1=1",s=o.createQuery();s.where=n;try{let{extent:a,count:i}=await o.queryExtent(s);if(i===0)return{text:`No features found in ${o.title} matching: ${n}`,where:n};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${o.title}`,where:n};let u={layerId:t,layerTitle:o.title??t,where:n,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${o.title} matching: ${n}`,where:n,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:n}}}async function gA({layerId:t,where:e},r){let{mapView:o}=D(r,["mapView"]);return await hA(t,e,o)}var yA=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Start with a fresh filter for the current request unless the task explicitly refers to prior results. Use only field name values from the selected layer, not aliases. Use field metadata only to interpret intent: prefer LIKE '%value%' for string fields, and use =, <, >, BETWEEN, IN, IS NULL, AND/OR/NOT as appropriate for number/date fields. For coded-value domain fields, use the domain code already provided in layerInfo.domain.codedValues, never the display label. Respect range-domain bounds when they are provided. Do NOT include subqueries, nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),_A=E(gA,{name:"goToFeatures",description:"Go to the features that match the given filter for the given layerId. Use coded-value domain codes from layer field metadata when building the WHERE clause.",schema:yA});async function bA(t){let e=new wA({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function AA(t,e){let{mapView:r}=D(e,["mapView"]);return await bA(r)}var xA=v.object({}),IA=E(AA,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:xA});async function vA(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function TA(t,e){let{mapView:r}=D(e,["mapView"]);return await vA(r)}var SA=c.object({}),CA=E(TA,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:SA});async function kA(t,e){await e.when();let r=e.map?.allLayers.find(n=>n.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?o=e.map.diagramNodesExtent:o=r.fullExtent,o?(await e.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function EA({layerId:t},e){let{mapView:r}=D(e,["mapView"]);return await kA(t,r)}var MA=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),PA=E(EA,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:MA});async function OA(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function RA({scale:t},e){let{mapView:r}=D(e,["mapView"]);return await OA(t,r)}var
|
|
250
|
+
- "Search for all john smiths and show their global ids`,schema:eA});async function iA(t,e){let r=nA.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let n=o.url,s=`${Yi.assetsPath?.endsWith("/")?Yi.assetsPath:`${Yi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await sA(n,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new aA({url:s,width:24,height:24}),u=new oA({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}async function lA({address:t},e){let{mapView:r}=D(e,["mapView"]);return await iA(t,r)}var uA=c.object({address:c.string().describe("The full address or place name to locate.")}),cA=E(lA,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:uA});async function dA(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(s=>s.name===t);if(!o)throw new Error(`Bookmark with name "${t}" not found.`);let n=o.viewpoint;if(!n)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(n),{text:`Navigated to bookmark: ${t}`}}async function pA({bookmarkName:t},e){let{mapView:r}=D(e,["mapView"]);return await Promise.resolve(dA(t,r))}var mA=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),fA=E(pA,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:mA});async function hA(t,e,r){let o=r.map?.allLayers.find(a=>a.id===t);if(!o)return{text:`Error: Layer with id ${t} not found`};let n=e?.trim()?e:"1=1",s=o.createQuery();s.where=n;try{let{extent:a,count:i}=await o.queryExtent(s);if(i===0)return{text:`No features found in ${o.title} matching: ${n}`,where:n};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${o.title}`,where:n};let u={layerId:t,layerTitle:o.title??t,where:n,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${o.title} matching: ${n}`,where:n,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:n}}}async function gA({layerId:t,where:e},r){let{mapView:o}=D(r,["mapView"]);return await hA(t,e,o)}var yA=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Start with a fresh filter for the current request unless the task explicitly refers to prior results. Use only field name values from the selected layer, not aliases. Use field metadata only to interpret intent: prefer LIKE '%value%' for string fields, and use =, <, >, BETWEEN, IN, IS NULL, AND/OR/NOT as appropriate for number/date fields. For coded-value domain fields, use the domain code already provided in layerInfo.domain.codedValues, never the display label. Respect range-domain bounds when they are provided. Do NOT include subqueries, nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),_A=E(gA,{name:"goToFeatures",description:"Go to the features that match the given filter for the given layerId. Use coded-value domain codes from layer field metadata when building the WHERE clause.",schema:yA});async function bA(t){let e=new wA({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function AA(t,e){let{mapView:r}=D(e,["mapView"]);return await bA(r)}var xA=v.object({}),IA=E(AA,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:xA});async function vA(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function TA(t,e){let{mapView:r}=D(e,["mapView"]);return await vA(r)}var SA=c.object({}),CA=E(TA,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:SA});async function kA(t,e){await e.when();let r=e.map?.allLayers.find(n=>n.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?o=e.map.diagramNodesExtent:o=r.fullExtent,o?(await e.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function EA({layerId:t},e){let{mapView:r}=D(e,["mapView"]);return await kA(t,r)}var MA=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),PA=E(EA,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:MA});async function OA(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function RA({scale:t},e){let{mapView:r}=D(e,["mapView"]);return await OA(t,r)}var $A=c.object({scale:c.number().describe("The map scale of the view to go to.")}),NA=E(RA,{name:"goToScale",description:"Go to the specified view scale.",schema:$A});async function LA(t,e,r){let o={target:new zA({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await e.goTo(o),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function jA({center:t,zoom:e,scale:r},o){let{mapView:n}=D(o,["mapView"]);return await LA(t,n,{zoom:e,scale:r})}var DA=c.object({center:c.object({longitude:c.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:c.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:c.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:c.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),FA=E(jA,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:DA});async function UA(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function qA({zoom:t},e){let{mapView:r}=D(e,["mapView"]);return await UA(t,r)}var BA=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),KA=E(qA,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:BA});var EJ=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
251
251
|
This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
|
|
252
252
|
|
|
253
253
|
Supported actions:
|
|
@@ -266,11 +266,11 @@ ${a}`};async function Xb(t,e,r){let o=await nt("arcgis_knowledge_lucene_generati
|
|
|
266
266
|
_Example: “Center the map on San Francisco at scale 50000”_
|
|
267
267
|
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
268
268
|
_Example: “Go to the Downtown bookmark”_
|
|
269
|
-
_Example: “Where is Mount Rainier?”_`;var
|
|
269
|
+
_Example: “Where is Mount Rainier?”_`;var HJ=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
|
|
270
270
|
_Example: “Color points by sales amount”_
|
|
271
271
|
_Example: “Show population density with a color gradient”_
|
|
272
272
|
_Example: “Create a relationship map between height and depth”_
|
|
273
|
-
_Example: “Vary circle sizes according to population”_`;var
|
|
273
|
+
_Example: “Vary circle sizes according to population”_`;var T3=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
|
|
274
274
|
The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
|
|
275
275
|
_Example: “Only show stations where Brand is Shell”_
|
|
276
276
|
_Example: “Make Shell stations stand out on the map”_
|
|
@@ -283,7 +283,7 @@ ${a}`};async function Xb(t,e,r){let o=await nt("arcgis_knowledge_lucene_generati
|
|
|
283
283
|
This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var GA=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let o=Array.from(r.fieldRegistry.values()),n=o.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
|
|
284
284
|
`);return`**${r.layerItem.title}** has ${o.length} field(s):
|
|
285
285
|
|
|
286
|
-
${n}`},VA=({layerTitle:t},e)=>{let r=Ct(e,"layersAndFieldsRegistry");return GA(r,t)},WA=E(VA,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:c.object({layerTitle:c.string().describe("The title or partial title of the layer to list fields for.")})});var
|
|
286
|
+
${n}`},VA=({layerTitle:t},e)=>{let r=Ct(e,"layersAndFieldsRegistry");return GA(r,t)},WA=E(VA,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:c.object({layerTitle:c.string().describe("The title or partial title of the layer to list fields for.")})});var Z3=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
|
|
287
287
|
|
|
288
288
|
_Example: “Tell me about this map”_
|
|
289
289
|
_Example: “List all layers in this map”_
|
|
@@ -296,7 +296,7 @@ ${n}`},VA=({layerTitle:t},e)=>{let r=Ct(e,"layersAndFieldsRegistry");return GA(r
|
|
|
296
296
|
|
|
297
297
|
IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
|
|
298
298
|
_Example: "Create a chart"_
|
|
299
|
-
_Example: "Create a table"_`;var
|
|
299
|
+
_Example: "Create a table"_`;var hZ=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
|
|
300
300
|
This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
|
|
301
301
|
For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
|
|
302
302
|
expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
|
|
@@ -334,7 +334,7 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
|
|
|
334
334
|
_example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
|
|
335
335
|
_example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
|
|
336
336
|
_example: "Find John Smith and all people he has made phone calls to in the last year"_
|
|
337
|
-
_example: "What is the average age of all people who work for Esri?"_`;var Re
|
|
337
|
+
_example: "What is the average age of all people who work for Esri?"_`;var Re=$n;var oe=J,Sp=Zd;var Qo=()=>rs(),ia=async(t,e)=>await fe(t,e),la=async({modelTier:t="default",config:e}={})=>await Fi({modelTier:t,config:e});var Wp=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function _r(t){if(!Wp(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var ZA=`
|
|
338
338
|
Write a concise, friendly success message for adding members to a group.
|
|
339
339
|
|
|
340
340
|
Rules:
|
|
@@ -409,8 +409,8 @@ User message:
|
|
|
409
409
|
`,ax=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),ix=async(t,e)=>{await oe({text:"Thinking about groups...",agentName:"group-creation"},e);let r=qe(t.agentExecutionContext.messages).trim(),o=await Re({promptText:sx,schema:ax,modelTier:"default",inputVariables:{userMessage:r}}),n=o.title.trim(),s=o.memberIdentifiers.filter(Boolean),a=o.clarifyMessage.trim(),i=o.intent==="create"&&!!n,u=o.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:n}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},lx=["general","about","homePage","gallery","aiAssistants","map","items","groups","webhooks","utilityServices","agol","esriContent","livingAtlas","servers","memberRoles","newMemberDefaults","marketplace","collaborations","credits","security","openData","hub","orgExtensions"],ux=["newItem","createLayer","developerCredentials"],cx=["favorites","group","living-atlas","org"],dx=["featured","my","organization"],px=["licenses","members","overview","reports","settings","status"],mx=c.object({destinationType:c.literal("portal-content"),hash:c.enum(cx).optional(),queryParams:c.object({newItem:c.enum(ux).optional()}).optional()}),fx=c.object({destinationType:c.literal("portal-groups"),hash:c.enum(dx).optional()}),hx=c.object({destinationType:c.literal("portal-org"),hash:c.enum(px).optional(),queryParams:c.object({tab:c.enum(lx).optional(),section:c.string().optional(),subsection:c.string().optional(),period:c.string().optional(),startTime:c.string().optional(),endTime:c.string().optional()}).optional()}),gx=c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),yx=c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1)}),_x=c.object({destinationType:c.union([c.literal("portal-gallery"),c.literal("portal-map-viewer"),c.literal("portal-notebooks"),c.literal("portal-scene-viewer")])}),wx=c.union([mx,fx,hx,gx,yx,_x]),Hp="portal-navigation",ma=async(t,e)=>{let r=e?.configurable?.context;!Wp(r)||!r.navigationTargetMap?.[t.destinationType]||await ia({type:Hp,data:{...t}},e)},bx=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await oe({text:"Preparing navigation...",agentName:"group-creation"},e),await ma({destinationType:"portal-group",groupId:r},e),{}):{}},Rp=(t,e)=>e??t,Jp=M.Root({...Qo(),intentParams:M({reducer:Rp,default:()=>({intent:"clarify"})}),createdGroupId:M({reducer:Rp,default:()=>""})}),Ax=()=>new ce(Jp).addNode("detectGroupCreationIntent",ix).addNode("createPortalGroup",nx).addNode("addMembersToPortalGroup",XA).addNode("suggestCreatedGroupNavigation",bx).addEdge(ue,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return K}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",K),xx=String.raw`- **portal-group-creation** - Portal group creation assistant:
|
|
410
410
|
- creates a new ArcGIS Portal group for the signed-in user
|
|
411
411
|
- adds users to the newly created group using @mention usernames
|
|
412
|
-
`,Ix={id:"portal-group-creation",name:"Portal Group Creation",description:xx,createGraph:Ax,workspace:Jp},Zp="portalDocAssistantMemory",vx=()=>({conversationId:""}),Tx=t=>{let e=t?.[Zp]?.value;if(!e||typeof e!="object")return vx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Sx=t=>({[Zp]:{value:t}}),Cx={pipeline:{follow_up:{allow:!1}}};function kx(t){return{kind:"DocAIAssistantRequest",filters:{...Cx,persona:{persona:t}}}}var Ex="https://www.arcgis.com/sharing/rest";async function Mx({portal:t,question:e,persona:r,previousConversationId:o,useProdDocAssistant:n,signal:s,skillId:a}){a??="doc_ai_assistant";let i=kx(r),u=await Px({portal:t,skillId:a,message:e,options:{context:i,previousConversationId:o,useProdDocAssistant:n,signal:s}});return{reply:Ox(u,a),conversationId:u[0]?.conversationId??""}}async function Px({portal:t,skillId:e,message:r,options:o}){let n=t.helperServices.aiAssistantServices.url,s=`${o.useProdDocAssistant?"https://aiservices-beta.arcgis.com":n}/skills/${e}/chat`,a={"Content-Type":"application/json",token:o.useProdDocAssistant?(await Cp.getCredential(Ex,{oAuthPopupConfirmation:!1})).token:Cp.findCredential(t.url)?.token??""},i=await kp(s,{method:"post",body:JSON.stringify({message:r,context:o.context,conversationId:o.previousConversationId}),headers:a,signal:o.signal});if(i.httpStatus!==200)throw new Error(`Doc assistant chat failed (${i.httpStatus})`,{cause:i.data});let u=i.data,l=[u],{conversationId:d,inquiryId:p}=u,f=async(x,w)=>{if(!w)return;await _l(500);let b=await kp(s,{method:"post",body:JSON.stringify({conversationId:d,inquiryId:p,ackSequenceNumber:x}),headers:a,signal:o.signal});if(b.httpStatus!==200)throw new Error(`Doc assistant poll failed (${b.httpStatus})`,{cause:b.data});let y=b.data;l.push(y),await f(y.sequenceNumber,y.hasMore)};return u.hasMore&&await f(u.sequenceNumber,u.hasMore),l}function Ox(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let o=t[r];if(o.context?.kind==="DocAIAssistantContext"){let n=o.context.results?.[0]?.reply;if(n)return n}}return"";default:return en(e)}}var Rx=async(t,e)=>{await oe({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=qe(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let o=e?.configurable?.context;_r(o);let n=Tx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Mx({portal:o.portal,question:r,previousConversationId:n.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online",useProdDocAssistant:o.useProdDocAssistant});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:Sx({conversationId:a||n.conversationId})}},Qp=E(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;_r(o);try{return(await Fl(o.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(n){return console.error("Error searching for portal group by title:",n),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:c.object({groupTitle:c.string().describe("The portal group title to resolve to a group id.")})}),Yp=E(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;_r(o);let{result:n,error:s}=await Bl(o.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),n?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:c.object({itemTitle:c.string().describe("The portal item title to resolve to an item id.")})});function Dn(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let o=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return o?.[1]?o[1].trim():null}function
|
|
413
|
-
`)}var zx={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"]},"portal-content-favorites":{description:"The Favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"]},"portal-content-group":{description:"The Groups view under Content in the portal.",hints:["Content groups","Group content","My groups content"]},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content living atlas"]},"portal-content-organization":{description:"The Organization view under Content in the portal.",hints:["Organization content","Content organization","My organization content"]},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"]},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"]},"portal-groups":{description:"The groups listing page of the portal.",hints:["Groups","Browse groups"]},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"]},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"]},"portal-groups-organization":{description:"The Organization groups view under Groups in the portal.",hints:["Organization groups","Groups organization","My organization groups"]},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"]},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"]},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"]},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"]},"portal-org-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],sections:{"custom-sign-in":{description:"The Organization > Settings > Security > Custom Sign In section of the portal.",hints:["Custom Sign In","Organization > Settings > Security > Custom Sign In"]},logins:{description:"The Organization > Settings > Security > Logins section of the portal.",hints:["Logins","Organization > Settings > Security > Logins"]},"change-login-provider":{description:"The Organization > Settings > Security > Change Login Provider section of the portal.",hints:["Change Login Provider","Organization > Settings > Security > Change Login Provider"]},"multifactor-auth":{description:"The Organization > Settings > Security > Multifactor Authentication section of the portal.",hints:["MFA","Multifactor Authentication","Organization > Settings > Security > MFA"]},"multifactor-enforcement":{description:"The Organization > Settings > Security > Enforce MFA section of the portal.",hints:["Enforce MFA","MFA enforcement","Organization > Settings > Security > Enforce MFA"]},"multifactor-designated-admins":{description:"The Organization > Settings > Security > Designated Admins section of the portal.",hints:["Designated admins","MFA designated admins","Organization > Settings > Security > Designated Admins"]}}},"portal-content-new-item":{description:"The Content page with the New Item flow opened.",hints:["New item","Create new item","Content > My Content > New Item"],sections:{"feature-layer":{description:"The Content page with New Item flow set to Feature Layer as the starting step.",hints:["Feature Layer","New Feature Layer","Content > My Content > New Item > Feature Layer"]},"developer-credentials":{description:"The Content page with New Item flow set to Developer Credentials as the starting step.",hints:["Developer Credentials","New developer credentials","Content > My Content > New Item > Developer Credentials"]}}}},Xp
|
|
412
|
+
`,Ix={id:"portal-group-creation",name:"Portal Group Creation",description:xx,createGraph:Ax,workspace:Jp},Zp="portalDocAssistantMemory",vx=()=>({conversationId:""}),Tx=t=>{let e=t?.[Zp]?.value;if(!e||typeof e!="object")return vx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Sx=t=>({[Zp]:{value:t}}),Cx={pipeline:{follow_up:{allow:!1}}};function kx(t){return{kind:"DocAIAssistantRequest",filters:{...Cx,persona:{persona:t}}}}var Ex="https://www.arcgis.com/sharing/rest";async function Mx({portal:t,question:e,persona:r,previousConversationId:o,useProdDocAssistant:n,signal:s,skillId:a}){a??="doc_ai_assistant";let i=kx(r),u=await Px({portal:t,skillId:a,message:e,options:{context:i,previousConversationId:o,useProdDocAssistant:n,signal:s}});return{reply:Ox(u,a),conversationId:u[0]?.conversationId??""}}async function Px({portal:t,skillId:e,message:r,options:o}){let n=t.helperServices.aiAssistantServices.url,s=`${o.useProdDocAssistant?"https://aiservices-beta.arcgis.com":n}/skills/${e}/chat`,a={"Content-Type":"application/json",token:o.useProdDocAssistant?(await Cp.getCredential(Ex,{oAuthPopupConfirmation:!1})).token:Cp.findCredential(t.url)?.token??""},i=await kp(s,{method:"post",body:JSON.stringify({message:r,context:o.context,conversationId:o.previousConversationId}),headers:a,signal:o.signal});if(i.httpStatus!==200)throw new Error(`Doc assistant chat failed (${i.httpStatus})`,{cause:i.data});let u=i.data,l=[u],{conversationId:d,inquiryId:p}=u,f=async(x,w)=>{if(!w)return;await _l(500);let b=await kp(s,{method:"post",body:JSON.stringify({conversationId:d,inquiryId:p,ackSequenceNumber:x}),headers:a,signal:o.signal});if(b.httpStatus!==200)throw new Error(`Doc assistant poll failed (${b.httpStatus})`,{cause:b.data});let y=b.data;l.push(y),await f(y.sequenceNumber,y.hasMore)};return u.hasMore&&await f(u.sequenceNumber,u.hasMore),l}function Ox(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let o=t[r];if(o.context?.kind==="DocAIAssistantContext"){let n=o.context.results?.[0]?.reply;if(n)return n}}return"";default:return en(e)}}var Rx=async(t,e)=>{await oe({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=qe(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let o=e?.configurable?.context;_r(o);let n=Tx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Mx({portal:o.portal,question:r,previousConversationId:n.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online",useProdDocAssistant:o.useProdDocAssistant});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:Sx({conversationId:a||n.conversationId})}},Qp=E(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;_r(o);try{return(await Fl(o.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(n){return console.error("Error searching for portal group by title:",n),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:c.object({groupTitle:c.string().describe("The portal group title to resolve to a group id.")})}),Yp=E(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;_r(o);let{result:n,error:s}=await Bl(o.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),n?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:c.object({itemTitle:c.string().describe("The portal item title to resolve to an item id.")})});function Dn(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let o=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return o?.[1]?o[1].trim():null}function $x(t){let e=Fn(t).flatMap(r=>{let o=r,n=t[r],s=[o,{description:n.description,hints:n.hints}],a=n.sections?Fn(n.sections).map(i=>{let u=n.sections?.[i];return[`${o}-${i}`,u]}):[];return[s,...a]});return Object.fromEntries(e)}function Nx(t){return Object.entries(t).map(([e,{description:r,hints:o}])=>` - ${e}: ${r} (hints: ${o.join(", ")})`).join(`
|
|
413
|
+
`)}var zx={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"]},"portal-content-favorites":{description:"The Favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"]},"portal-content-group":{description:"The Groups view under Content in the portal.",hints:["Content groups","Group content","My groups content"]},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content living atlas"]},"portal-content-organization":{description:"The Organization view under Content in the portal.",hints:["Organization content","Content organization","My organization content"]},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"]},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"]},"portal-groups":{description:"The groups listing page of the portal.",hints:["Groups","Browse groups"]},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"]},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"]},"portal-groups-organization":{description:"The Organization groups view under Groups in the portal.",hints:["Organization groups","Groups organization","My organization groups"]},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"]},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"]},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"]},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"]},"portal-org-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],sections:{"custom-sign-in":{description:"The Organization > Settings > Security > Custom Sign In section of the portal.",hints:["Custom Sign In","Organization > Settings > Security > Custom Sign In"]},logins:{description:"The Organization > Settings > Security > Logins section of the portal.",hints:["Logins","Organization > Settings > Security > Logins"]},"change-login-provider":{description:"The Organization > Settings > Security > Change Login Provider section of the portal.",hints:["Change Login Provider","Organization > Settings > Security > Change Login Provider"]},"multifactor-auth":{description:"The Organization > Settings > Security > Multifactor Authentication section of the portal.",hints:["MFA","Multifactor Authentication","Organization > Settings > Security > MFA"]},"multifactor-enforcement":{description:"The Organization > Settings > Security > Enforce MFA section of the portal.",hints:["Enforce MFA","MFA enforcement","Organization > Settings > Security > Enforce MFA"]},"multifactor-designated-admins":{description:"The Organization > Settings > Security > Designated Admins section of the portal.",hints:["Designated admins","MFA designated admins","Organization > Settings > Security > Designated Admins"]}}},"portal-content-new-item":{description:"The Content page with the New Item flow opened.",hints:["New item","Create new item","Content > My Content > New Item"],sections:{"feature-layer":{description:"The Content page with New Item flow set to Feature Layer as the starting step.",hints:["Feature Layer","New Feature Layer","Content > My Content > New Item > Feature Layer"]},"developer-credentials":{description:"The Content page with New Item flow set to Developer Credentials as the starting step.",hints:["Developer Credentials","New developer credentials","Content > My Content > New Item > Developer Credentials"]}}}},Xp=$x(zx),Lx=Fn(Xp),jx=Nx(Xp),Dx=`
|
|
414
414
|
You decide whether the assistant response should include a navigation action to ArcGIS Portal.
|
|
415
415
|
|
|
416
416
|
Given the user question and assistant response:
|
|
@@ -439,7 +439,7 @@ User question:
|
|
|
439
439
|
|
|
440
440
|
Assistant response:
|
|
441
441
|
{response}
|
|
442
|
-
|
|
442
|
+
`,$p=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...Lx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),Fx=async(t,e)=>{await oe({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let o=qe(t.agentExecutionContext.messages).trim(),n=await br.fromTemplate(Dx).format({question:o,response:r}),s=(await la({modelTier:"fast"})).withStructuredOutput($p),a=$p.parse(await s.invoke(n));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Dn(o,"#");u&&(a.itemId=await Yp.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Dn(o,"$")??Dn(o,"#");u&&(a.groupId=await Qp.invoke({groupTitle:u},e)??"")}let i=Ux(a);return i?(await ma(i,e),{}):{}};function Ux({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":case"portal-gallery":case"portal-groups":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":return{destinationType:t};case"portal-org-security":return{destinationType:"portal-org",hash:"settings",queryParams:{tab:"security"}};case"portal-content-new-item":case"portal-content-new-item-feature-layer":case"portal-content-new-item-developer-credentials":return{queryParams:{newItem:qx[t]},destinationType:"portal-content"};case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":return{destinationType:"portal-content",hash:Bx[t]};case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":return{destinationType:"portal-groups",hash:Kx[t]};case"portal-org-security-custom-sign-in":case"portal-org-security-logins":case"portal-org-security-change-login-provider":case"portal-org-security-multifactor-auth":case"portal-org-security-multifactor-enforcement":case"portal-org-security-multifactor-designated-admins":return{destinationType:"portal-org",hash:"settings",queryParams:{tab:"security",subsection:Gx[t]}};case"portal-item":return e?{destinationType:t,itemId:e}:null;case"portal-group":return r?{destinationType:t,groupId:r}:null;case"none":return null;default:return en(t)}}var qx={"portal-content-new-item":"newItem","portal-content-new-item-feature-layer":"createLayer","portal-content-new-item-developer-credentials":"developerCredentials"},Bx={"portal-content-favorites":"favorites","portal-content-group":"group","portal-content-living-atlas":"living-atlas","portal-content-organization":"org"},Kx={"portal-groups-featured":"featured","portal-groups-my":"my","portal-groups-organization":"organization"},Gx={"portal-org-security-custom-sign-in":"customSignInSection","portal-org-security-logins":"loginsSection","portal-org-security-change-login-provider":"changeLoginProviderSection","portal-org-security-multifactor-auth":"multiFactorAuthSection","portal-org-security-multifactor-enforcement":"multifactorEnforcementSection","portal-org-security-multifactor-designated-admins":"multifactorDesignatedAdminsSection"},em=M.Root({...Qo()}),Vx=()=>new ce(em).addNode("answerDocQuestion",Rx).addNode("extractNavigationIntent",Fx).addEdge(ue,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",K),Wx=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
|
|
443
443
|
- answers general ArcGIS, Portal, Enterprise, and JavaScript SDK questions
|
|
444
444
|
- acts as a fallback when specialized agents are not applicable
|
|
445
445
|
`,Hx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:Wx,createGraph:Vx,workspace:em},Jx=()=>({latestGroupId:null,memory:{}}),fa=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:Jx()},tm=`
|
|
@@ -503,7 +503,7 @@ hasAnalyticsContext:
|
|
|
503
503
|
|
|
504
504
|
User message:
|
|
505
505
|
{userMessage}
|
|
506
|
-
`,eI=async(t,e)=>{await oe({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=qe(t.agentExecutionContext.messages),o=!!fa(t).latestGroupId,n=await br.fromTemplate(Xx).format({userMessage:r,hasAnalyticsContext:String(o)}),s=(await la({modelTier:"fast"})).withStructuredOutput(
|
|
506
|
+
`,eI=async(t,e)=>{await oe({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=qe(t.agentExecutionContext.messages),o=!!fa(t).latestGroupId,n=await br.fromTemplate(Xx).format({userMessage:r,hasAnalyticsContext:String(o)}),s=(await la({modelTier:"fast"})).withStructuredOutput(Np),a=Np.parse(await s.invoke(n)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let x=Dn(r,"$");x&&(i=await Qp.invoke({groupTitle:x},e)??"")}let{intent:u,question:l}=a,d=u==="summarize"&&!i,p=u==="followUp"&&!(l??"").trim(),f=u==="clarify"||d||p;return{groupSummaryIntent:f?"clarify":u,groupSummaryGroupId:i||null,groupSummaryQuestion:l||"",status:"success",outputMessage:f?"Please clarify with a group id or title":""}},Np=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),tI=async(t,e)=>{let r=fa(t),o=t.groupSummaryGroupId??r.latestGroupId;return await oe({text:"Preparing navigation...",agentName:"group-analytics"},e),await ma(o?{destinationType:"portal-group",groupId:o}:{destinationType:"portal-groups"},e),{status:"success"}};function rm({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var rI=720*60*60*1e3;function oI(t){let e=Gl(t);return{id:t.id??"",title:t.title??"",description:t.description??"",snippet:t.snippet??"",access:t.access??null,owner:t.owner??"",tags:t.tags??[],created:t.created?.getTime(),modified:t.modified?.getTime(),isInvitationOnly:t.isInvitationOnly,sourceSignals:{capabilities:Vl(t),membershipAccess:Wl(t),isOpenData:Hl(t),isDistributedCollaborationGroup:Jl(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function nI(t){let e={owner:t.owner??"",admins:[],users:[]};try{return await t.fetchMembers()}catch(r){return console.warn("Unable to fetch group members for analytics context",r),e}}function sI(t){return t.map(e=>({id:e.id??"",title:e.title??"Untitled",type:e.type??"Unknown",owner:e.owner??"",created:e.created?.getTime(),modified:e.modified?.getTime()}))}function aI(t,e){return t.filter(r=>r.modified?rm({timestamp:r.modified,now:e,windowMs:rI}):!1)}function iI(t){let e=new Map;for(let r of t)e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].sort((r,o)=>o[1]-r[1]||r[0].localeCompare(o[0])).slice(0,6).map(([r,o])=>({type:r,count:o}))}async function lI(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=sI(e.results),o=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:aI(r,o),topItemTypes:iI(r)}}async function uI(t,e){if(!e)return{error:{code:"missingGroupId",message:"Group id is required."}};try{let r=(await t.queryGroups({query:`id:${e}`,num:1})).results[0];if(!r)return{error:{code:"groupNotFound",message:`No group found for id: ${e}`}};let o=oI(r),n=await nI(r),s=await lI(r);return{result:{group:o,members:n,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var cI=`
|
|
507
507
|
You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
|
|
508
508
|
|
|
509
509
|
${tm}
|
|
@@ -616,7 +616,7 @@ Item context:
|
|
|
616
616
|
- summarizes item details, metadata, and context grounded in that item
|
|
617
617
|
- suggests follow-up prompts grounded in the same item
|
|
618
618
|
- use for item-specific requests, not for gallery browsing, featured content, or opening Map Viewer
|
|
619
|
-
`,kI={id:"portal-item-analytics",name:"Portal Item Analytics",description:CI,createGraph:SI,workspace:nm},EI={schemaVersion:"1.0",capabilities:[{id:"my-content",title:"My content",description:"Browse, discover, search, and filter ArcGIS content\u2014including maps, apps, datasets, and other items\u2014that you own or can access.",hints:["view my content","show my content","my content"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}},{id:"create-feature-layer",title:"Create feature layer",description:"Generate an editable feature layer by copying fields from templates or existing layers.",hints:["add a feature layer","make a feature layer","generate a feature layer"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}},{id:"create-folder",title:"Create folder",description:"Create a new folder in your ArcGIS content to organize your items.",hints:["create a folder","make a folder","set up a folder","new folder"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}}]},MI={schemaVersion:"1.0",capabilities:[{id:"my groups",title:"My groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that you own, belong to, or can access.",hints:["view my groups","show my groups","my groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups"}}},{id:"create-group",title:"Create group",description:"Create a new ArcGIS Portal group owned by the signed-in user.",hints:["create a group","make a group","set up a group","new group"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups"}}},{id:"featured-groups",title:"Featured groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that organization administrators choose to highlight in ArcGIS.",hints:["view featured groups","show featured groups","highlighted groups","top groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups",hash:"featured"}}},{id:"organization-groups",title:"Organization groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that are specific to your organization in ArcGIS.",hints:["view organization groups","show organization groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups",hash:"organization"}}}]},PI={schemaVersion:"1.0",capabilities:[{id:"org-config-mfa",title:"Multifactor Authentication (MFA)",description:"Configure organization-level multifactor authentication (MFA) settings. Administrators can enable MFA for ArcGIS logins, allow recovery codes for members, view MFA adoption status, enforce MFA requirements for all members, manage the MFA exemption list, and designate administrators who can troubleshoot MFA issues.",hints:["config MFA","set up MFA"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"organization",queryParams:{tab:"security"},hash:"settings"}}}]},OI={"contentRouteRegistry.ts":EI,"groupsRouteRegistry.ts":MI,"orgSettingsRouteRegistry.ts":PI};function Lp(t){let e=[],r=new Set;for(let[o,n]of Object.entries(t))for(let s of n.capabilities){if(r.has(s.id))throw new Error(`${o}: duplicate capability id "${s.id}" across registries`);r.add(s.id),e.push(s)}return e}var ua;function yr(t){return t?ua=Lp({customCapabilities:t}):ua||(ua=Lp(OI)),ua}var RI=/^(?:take me to|navigate to|go to|show me|open)\s+(?:the\s+)?/u;function pa(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim().replace(RI,"").trim()}var
|
|
619
|
+
`,kI={id:"portal-item-analytics",name:"Portal Item Analytics",description:CI,createGraph:SI,workspace:nm},EI={schemaVersion:"1.0",capabilities:[{id:"my-content",title:"My content",description:"Browse, discover, search, and filter ArcGIS content\u2014including maps, apps, datasets, and other items\u2014that you own or can access.",hints:["view my content","show my content","my content"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}},{id:"create-feature-layer",title:"Create feature layer",description:"Generate an editable feature layer by copying fields from templates or existing layers.",hints:["add a feature layer","make a feature layer","generate a feature layer"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}},{id:"create-folder",title:"Create folder",description:"Create a new folder in your ArcGIS content to organize your items.",hints:["create a folder","make a folder","set up a folder","new folder"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"content"}}}]},MI={schemaVersion:"1.0",capabilities:[{id:"my groups",title:"My groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that you own, belong to, or can access.",hints:["view my groups","show my groups","my groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups"}}},{id:"create-group",title:"Create group",description:"Create a new ArcGIS Portal group owned by the signed-in user.",hints:["create a group","make a group","set up a group","new group"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups"}}},{id:"featured-groups",title:"Featured groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that organization administrators choose to highlight in ArcGIS.",hints:["view featured groups","show featured groups","highlighted groups","top groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups",hash:"featured"}}},{id:"organization-groups",title:"Organization groups",description:"Browse, discover, search, and filter ArcGIS content collections\u2014including maps, apps, datasets, and other items\u2014that are specific to your organization in ArcGIS.",hints:["view organization groups","show organization groups"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"groups",hash:"organization"}}}]},PI={schemaVersion:"1.0",capabilities:[{id:"org-config-mfa",title:"Multifactor Authentication (MFA)",description:"Configure organization-level multifactor authentication (MFA) settings. Administrators can enable MFA for ArcGIS logins, allow recovery codes for members, view MFA adoption status, enforce MFA requirements for all members, manage the MFA exemption list, and designate administrators who can troubleshoot MFA issues.",hints:["config MFA","set up MFA"],platforms:["online","enterprise"],resolutions:{navigate:{routeKey:"organization",queryParams:{tab:"security"},hash:"settings"}}}]},OI={"contentRouteRegistry.ts":EI,"groupsRouteRegistry.ts":MI,"orgSettingsRouteRegistry.ts":PI};function Lp(t){let e=[],r=new Set;for(let[o,n]of Object.entries(t))for(let s of n.capabilities){if(r.has(s.id))throw new Error(`${o}: duplicate capability id "${s.id}" across registries`);r.add(s.id),e.push(s)}return e}var ua;function yr(t){return t?ua=Lp({customCapabilities:t}):ua||(ua=Lp(OI)),ua}var RI=/^(?:take me to|navigate to|go to|show me|open)\s+(?:the\s+)?/u;function pa(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim().replace(RI,"").trim()}var $I=c.object({capabilityIds:c.array(c.string()).default([]),confidence:c.number().min(0).max(1).default(0),reason:c.string().default("")}),jp=.8,NI=String.raw`You select Portal navigation capabilities for a user's request.
|
|
620
620
|
|
|
621
621
|
Select only capability IDs from the supplied candidates. Return an empty array when none fit.
|
|
622
622
|
A named surface is required: do not select a capability on another Portal surface.
|
|
@@ -626,7 +626,7 @@ User request:
|
|
|
626
626
|
{userRequest}
|
|
627
627
|
|
|
628
628
|
Candidates:
|
|
629
|
-
{candidates}`,zI=async(t,e)=>{if(t.outputMessage||t.targets.length===0)return{};let r=qe(t.agentExecutionContext.messages).trim(),o=LI(r,t);if(o.length===1)return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"exact-match",request:r,selectedCapabilityIds:o}),{chosenCapabilityIds:o};await oe({text:"Choosing a navigation destination...",agentName:"navigation"},e);let n=JSON.stringify(t.targets.map(({capability:s,keywordScore:a,semanticScore:i})=>({id:s.id,title:s.title,description:s.description,route:s.resolutions.navigate,keywordScore:a,semanticScore:i})));try{let s=await Re({promptText:$I,
|
|
629
|
+
{candidates}`,zI=async(t,e)=>{if(t.outputMessage||t.targets.length===0)return{};let r=qe(t.agentExecutionContext.messages).trim(),o=LI(r,t);if(o.length===1)return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"exact-match",request:r,selectedCapabilityIds:o}),{chosenCapabilityIds:o};await oe({text:"Choosing a navigation destination...",agentName:"navigation"},e);let n=JSON.stringify(t.targets.map(({capability:s,keywordScore:a,semanticScore:i})=>({id:s.id,title:s.title,description:s.description,route:s.resolutions.navigate,keywordScore:a,semanticScore:i})));try{let s=await Re({promptText:NI,schema:$I,modelTier:"fast",inputVariables:{candidates:n,userRequest:r}}),a=new Set(t.targets.map(({capability:u})=>u.id)),i=s.capabilityIds.filter(u=>a.has(u));return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{confidence:s.confidence,method:"structured-model",reason:s.reason,request:r,selectedCapabilityIds:i}),s.confidence<jp?{chosenCapabilityIds:[],status:"failed",summary:`Navigation selection confidence ${s.confidence} is below the required ${jp}; defer to the Portal Doc Assistant.`}:{chosenCapabilityIds:i}}catch{return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"structured-model-unavailable",request:r,selectedCapabilityIds:[]}),{chosenCapabilityIds:[]}}};function LI(t,e){let r=pa(t);return e.targets.filter(({capability:o})=>[o.title,...o.hints].some(n=>pa(n)===r)).map(({capability:o})=>o.id)}var sm=new Set(["1d","7d","14d","30d","3m","6m"]),jI=c.object({period:c.string(),startTime:c.string(),endTime:c.string()}),DI=String.raw`Extract temporal filters for an ArcGIS storage-credits query.
|
|
630
630
|
|
|
631
631
|
Return JSON only with these optional string fields:
|
|
632
632
|
- period
|