@arcgis/portal-components 5.2.0-next.97 → 5.2.0-next.99
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,16 +1,16 @@
|
|
|
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
|
|
2
|
+
import c from"./OHEUIODH.js";import b from"./AMBLICID.js";import{a as Wl,c as Hl,e as Jl,f as Zl,g as Ql}from"./3YCG5UCH.js";import a from"./F3ODJVJC.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as rn,b as bl,d as Bn}from"./2GBRZSEC.js";import{a as Al}from"./ACCEI7S4.js";import"./S7IRYX4A.js";import"./VJ4STLVD.js";import{K as en,L as tn,M as _l,S as wl,h as fl,j as Re,n as hl,w as gl,z as yl}from"./4PPXBKIJ.js";import{$ as Aa,Aa as jl,Ca as Dl,Cb as an,Da as es,Ea as ts,Fa as Fl,Ga as Ar,Gb as rs,Ha as xr,Hb as os,Ia as v,Ib as ce,J as Il,Ja as E,K as ge,Ka as Ta,L as Pt,La as Sa,M as vl,Ma as Ca,N as Tl,O as Gn,P as _a,Q as wa,R as Vn,S as nn,T as B,U as ba,V as F,W as at,Wa as M,X as it,Y as Wn,Z as Sl,_ as Cl,a as ue,aa as Hn,b as K,ba as kl,ca as El,da as sn,ea as Jn,fa as Ml,g as xl,ga as Pl,ha as Ol,ia as Zn,j as Be,ja as Rl,k as Mt,ka as Ot,la as xa,ma as Qn,na as $,oa as A,pa as Rt,pb as Ul,qa as lt,ra as Nl,s as on,sa as Yn,ta as $l,ua as zl,va as Xn,wa as Ia,xa as br,y as Kn,ya as va,za as Ll}from"./JCYCRSPL.js";import"./UZLQALHY.js";export default $arcgis.t(([u2,d2,Dd,Fd,wy,by,Oy,_2,b2,B5,ox,fp,Ho,hp,,wp,,Vy,Wy,qy,rp,{formatDateOnly:t_,convertDateFormatToIntlOptions:ta,formatTimeOnly:r_,formatDate:op},h_,g_,y_,I_,v_,{createRenderer:L_},{getSchemesByTag:j_,getSchemes:D_},{getBackgroundColorTheme:gp},{createAgeRenderer:F_,createContinuousRenderer:U_},{getSchemesByTag:Yi},{createContinuousRenderer:q_},{createRenderer:B_},{getSchemesByTag:K_},{createRenderer:G_},{getSchemesByTag:V_},{createRenderer:W_},{getSchemesByTag:H_},{createRenderer:J_},{getSchemesByTag:Z_},{createAgeRenderer:Q_,createContinuousRenderer:Y_},{createRenderer:X_},{getSchemesByTag:ew},tw,bp,{fetchKnowledgeGraph:yp,executeQueryStreaming:rw,executeSearchStreaming:ow},nw,{getBindParametersFromCypherQuery:sw},,,,,,,el,pA,mA,{addressToLocations:fA},hA,kA,GA,,,,,,,,,,,,,,,,,,,c3,p3,,,,,,,,,,,,,Ep,Mp,nx,,{a:Gl,b:Vl},{a:ql,b:Bl,c:Kl}])=>{var Ke=(t,e)=>e,ka=(t,e)=>({...t,...e}),Ea=(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
|
|
|
6
|
-
${r}`},
|
|
6
|
+
${r}`},Ma=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{},sharedResources:[]}),Nt=()=>({agentExecutionContext:M({reducer:ka,default:Ma}),outputMessage:M({reducer:Ea,default:()=>""}),summary:M({reducer:Ke,default:()=>""}),status:M({reducer:Ke}),sharedStatePatch:M({reducer:Ke}),sharedResourceAdditions:M({reducer:Ke})}),ns=()=>Nt();var c=v;async function Pa(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
|
|
7
7
|
|
|
8
8
|
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
9
9
|
|
|
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
|
|
13
|
+
`].join(" "));let o=await El(r),n=o?.getParentRunId();o!==void 0&&n!==void 0&&await o.handleCustomEvent?.(t,e,n)}var Z=async(t,e)=>{await Pa("trace_message",t,e)},fe=async(t,e)=>{await Pa("graph_ux_suggestion",t,e)};var wm={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"}},oT=Object.keys(wm);var za=Symbol.for("langgraph-zod");za in globalThis||(globalThis[za]=new WeakSet);function Xl(t){let e=globalThis[za];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(o){return os(r,{jsonSchemaExtra:o})},reducer(o,n){return os(r,{default:Qn(r),reducer:{schema:n,fn:o}})}}}}),e.add(t))}try{Xl(A.ZodType.prototype),Xl(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 eu=class extends Pl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let o=Qn(t);o!=null&&(r.default=o)}return super.add(t,...e)}},Im=new eu(rs);var zm=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Lm=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),jm=["approve","edit","reject"],Dm=A.enum(jm),Fm=A.object({allowedDecisions:A.array(Dm),description:A.union([A.string(),Lm]).optional(),argsSchema:A.record(A.any()).optional(),when:zm.optional()}),pk=A.object({interruptOn:A.record(A.union([A.boolean(),Fm])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var ls=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=>vl(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 Bm=`<role>
|
|
14
14
|
Context Extraction Assistant
|
|
15
15
|
</role>
|
|
16
16
|
|
|
@@ -36,23 +36,23 @@ Respond ONLY with the extracted context. Do not include any additional informati
|
|
|
36
36
|
<messages>
|
|
37
37
|
Messages to summarize:
|
|
38
38
|
{messages}
|
|
39
|
-
</messages>`;var
|
|
39
|
+
</messages>`;var Km=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),Ua=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"}),pu=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"}),Nk=A.object({model:A.custom(),trigger:A.union([Ua,A.array(Ua)]).optional(),keep:pu.optional(),tokenCounter:Km.optional(),summaryPrompt:A.string().default(Bm),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var Vk=A.object({model:A.string().or(A.instanceof($l)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var Xk=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var nE=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Gm=["continue","error","end"],Vm="continue";var Wm=A.enum(Gm).default(Vm);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Wm});var hE=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Hm=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Jm=A.object({content:A.string().describe("Content of the todo item"),status:Hm}),IE=A.object({todos:A.array(Jm).default([])});var kE=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),EE=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var UE=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(ls);var JE=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(ls);var gM=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var bM=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function ln(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 an(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var ln=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{},W=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:ln(r)});let s=r?.error;return e===400?new xr(e,s,o,n):e===401?new Ir(e,s,o,n):e===403?new vr(e,s,o,n):e===404?new Tr(e,s,o,n):e===409?new Sr(e,s,o,n):e===422?new Cr(e,s,o,n):e===429?new kr(e,s,o,n):e>=500?new Er(e,s,o,n):new t(e,s,o,n)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends W{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."})}},xr=class extends W{},Ir=class extends W{},vr=class extends W{},Tr=class extends W{},Sr=class extends W{},Cr=class extends W{},kr=class extends W{},Er=class extends W{},Mr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Pr=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 W{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}},un=class extends C{constructor(e,r,o){super(e),this.provider=r,this.cause=o}};var Pf=/^[a-z][a-z0-9+.-]*:/i,mu=t=>Pf.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 cn(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 Of(){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 Rf=()=>{let t=Of();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=Nf();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 Nf(){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=Rf());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,re={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 zf(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 Y=I.get(t);if(k+=1,typeof Y<"u"){if(Y===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(Y){return Y instanceof Date?f?.(Y):Y})),h===null){if(s)return u&&!b?u(e,re.encoder,y,"key",x):e;h=""}if(zf(h)||Su(h)){if(u){let Y=b?e:u(e,re.encoder,y,"key",x);return[w?.(Y)+"="+w?.(u(h,re.encoder,y,"value",x))]}return[w?.(e)+"="+w?.(String(h))]}let q=[];if(typeof h>"u")return q;let V;if(r==="comma"&&de(h))b&&u&&(h=Ya(h,u)),V=[{value:h.length>0?h.join(",")||null:void 0}];else if(de(l))V=l;else{let Y=Object.keys(h);V=d?Y.sort(d):Y}let J=i?String(e).replace(/\./g,"%2E"):String(e),le=o&&de(h)&&h.length===1?J+"[]":J;if(n&&de(h)&&h.length===0)return le+"[]";for(let Y=0;Y<V.length;++Y){let te=V[Y],cl=typeof te=="object"&&typeof te.value<"u"?te.value:h[te];if(a&&cl===null)continue;let ha=p&&i?te.replace(/\./g,"%2E"):te,hm=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,hm,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 Lf(t=re){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||re.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=re.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=re.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:re.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:re.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:re.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:re.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?re.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:re.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:re.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:re.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:re.encodeValuesOnly,filter:n,format:r,formatter:o,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:re.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:re.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:re.strictNullHandling}}function Pu(t,e={}){let r=t,o=Lf(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 Or(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"?Or(e):e;P(this,ye,$u([_(this,ye,"f"),r]),"f");let o=[],n;for(;(n=Df(_(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*
|
|
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]=Bf(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function Bf(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 Q(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 Q(t).debug(`[${o}] response parsed`,Ge({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 mn,zt=class t extends Promise{constructor(e,r,o=ms){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=o,mn.set(this,void 0),P(this,mn,e,"f")}_thenUnwrap(e){return new t(_(this,mn,"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,mn,"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)}};mn=new WeakMap;var fs,Rr=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}},fn=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 Rr{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 Rr{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 Rr{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}},ee=class extends Rr{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 Gf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Vf="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:Vf,subject_token:e,subject_token_type:Gf[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):W.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 hn(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 Wf(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 Wf(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,Hf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||gs(t)||Fu(t)),ni=t=>{if(Hf(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()],hn(r)));else if(gs(r))t.append(e,Nr([await new Response(us(r)).blob()],hn(r)));else if(Fu(r))t.append(e,r,hn(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",Jf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Uu(t),Zf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function gn(t,e,r){if(ai(),t=await t,Jf(t))return t instanceof File?t:Nr([await t.arrayBuffer()],t.name);if(Zf(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=hn(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}`:""}${Qf(t)}`)}return e}function Qf(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)),Xf=(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 Ka=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Ka=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 un(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var cn=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{},W=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:cn(r)});let s=r?.error;return e===400?new vr(e,s,o,n):e===401?new Tr(e,s,o,n):e===403?new Sr(e,s,o,n):e===404?new Cr(e,s,o,n):e===409?new kr(e,s,o,n):e===422?new Er(e,s,o,n):e===429?new Mr(e,s,o,n):e>=500?new Pr(e,s,o,n):new t(e,s,o,n)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends W{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."})}},vr=class extends W{},Tr=class extends W{},Sr=class extends W{},Cr=class extends W{},kr=class extends W{},Er=class extends W{},Mr=class extends W{},Pr=class extends W{},Or=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Rr=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)}},zt=class extends W{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}},dn=class extends C{constructor(e,r,o){super(e),this.provider=r,this.cause=o}};var Rf=/^[a-z][a-z0-9+.-]*:/i,hu=t=>Rf.test(t),de=t=>(de=Array.isArray,de(t)),Ga=de;function us(t){return typeof t!="object"?{}:t??{}}function Va(t){if(!t)return!0;for(let e in t)return!1;return!0}function gu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function pn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var yu=(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 _u=t=>{try{return JSON.parse(t)}catch{return}};var ze=t=>new Promise(e=>setTimeout(e,t));var dt="6.45.0";var xu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Nf(){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 $f=()=>{let t=Nf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":bu(Deno.build.os),"X-Stainless-Arch":wu(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":bu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":wu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=zf();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 zf(){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 wu=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",bu=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"),Au,Iu=()=>Au??(Au=$f());function cs(){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 Wa(...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 ds(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Wa({start(){},async pull(r){let{done:o,value:n}=await e.next();o?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function Ha(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 Ja(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 Tu=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Za="RFC3986",Qa=t=>String(t),Ya={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Qa},Su="RFC1738";var ps=(t,e)=>(ps=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ps(t,e)),Le=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Xa=1024,Cu=(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+=Xa){let u=s.length>=Xa?s.slice(i,i+Xa):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===Su&&(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 ku(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ei(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 Mu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Pu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},Eu,re={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Cu,encodeValuesOnly:!1,format:Za,formatter:Qa,indices:!1,serializeDate(t){return(Eu??(Eu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function jf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var ti={};function Ou(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(ti))!==void 0&&!U;){let Y=I.get(t);if(k+=1,typeof Y<"u"){if(Y===k)throw new RangeError("Cyclic object value");U=!0}typeof I.get(ti)>"u"&&(k=0)}if(typeof l=="function"?h=l(e,h):h instanceof Date?h=f?.(h):r==="comma"&&de(h)&&(h=ei(h,function(Y){return Y instanceof Date?f?.(Y):Y})),h===null){if(s)return u&&!b?u(e,re.encoder,y,"key",x):e;h=""}if(jf(h)||ku(h)){if(u){let Y=b?e:u(e,re.encoder,y,"key",x);return[w?.(Y)+"="+w?.(u(h,re.encoder,y,"value",x))]}return[w?.(e)+"="+w?.(String(h))]}let q=[];if(typeof h>"u")return q;let V;if(r==="comma"&&de(h))b&&u&&(h=ei(h,u)),V=[{value:h.length>0?h.join(",")||null:void 0}];else if(de(l))V=l;else{let Y=Object.keys(h);V=d?Y.sort(d):Y}let J=i?String(e).replace(/\./g,"%2E"):String(e),le=o&&de(h)&&h.length===1?J+"[]":J;if(n&&de(h)&&h.length===0)return le+"[]";for(let Y=0;Y<V.length;++Y){let te=V[Y],pl=typeof te=="object"&&typeof te.value<"u"?te.value:h[te];if(a&&pl===null)continue;let ya=p&&i?te.replace(/\./g,"%2E"):te,ym=de(h)?typeof r=="function"?r(le,ya):le:le+(p?"."+ya:"["+ya+"]");S.set(t,k);let ml=new WeakMap;ml.set(ti,S),Pu(q,Ou(pl,ym,r,o,n,s,a,i,r==="comma"&&b&&de(h)?null:u,l,d,p,f,x,w,b,y,ml))}return q}function Df(t=re){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||re.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=Za;if(typeof t.format<"u"){if(!ps(Ya,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let o=Ya[r],n=re.filter;(typeof t.filter=="function"||de(t.filter))&&(n=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Mu?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=re.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:re.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:re.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:re.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:re.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?re.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:re.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:re.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:re.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:re.encodeValuesOnly,filter:n,format:r,formatter:o,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:re.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:re.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:re.strictNullHandling}}function Ru(t,e={}){let r=t,o=Df(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=Mu[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||Pu(a,Ou(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 Nu(t){return Ru(t,{arrayFormat:"brackets"})}function Lu(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 $u;function Nr(t){let e;return($u??(e=new globalThis.TextEncoder,$u=e.encode.bind(e)))(t)}var zu;function ri(t){let e;return(zu??(e=new globalThis.TextDecoder,zu=e.decode.bind(e)))(t)}var ye,_e,Lt=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"?Nr(e):e;P(this,ye,Lu([_(this,ye,"f"),r]),"f");let o=[],n;for(;(n=Uf(_(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(ri(_(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=ri(_(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;Lt.NEWLINE_CHARS=new Set([`
|
|
44
|
+
`,"\r"]);Lt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Uf(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 ju(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 fs={off:0,error:200,warn:300,info:400,debug:500},oi=(t,e,r)=>{if(t){if(gu(fs,t))return t;Q(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(fs))}`)}};function mn(){}function ms(t,e,r){return!e||fs[t]>fs[r]?mn:e[t].bind(e)}var qf={error:mn,warn:mn,info:mn,debug:mn},Du=new WeakMap;function Q(t){let e=t.logger,r=t.logLevel??"off";if(!e)return qf;let o=Du.get(e);if(o&&o[0]===r)return o[1];let n={error:ms("error",e,r),warn:ms("warn",e,r),info:ms("info",e,r),debug:ms("debug",e,r)};return Du.set(e,[r,n]),n}var Ge=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 fn,je=class t{constructor(e,r,o){this.iterator=e,fn.set(this,void 0),this.controller=r,P(this,fn,o,"f")}static fromSSEResponse(e,r,o,n){let s=!1,a=o?Q(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 Bf(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 W(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 W(void 0,d.error,d.message,void 0);yield{event:l.event,data:d}}}u=!0}catch(l){if(un(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 Lt,u=Ha(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(un(u))return;throw u}finally{i||r.abort()}}return new t(a,r,o)}[(fn=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,fn,"f")),new t(()=>n(r),this.controller,_(this,fn,"f"))]}toReadableStream(){let e=this,r;return Wa({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=Nr(JSON.stringify(n)+`
|
|
45
|
+
`);o.enqueue(a)}catch(n){o.error(n)}},async cancel(){await r.return?.()}})}};async function*Bf(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 ni,o=new Lt,n=Ha(t.body);for await(let s of Kf(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*Kf(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"?Nr(r):r,n=new Uint8Array(e.length+o.length);n.set(e),n.set(o,e.length),e=n;let s;for(;(s=ju(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ni=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]=Gf(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function Gf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function hs(t,e){let{response:r,requestLogID:o,retryOfRequestLogID:n,startTime:s}=e,a=await(async()=>{if(e.options.stream)return Q(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 si(f,r)}return await r.text()})();return Q(t).debug(`[${o}] response parsed`,Ge({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function si(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 hn,jt=class t extends Promise{constructor(e,r,o=hs){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=o,hn.set(this,void 0),P(this,hn,e,"f")}_thenUnwrap(e){return new t(_(this,hn,"f"),this.responsePromise,async(r,o)=>si(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,hn,"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)}};hn=new WeakMap;var gs,$r=class{constructor(e,r,o,n){gs.set(this,void 0),P(this,gs,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,gs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},gn=class extends jt{constructor(e,r,o){super(e,r,async(n,s)=>new o(n,s.response,await hs(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}},N=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:{...us(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:{...us(this.options.query),after:e}}:null}},ee=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:{...us(this.options.query),after:e}}:null}};var Wf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Hf="urn:ietf:params:oauth:grant-type:token-exchange",ys=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??cs()}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:Hf,subject_token:e,subject_token_type:Wf[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 zt(o.status,l,o.headers):W.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 li=()=>{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 zr(t,e,r){return li(),new File(t,e??"unknown_file",r)}function yn(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 _s=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pt=async(t,e)=>ai(t.body)?{...t,body:await Uu(t.body,e)}:t,me=async(t,e)=>({...t,body:await Uu(t.body,e)}),Fu=new WeakMap;function Jf(t){let e=typeof t=="function"?t:t.fetch,r=Fu.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 Fu.set(e,o),o}var Uu=async(t,e)=>{if(!await Jf(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])=>ii(r,o,n))),r},qu=t=>t instanceof Blob&&"name"in t,Zf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||_s(t)||qu(t)),ai=t=>{if(Zf(t))return!0;if(Array.isArray(t))return t.some(ai);if(t&&typeof t=="object"){for(let e in t)if(ai(t[e]))return!0}return!1},ii=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,zr([await r.blob()],yn(r)));else if(_s(r))t.append(e,zr([await new Response(ds(r)).blob()],yn(r)));else if(qu(r))t.append(e,r,yn(r));else if(Array.isArray(r))await Promise.all(r.map(o=>ii(t,e+"[]",o)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([o,n])=>ii(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 Bu=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",Qf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Bu(t),Yf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function _n(t,e,r){if(li(),t=await t,Qf(t))return t instanceof File?t:zr([await t.arrayBuffer()],t.name);if(Yf(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),zr(await ui(n),e,r)}let o=await ui(t);if(e||(e=yn(t)),!r?.type){let n=o.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof n=="string"&&(r={...r,type:n})}return zr(o,e,r)}async function ui(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Bu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(_s(t))for await(let r of t)e.push(...await ui(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Xf(t)}`)}return e}function Xf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function Gu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ku=Object.freeze(Object.create(null)),th=(t=Gu)=>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??Ku)??Ku)?.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=Xf(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 yn(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 _n(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}}))}:wn(t,e)}function wn(t,e){let r=t.choices.map(o=>{if(o.finish_reason==="length")throw new Mr;if(o.finish_reason==="content_filter")throw new Pr;return Hu(o.message.tool_calls),{...o,message:{...o.message,...o.message.tool_calls?{tool_calls:o.message.tool_calls?.map(n=>rh(e,n))??void 0}:void 0,parsed:o.message.content&&!o.message.refusal?th(e,o.message.content):null}}});return{...t,choices:r}}function th(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 rh(t,e){let r=t.tools?.find(o=>yn(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=>yn(o)&&o.function?.name===e.function.name);return yn(r)&&(jt(r)||r?.function.strict||!1)}function li(t){return _n(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 $r=t=>t?.role==="assistant",ui=t=>t?.role==="tool";var ys,_s,ws,bn,An,bs,xn,Ve,As,In,xs,Is,zr,Zu,Qu,mt=class{constructor(){ys.add(this),this.controller=new AbortController,_s.set(this,void 0),ws.set(this,()=>{}),bn.set(this,()=>{}),An.set(this,void 0),bs.set(this,()=>{}),xn.set(this,()=>{}),Ve.set(this,{}),As.set(this,[]),In.set(this,!1),xs.set(this,!1),Is.set(this,!1),zr.set(this,!1),P(this,_s,new Promise((e,r)=>{P(this,ws,e,"f"),P(this,bn,r,"f")}),"f"),P(this,An,new Promise((e,r)=>{P(this,bs,e,"f"),P(this,xn,r,"f")}),"f"),_(this,_s,"f").catch(()=>{}),_(this,An,"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,In,"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,Ve,"f")[e]||(_(this,Ve,"f")[e]=[])).push({listener:r}),this}off(e,r){let o=_(this,Ve,"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,Ve,"f")[e]||(_(this,Ve,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,o)=>{P(this,zr,!0,"f"),e!=="error"&&this.once("error",o),this.once(e,r)})}async done(){P(this,zr,!0,"f"),await _(this,An,"f")}_emit(e,...r){if(_(this,In,"f"))return;e==="end"&&(_(this,ys,"m",Zu).call(this),P(this,In,!0,"f"),_(this,bs,"f").call(this));let o=_(this,Ve,"f")[e];if(o&&(_(this,Ve,"f")[e]=o.filter(n=>!n.once),o.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!_(this,zr,"f")&&!o?.length&&Promise.reject(n),_(this,bn,"f").call(this,n),_(this,xn,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!_(this,zr,"f")&&!o?.length&&Promise.reject(n),_(this,bn,"f").call(this,n),_(this,xn,"f").call(this,n),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,ws=new WeakMap,bn=new WeakMap,An=new WeakMap,bs=new WeakMap,xn=new WeakMap,Ve=new WeakMap,As=new WeakMap,In=new WeakMap,xs=new WeakMap,Is=new WeakMap,zr=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 H),e instanceof H)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,oh=10,Lr=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($r(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(wn(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=oh,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 V=`Invalid tool_call: ${JSON.stringify(h)}. Available options are: ${Object.keys(x).map(J=>JSON.stringify(J)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:S,content:V},functionCalled:!1}}if(l&&l!==h){let V=`Invalid tool_call: ${JSON.stringify(h)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:S,content:V},functionCalled:!1}}let U;if(Yu(k)){let V;try{V=await k.parse(I)}catch(J){let le=J instanceof Error?J.message:String(J);return{message:{role:s,tool_call_id:S,content:le},functionCalled:!1}}U=await k.function(V,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($r(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($r(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 vn=class t extends Lr{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),$r(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 nh(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 sh(t.trim(),e)}var sh=(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
|
-
\r `.includes(t[o]);)o++};return a()},
|
|
52
|
-
${
|
|
53
|
-
${
|
|
54
|
-
${
|
|
55
|
-
${Cs(t)}`);return{...J,id:V,type:q,function:{...te,name:Y,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 Tn=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 He=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=>wn(o,e))}runTools(e,r){return e.stream?Tn.runTools(this._client,e,r):vn.runTools(this._client,e,r)}stream(e,r){return Dt.createChatCompletion(this._client,e,r)}};He.Messages=Lt;var ht=class extends g{constructor(){super(...arguments),this.completions=new He(this._client)}};ht.Completions=He;var Dr=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 Fr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=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 qr=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 Br=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 Kr=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",ee,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Gr=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 Vr=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 Wr=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`,ee,{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 Hr=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`,ee,{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 Hr(this._client),this.roles=new Wr(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",ee,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};gt.Users=Hr;gt.Roles=Wr;var Jr=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 Zr=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 Qr=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 Yr=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 Xr=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 eo=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 to=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`,ee,{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 ro=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 oo=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 no=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`,ee,{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 no(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`,ee,{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=no;var so=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`,ee,{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 so(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=so;var se=class extends g{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new ro(this._client),this.apiKeys=new Jr(this._client),this.rateLimits=new eo(this._client),this.modelPermissions=new Xr(this._client),this.hostedToolPermissions=new Yr(this._client),this.groups=new Ft(this._client),this.roles=new to(this._client),this.dataRetention=new Qr(this._client),this.spendAlerts=new oo(this._client),this.certificates=new Zr(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=ro;se.APIKeys=Jr;se.RateLimits=eo;se.ModelPermissions=Xr;se.HostedToolPermissions=Yr;se.Groups=Ft;se.Roles=to;se.DataRetention=Qr;se.SpendAlerts=oo;se.Certificates=Zr;var ao=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`,ee,{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 ao(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=ao;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new Fr(this._client),this.adminAPIKeys=new Dr(this._client),this.usage=new Vr(this._client),this.invites=new Br(this._client),this.users=new qt(this._client),this.groups=new gt(this._client),this.roles=new Kr(this._client),this.dataRetention=new qr(this._client),this.spendAlerts=new Gr(this._client),this.certificates=new Ur(this._client),this.projects=new se(this._client)}};ae.AuditLogs=Fr;ae.AdminAPIKeys=Dr;ae.Usage=Vr;ae.Invites=Br;ae.Users=qt;ae.Groups=gt;ae.Roles=Kr;ae.DataRetention=qr;ae.SpendAlerts=Gr;ae.Certificates=Ur;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*zh(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 zh(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 io=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 lo=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 uo=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 lo(this._client),this.translations=new uo(this._client),this.speech=new io(this._client)}};De.Transcriptions=lo;De.Translations=uo;De.Speech=io;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 co=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 po=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 mo=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 po(this._client),this.transcriptionSessions=new mo(this._client)}};_t.Sessions=po;_t.TranscriptionSessions=mo;var fo=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 ho=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 fo(this._client),this.threads=new ho(this._client)}};wt.Sessions=fo;wt.Threads=ho;var go=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 yo=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 ve=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,Te,Vt,_o,Kt,Ps,we,Es,Ms,kn,Sn,Cn,nc,sc,ac,ic,lc,uc,cc,Je=class extends mt{constructor(){super(...arguments),ie.add(this),xi.set(this,[]),Fe.set(this,{}),ks.set(this,{}),Te.set(this,void 0),Vt.set(this,void 0),_o.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),kn.set(this,void 0)}[(xi=new WeakMap,Fe=new WeakMap,ks=new WeakMap,Te=new WeakMap,Vt=new WeakMap,_o=new WeakMap,Kt=new WeakMap,Ps=new WeakMap,we=new WeakMap,Es=new WeakMap,Ms=new WeakMap,kn=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",Sn).call(this,n);if(o.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",Cn).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",Sn).call(this,i);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",Cn).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,Te,"f")}currentRunStepSnapshot(){return _(this,kn,"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",Sn).call(this,a);if(s.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",Cn).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",Sn).call(this,i);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",Cn).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(cn(s)&&cn(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(!cn(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=Je,Sn=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:}},Cn=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,Te,"f"));P(this,Te,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,_o,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Te,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Te,"f"));break}P(this,_o,n.index,"f")}P(this,Kt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,_o,"f")!==void 0){let n=e.data.content[_(this,_o,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,_(this,Te,"f"));break;case"text":this._emit("textDone",n.text,_(this,Te,"f"));break}}_(this,Te,"f")&&this._emit("messageDone",e.data),P(this,Te,void 0,"f")}},sc=function(e){let r=_(this,ie,"m",ic).call(this,e);switch(P(this,kn,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,kn,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 yo(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 Je.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 Je.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 Je.createToolAssistantStream(e,this._client.beta.threads.runs,r,o)}};Wt.Steps=yo;var bt=class extends g{constructor(){super(...arguments),this.runs=new Wt(this._client),this.messages=new go(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 Je.createThreadAssistantStream(e,this._client.beta.threads,r)}};bt.Runs=Wt;bt.Messages=go;var Se=class extends g{constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new wt(this._client),this.assistants=new co(this._client),this.threads=new bt(this._client)}};Se.Realtime=_t;Se.ChatKit=wt;Se.Assistants=co;Se.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 wo=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 wo(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=wo;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 bo=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 bo(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=bo;var Zt=class extends g{create(e,r){let o=!!e.encoding_format,n=o?e.encoding_format:"base64";o&&Q(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:(Q(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 Ao=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 Ao(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=Ao;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 xo=class extends g{};var Io=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 Io(this._client)}};Xt.Graders=Io;var vo=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 vo(this._client)}};er.Permissions=vo;var To=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 To(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=To;var Ce=class extends g{constructor(){super(...arguments),this.methods=new xo(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};Ce.Methods=xo;Ce.Jobs=tr;Ce.Checkpoints=er;Ce.Alpha=Xt;var So=class extends g{};var vt=class extends g{constructor(){super(...arguments),this.graderModels=new So(this._client)}};vt.GraderModels=So;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 Co=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 ko=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Ze=class extends g{constructor(){super(...arguments),this.clientSecrets=new ko(this._client),this.calls=new Co(this._client)}};Ze.ClientSecrets=ko;Ze.Calls=Co;function dc(t,e){if(!e||!mg(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?gg(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?pg(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 pg(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function mg(t){return!!_n(t.text?.format)}function fg(t){return t?.$brand==="auto-parseable-tool"}function hg(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function gg(t,e){let r=hg(t.tools??[],e.name);return{...e,...e,parsed_arguments:fg(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:yg(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 yg(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var En,Os,sr,Rs,hc,gc,yc,Ns=class t extends mt{constructor(e){super(),En.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,En,"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,En,"m",gc).call(this,a,s);if(n.controller.signal?.aborted)throw new H;return _(this,En,"m",yc).call(this)}[(Os=new WeakMap,sr=new WeakMap,Rs=new WeakMap,En=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=_g(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 _g(t,e){return dc(t,e)}var Eo=class extends g{list(e,r={},o){return this._client.getAPIList(m`/responses/${e}/input_items`,N,{query:r,...o,__security:{bearerAuth:!0}})}};var Mo=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 Eo(this._client),this.inputTokens=new Mo(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=Eo;Ue.InputTokens=Mo;var Po=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 Oo=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 Oo(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=Oo;var Qe=class extends g{constructor(){super(...arguments),this.content=new Po(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}})}};Qe.Content=Po;Qe.Versions=ar;var Ro=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 Ro(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=Ro;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`,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 $o=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 Ye=class extends g{constructor(){super(...arguments),this.files=new $o(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",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}})}};Ye.Files=$o;Ye.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 zo,wc,$s,lr=class extends g{constructor(){super(...arguments),zo.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,zo,"m",wc).call(this,o);let s=T([r]).values,a=_(this,zo,"m",$s).call(this,s,"webhook-signature"),i=_(this,zo,"m",$s).call(this,s,"webhook-timestamp"),u=_(this,zo,"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")}};zo=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,Mn,Sc,Cg="workload-identity-auth",O=class{constructor(e={}){vi.add(this),Mn.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 Ce(this),this.graders=new vt(this),this.vectorStores=new Ye(this),this.webhooks=new lr(this),this.beta=new Se(this),this.batches=new Bt(this),this.uploads=new Tt(this),this.admin=new yt(this),this.responses=new Ue(this),this.realtime=new Ze(this),this.conversations=new xt(this),this.evals=new It(this),this.containers=new At(this),this.skills=new Qe(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:ve("OPENAI_BASE_URL"),apiKey:n=r?null:ve("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:ve("OPENAI_ADMIN_KEY")??null,organization:a=r?null:ve("OPENAI_ORG_ID")??null,project:i=r?null:ve("OPENAI_PROJECT_ID")??null,webhookSecret:u=ve("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.
|
|
50
|
+
${p}`)}return a},m=th(Gu);var Dt=class extends g{list(e,r={},o){return this._client.getAPIList(m`/chat/completions/${e}/messages`,N,{query:r,...o,__security:{bearerAuth:!0}})}};function wn(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Wu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function bn(t){return t?.$brand==="auto-parseable-response-format"}function Ft(t){return t?.$brand==="auto-parseable-tool"}function Hu(t,e){return!e||!ci(e)?{...t,choices:t.choices.map(r=>(Zu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:An(t,e)}function An(t,e){let r=t.choices.map(o=>{if(o.finish_reason==="length")throw new Or;if(o.finish_reason==="content_filter")throw new Rr;return Zu(o.message.tool_calls),{...o,message:{...o.message,...o.message.tool_calls?{tool_calls:o.message.tool_calls?.map(n=>nh(e,n))??void 0}:void 0,parsed:o.message.content&&!o.message.refusal?oh(e,o.message.content):null}}});return{...t,choices:r}}function oh(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 nh(t,e){let r=t.tools?.find(o=>wn(o)&&o.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ft(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Ju(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(o=>wn(o)&&o.function?.name===e.function.name);return wn(r)&&(Ft(r)||r?.function.strict||!1)}function ci(t){return bn(t.response_format)?!0:t.tools?.some(e=>Ft(e)||e.type==="function"&&e.function.strict===!0)??!1}function Zu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Qu(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 Lr=t=>t?.role==="assistant",di=t=>t?.role==="tool";var ws,bs,As,xn,In,xs,vn,Ve,Is,Tn,vs,Ts,jr,Yu,Xu,mt=class{constructor(){ws.add(this),this.controller=new AbortController,bs.set(this,void 0),As.set(this,()=>{}),xn.set(this,()=>{}),In.set(this,void 0),xs.set(this,()=>{}),vn.set(this,()=>{}),Ve.set(this,{}),Is.set(this,[]),Tn.set(this,!1),vs.set(this,!1),Ts.set(this,!1),jr.set(this,!1),P(this,bs,new Promise((e,r)=>{P(this,As,e,"f"),P(this,xn,r,"f")}),"f"),P(this,In,new Promise((e,r)=>{P(this,xs,e,"f"),P(this,vn,r,"f")}),"f"),_(this,bs,"f").catch(()=>{}),_(this,In,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,ws,"m",Xu).bind(this))},0)}_connected(){this.ended||(_(this,As,"f").call(this),this._emit("connect"))}get ended(){return _(this,Tn,"f")}get errored(){return _(this,vs,"f")}get aborted(){return _(this,Ts,"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,Is,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ve,"f")[e]||(_(this,Ve,"f")[e]=[])).push({listener:r}),this}off(e,r){let o=_(this,Ve,"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,Ve,"f")[e]||(_(this,Ve,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,o)=>{P(this,jr,!0,"f"),e!=="error"&&this.once("error",o),this.once(e,r)})}async done(){P(this,jr,!0,"f"),await _(this,In,"f")}_emit(e,...r){if(_(this,Tn,"f"))return;e==="end"&&(_(this,ws,"m",Yu).call(this),P(this,Tn,!0,"f"),_(this,xs,"f").call(this));let o=_(this,Ve,"f")[e];if(o&&(_(this,Ve,"f")[e]=o.filter(n=>!n.once),o.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!_(this,jr,"f")&&!o?.length&&Promise.reject(n),_(this,xn,"f").call(this,n),_(this,vn,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!_(this,jr,"f")&&!o?.length&&Promise.reject(n),_(this,xn,"f").call(this,n),_(this,vn,"f").call(this,n),this._emit("end")}}_emitFinal(){}};bs=new WeakMap,As=new WeakMap,xn=new WeakMap,In=new WeakMap,xs=new WeakMap,vn=new WeakMap,Ve=new WeakMap,Is=new WeakMap,Tn=new WeakMap,vs=new WeakMap,Ts=new WeakMap,jr=new WeakMap,ws=new WeakSet,Yu=function(){for(let{signal:e,listener:r}of _(this,Is,"f").splice(0))e.removeEventListener("abort",r)},Xu=function(e){if(P(this,vs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new H),e instanceof H)return P(this,Ts,!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 ec(t){return typeof t.parse=="function"}var he,pi,Ss,mi,fi,hi,tc,rc,sh=10,Dr=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),di(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Lr(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",pi).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",Ss).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",mi).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",fi).call(this)}async totalUsage(){return await this.done(),_(this,he,"m",hi).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",Ss).call(this);r&&this._emit("finalMessage",r);let o=_(this,he,"m",pi).call(this);o&&this._emit("finalContent",o);let n=_(this,he,"m",mi).call(this);n&&this._emit("finalFunctionToolCall",n);let s=_(this,he,"m",fi).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,he,"m",hi).call(this))}async _createChatCompletion(e,r,o){this._listenForAbort(o?.signal),_(this,he,"m",tc).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...o,signal:this.controller.signal});return this._connected(),this._addChatCompletion(An(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=sh,afterCompletion:p}=n||{},f=r.tools.map(y=>{if(Ft(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 V=`Invalid tool_call: ${JSON.stringify(h)}. Available options are: ${Object.keys(x).map(J=>JSON.stringify(J)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:S,content:V},functionCalled:!1}}if(l&&l!==h){let V=`Invalid tool_call: ${JSON.stringify(h)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:S,content:V},functionCalled:!1}}let U;if(ec(k)){let V;try{V=await k.parse(I)}catch(J){let le=J instanceof Error?J.message:String(J);return{message:{role:s,tool_call_id:S,content:le},functionCalled:!1}}U=await k.function(V,o)}else U=await k.function(I,o);let q=_(this,he,"m",rc).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,pi=function(){return _(this,he,"m",Ss).call(this).content??null},Ss=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Lr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},mi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Lr(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}}},fi=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(di(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}},hi=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},tc=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.")},rc=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Sn=class t extends Dr{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),Lr(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},gi=class extends Error{},yi=class extends Error{};function ah(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 ih(t.trim(),e)}var ih=(t,e)=>{let r=t.length,o=0,n=f=>{throw new gi(`${f} at position ${o}`)},s=f=>{throw new yi(`${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
|
+
\r `.includes(t[o]);)o++};return a()},_i=t=>ah(t,ne.ALL^ne.NUM);var oe,We,Fr,ft,wi,Cs,bi,Ai,xi,ks,Ii,oc,Ut=class t extends Dr{constructor(e){super(),oe.add(this),We.set(this,void 0),Fr.set(this,void 0),ft.set(this,void 0),P(this,We,e,"f"),P(this,Fr,[],"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,oe,"m",wi).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,oe,"m",bi).call(this,s);if(n.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,oe,"m",ks).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,oe,"m",wi).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,oe,"m",ks).call(this)),_(this,oe,"m",bi).call(this,s),n=s.id;if(o.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,oe,"m",ks).call(this))}[(We=new WeakMap,Fr=new WeakMap,ft=new WeakMap,oe=new WeakSet,wi=function(){this.ended||P(this,ft,void 0,"f")},Cs=function(r){let o=_(this,Fr,"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,Fr,"f")[r.index]=o,o)},bi=function(r){if(this.ended)return;let o=_(this,oe,"m",oc).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,oe,"m",Cs).call(this,s);s.finish_reason&&(_(this,oe,"m",xi).call(this,s),a.current_tool_call_index!=null&&_(this,oe,"m",Ai).call(this,s,a.current_tool_call_index));for(let i of n.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(_(this,oe,"m",xi).call(this,s),a.current_tool_call_index!=null&&_(this,oe,"m",Ai).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))}}},Ai=function(r,o){if(_(this,oe,"m",Cs).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,We,"f")?.tools?.find(i=>wn(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:Ft(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},xi=function(r){let o=_(this,oe,"m",Cs).call(this,r);if(r.message.content&&!o.content_done){o.content_done=!0;let n=_(this,oe,"m",Ii).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}))},ks=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,Fr,[],"f"),lh(r,_(this,We,"f"))},Ii=function(){let r=_(this,We,"f")?.response_format;return bn(r)?r:null},oc=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:V,...J}=x;Object.assign(b.logprobs,J),q&&((o=b.logprobs).content??(o.content=[]),b.logprobs.content.push(...q)),V&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...V))}if(p&&(b.finish_reason=p,_(this,We,"f")&&ci(_(this,We,"f")))){if(p==="length")throw new Or;if(p==="content_filter")throw new Rr}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,oe,"m",Ii).call(this)&&(b.message.parsed=b.message.content.trim()?_i(b.message.content):null)),k){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:q,id:V,type:J,function:le,...Y}of k){let te=(a=b.message.tool_calls)[q]??(a[q]={});Object.assign(te,Y),V&&(te.id=V),J&&(te.type=J),le&&(te.function??(te.function={name:le.name??"",arguments:""})),le?.name&&(te.function.name=le.name),le?.arguments&&(te.function.arguments+=le.arguments,Ju(_(this,We,"f"),te)&&(te.function.parsed_arguments=_i(te.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 lh(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:V,...J}=I,{arguments:le,name:Y,...te}=U||{};if(V==null)throw new C(`missing choices[${p}].tool_calls[${k}].id
|
|
52
|
+
${Es(t)}`);if(q==null)throw new C(`missing choices[${p}].tool_calls[${k}].type
|
|
53
|
+
${Es(t)}`);if(Y==null)throw new C(`missing choices[${p}].tool_calls[${k}].function.name
|
|
54
|
+
${Es(t)}`);if(le==null)throw new C(`missing choices[${p}].tool_calls[${k}].function.arguments
|
|
55
|
+
${Es(t)}`);return{...J,id:V,type:q,function:{...te,name:Y,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 Hu(u,e)}function Es(t){return JSON.stringify(t)}var Cn=class t extends Ut{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 He=class extends g{constructor(){super(...arguments),this.messages=new Dt(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 Qu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(o=>An(o,e))}runTools(e,r){return e.stream?Cn.runTools(this._client,e,r):Sn.runTools(this._client,e,r)}stream(e,r){return Ut.createChatCompletion(this._client,e,r)}};He.Messages=Dt;var ht=class extends g{constructor(){super(...arguments),this.completions=new He(this._client)}};ht.Completions=He;var Ur=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 qr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Br=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 Kr=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 Gr=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 Vr=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",ee,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=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 Hr=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 Jr=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`,ee,{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 Zr=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`,ee,{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 Zr(this._client),this.roles=new Jr(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",ee,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};gt.Users=Zr;gt.Roles=Jr;var Qr=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 Yr=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 Xr=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 eo=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 to=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 ro=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 oo=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`,ee,{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 no=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 so=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 ao=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`,ee,{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 qt=class extends g{constructor(){super(...arguments),this.roles=new ao(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`,ee,{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}})}};qt.Roles=ao;var io=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`,ee,{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 Bt=class extends g{constructor(){super(...arguments),this.roles=new io(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}})}};Bt.Roles=io;var se=class extends g{constructor(){super(...arguments),this.users=new Bt(this._client),this.serviceAccounts=new no(this._client),this.apiKeys=new Qr(this._client),this.rateLimits=new ro(this._client),this.modelPermissions=new to(this._client),this.hostedToolPermissions=new eo(this._client),this.groups=new qt(this._client),this.roles=new oo(this._client),this.dataRetention=new Xr(this._client),this.spendAlerts=new so(this._client),this.certificates=new Yr(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=Bt;se.ServiceAccounts=no;se.APIKeys=Qr;se.RateLimits=ro;se.ModelPermissions=to;se.HostedToolPermissions=eo;se.Groups=qt;se.Roles=oo;se.DataRetention=Xr;se.SpendAlerts=so;se.Certificates=Yr;var lo=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`,ee,{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 Kt=class extends g{constructor(){super(...arguments),this.roles=new lo(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}})}};Kt.Roles=lo;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new qr(this._client),this.adminAPIKeys=new Ur(this._client),this.usage=new Hr(this._client),this.invites=new Gr(this._client),this.users=new Kt(this._client),this.groups=new gt(this._client),this.roles=new Vr(this._client),this.dataRetention=new Kr(this._client),this.spendAlerts=new Wr(this._client),this.certificates=new Br(this._client),this.projects=new se(this._client)}};ae.AuditLogs=qr;ae.AdminAPIKeys=Ur;ae.Usage=Hr;ae.Invites=Gr;ae.Users=Kt;ae.Groups=gt;ae.Roles=Vr;ae.DataRetention=Kr;ae.SpendAlerts=Wr;ae.Certificates=Br;ae.Projects=se;var yt=class extends g{constructor(){super(...arguments),this.organization=new ae(this._client)}};yt.Organization=ae;var nc=Symbol("brand.privateNullableHeaders");function*jh(t){if(!t)return;if(nc 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():Ga(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=Ga(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 jh(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{[nc]:!0,values:e,nulls:r}};var uo=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 co=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 po=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 co(this._client),this.translations=new po(this._client),this.speech=new uo(this._client)}};De.Transcriptions=co;De.Translations=po;De.Speech=uo;var Gt=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 mo=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 fo=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 ho=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 fo(this._client),this.transcriptionSessions=new ho(this._client)}};_t.Sessions=fo;_t.TranscriptionSessions=ho;var go=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 yo=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 go(this._client),this.threads=new yo(this._client)}};wt.Sessions=go;wt.Threads=yo;var _o=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 wo=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 sc=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 ve=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,Wt,vi,Fe,Ms,Te,Ht,bo,Vt,Rs,we,Ps,Os,Mn,kn,En,ac,ic,lc,uc,cc,dc,pc,Je=class extends mt{constructor(){super(...arguments),ie.add(this),vi.set(this,[]),Fe.set(this,{}),Ms.set(this,{}),Te.set(this,void 0),Ht.set(this,void 0),bo.set(this,void 0),Vt.set(this,void 0),Rs.set(this,void 0),we.set(this,void 0),Ps.set(this,void 0),Os.set(this,void 0),Mn.set(this,void 0)}[(vi=new WeakMap,Fe=new WeakMap,Ms=new WeakMap,Te=new WeakMap,Ht=new WeakMap,bo=new WeakMap,Vt=new WeakMap,Rs=new WeakMap,we=new WeakMap,Ps=new WeakMap,Os=new WeakMap,Mn=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 Wt;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",kn).call(this,n);if(o.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",En).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,o,n){let s=new Wt;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",kn).call(this,i);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",En).call(this))}static createThreadAssistantStream(e,r,o){let n=new Wt;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 Wt;return s._run(()=>s._runAssistantStream(e,r,o,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Ps,"f")}currentRun(){return _(this,Os,"f")}currentMessageSnapshot(){return _(this,Te,"f")}currentRunStepSnapshot(){return _(this,Mn,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,Ms,"f"))}async finalRun(){if(await this.done(),!_(this,Ht,"f"))throw Error("Final run was not received.");return _(this,Ht,"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",kn).call(this,a);if(s.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",En).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",kn).call(this,i);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,ie,"m",En).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(pn(s)&&pn(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(!pn(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)}};Wt=Je,kn=function(e){if(!this.ended)switch(P(this,Ps,e,"f"),_(this,ie,"m",lc).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",pc).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",ic).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",ac).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},En=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Ht,"f"))throw Error("Final run has not been received");return _(this,Ht,"f")},ac=function(e){let[r,o]=_(this,ie,"m",cc).call(this,e,_(this,Te,"f"));P(this,Te,r,"f"),_(this,Ms,"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,bo,"f")){if(_(this,Vt,"f"))switch(_(this,Vt,"f").type){case"text":this._emit("textDone",_(this,Vt,"f").text,_(this,Te,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Vt,"f").image_file,_(this,Te,"f"));break}P(this,bo,n.index,"f")}P(this,Vt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,bo,"f")!==void 0){let n=e.data.content[_(this,bo,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,_(this,Te,"f"));break;case"text":this._emit("textDone",n.text,_(this,Te,"f"));break}}_(this,Te,"f")&&this._emit("messageDone",e.data),P(this,Te,void 0,"f")}},ic=function(e){let r=_(this,ie,"m",uc).call(this,e);switch(P(this,Mn,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,Rs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),P(this,Rs,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,Mn,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}},lc=function(e){_(this,vi,"f").push(e),this._emit("event",e)},uc=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=Wt.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")},cc=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",dc).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")},dc=function(e,r){return Wt.accumulateDelta(r,e)},pc=function(e){switch(P(this,Os,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,Ht,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 Jt=class extends g{constructor(){super(...arguments),this.steps=new wo(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 Je.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 Je.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 Je.createToolAssistantStream(e,this._client.beta.threads.runs,r,o)}};Jt.Steps=wo;var bt=class extends g{constructor(){super(...arguments),this.runs=new Jt(this._client),this.messages=new _o(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 Je.createThreadAssistantStream(e,this._client.beta.threads,r)}};bt.Runs=Jt;bt.Messages=_o;var Se=class extends g{constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new wt(this._client),this.assistants=new mo(this._client),this.threads=new bt(this._client)}};Se.Realtime=_t;Se.ChatKit=wt;Se.Assistants=mo;Se.Threads=bt;var Zt=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Ao=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 Qt=class extends g{constructor(){super(...arguments),this.content=new Ao(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}})}};Qt.Content=Ao;var At=class extends g{constructor(){super(...arguments),this.files=new Qt(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=Qt;var xo=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 xo(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=xo;var Yt=class extends g{create(e,r){let o=!!e.encoding_format,n=o?e.encoding_format:"base64";o&&Q(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:(Q(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=sc(u)}),a)))}};var Io=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 Xt=class extends g{constructor(){super(...arguments),this.outputItems=new Io(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}})}};Xt.OutputItems=Io;var It=class extends g{constructor(){super(...arguments),this.runs=new Xt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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=Xt;var er=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 vo=class extends g{};var To=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 tr=class extends g{constructor(){super(...arguments),this.graders=new To(this._client)}};tr.Graders=To;var So=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 rr=class extends g{constructor(){super(...arguments),this.permissions=new So(this._client)}};rr.Permissions=So;var Co=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 or=class extends g{constructor(){super(...arguments),this.checkpoints=new Co(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}})}};or.Checkpoints=Co;var Ce=class extends g{constructor(){super(...arguments),this.methods=new vo(this._client),this.jobs=new or(this._client),this.checkpoints=new rr(this._client),this.alpha=new tr(this._client)}};Ce.Methods=vo;Ce.Jobs=or;Ce.Checkpoints=rr;Ce.Alpha=tr;var ko=class extends g{};var vt=class extends g{constructor(){super(...arguments),this.graderModels=new ko(this._client)}};vt.GraderModels=ko;var nr=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 sr=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 ar=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Eo=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 Mo=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Ze=class extends g{constructor(){super(...arguments),this.clientSecrets=new Mo(this._client),this.calls=new Eo(this._client)}};Ze.ClientSecrets=Mo;Ze.Calls=Eo;function mc(t,e){if(!e||!hg(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 fc(t,r)&&be(r),r}return Ti(t,e)}function Ti(t,e){let r=!t.status||t.status==="completed",o=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?_g(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?fg(e,i.text):null}:i);return{...s,content:a}}return s}),n=Object.assign({},t,{output:o});return fc(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 fg(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function hg(t){return!!bn(t.text?.format)}function gg(t){return t?.$brand==="auto-parseable-tool"}function yg(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function _g(t,e){let r=yg(t.tools??[],e.name);return{...e,...e,parsed_arguments:gg(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function fc(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 gc(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 hc(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")xe(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}`);xe(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=xe(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=xe(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=xe(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=xe(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=xe(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=xe(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=xe(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"&&(xe(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=xe(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=xe(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=hc(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:wg(t)}return e}function hc(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 xe(t,e){let r=t[e];if(!r)throw new C(`missing content at index ${e}`);return r}function wg(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var Pn,Ns,ir,$s,yc,_c,wc,zs=class t extends mt{constructor(e){super(),Pn.add(this),Ns.set(this,void 0),ir.set(this,void 0),$s.set(this,void 0),P(this,Ns,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,Pn,"m",yc).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,Pn,"m",_c).call(this,a,s);if(n.controller.signal?.aborted)throw new H;return _(this,Pn,"m",wc).call(this)}[(Ns=new WeakMap,ir=new WeakMap,$s=new WeakMap,Pn=new WeakSet,yc=function(){this.ended||P(this,ir,void 0,"f")},_c=function(r,o){if(this.ended)return;let n=(a,i)=>{(o==null||i.sequence_number>o)&&this._emit(a,i)},s=gc(r,_(this,ir,"f"));switch(P(this,ir,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}},wc=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,ir,"f");if(!r)throw new C("request ended without sending any events");P(this,ir,void 0,"f");let o=bg(r,_(this,Ns,"f"));return P(this,$s,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,$s,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function bg(t,e){return mc(t,e)}var Po=class extends g{list(e,r={},o){return this._client.getAPIList(m`/responses/${e}/input_items`,N,{query:r,...o,__security:{bearerAuth:!0}})}};var Oo=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 Po(this._client),this.inputTokens=new Oo(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=>Ti(o,e))}stream(e,r){return zs.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=Po;Ue.InputTokens=Oo;var Ro=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 No=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 lr=class extends g{constructor(){super(...arguments),this.content=new No(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}})}};lr.Content=No;var Qe=class extends g{constructor(){super(...arguments),this.content=new Ro(this._client),this.versions=new lr(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}})}};Qe.Content=Ro;Qe.Versions=lr;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 bc=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 zo=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 bc(p),await this.createAndPoll(e,{file_ids:l})}};var Lo=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 Ye=class extends g{constructor(){super(...arguments),this.files=new Lo(this._client),this.fileBatches=new zo(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}})}};Ye.Files=Lo;Ye.FileBatches=zo;var ur=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 jo,Ac,Ls,cr=class extends g{constructor(){super(...arguments),jo.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,jo,"m",Ac).call(this,o);let s=T([r]).values,a=_(this,jo,"m",Ls).call(this,s,"webhook-signature"),i=_(this,jo,"m",Ls).call(this,s,"webhook-timestamp"),u=_(this,jo,"m",Ls).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")}};jo=new WeakSet,Ac=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")},Ls=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 Ic=Symbol.for("openai.node.providerDefinitions.v1"),vc=globalThis,Tc=vc[Ic],Sc=Tc??new WeakMap;Tc||Object.defineProperty(vc,Ic,{value:Sc});function Cc(t){let e=Sc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Si,Ci,On,kc,Eg="workload-identity-auth",O=class{constructor(e={}){Si.add(this),On.set(this,void 0),this.completions=new Zt(this),this.chat=new ht(this),this.embeddings=new Yt(this),this.files=new er(this),this.images=new nr(this),this.audio=new De(this),this.moderations=new ar(this),this.models=new sr(this),this.fineTuning=new Ce(this),this.graders=new vt(this),this.vectorStores=new Ye(this),this.webhooks=new cr(this),this.beta=new Se(this),this.batches=new Gt(this),this.uploads=new Tt(this),this.admin=new yt(this),this.responses=new Ue(this),this.realtime=new Ze(this),this.conversations=new xt(this),this.evals=new It(this),this.containers=new At(this),this.skills=new Qe(this),this.videos=new ur(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:ve("OPENAI_BASE_URL"),apiKey:n=r?null:ve("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:ve("OPENAI_ADMIN_KEY")??null,organization:a=r?null:ve("OPENAI_ORG_ID")??null,project:i=r?null:ve("OPENAI_PROJECT_ID")??null,webhookSecret:u=ve("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,p=r?Cc(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&&xu())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,
|
|
@@ -61,20 +61,20 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
61
61
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
62
62
|
|
|
63
63
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
64
|
-
`);this.baseURL=f.baseURL,this.timeout=f.timeout??
|
|
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 W.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(Q(this).debug(`[${l}] sending request`,Ge({retryOfRequestLogID:o,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new H;let f=n.__security??{bearerAuth:!0},x=new AbortController,w=await this.fetchWithAuth(i,a,u,x,f).catch(ln),b=Date.now();if(w instanceof globalThis.Error){let h=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new H;let I=an(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Q(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${h}`),Q(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${h})`,Ge({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),this.retryRequest(n,r,o??l);throw Q(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),Q(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ge({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),w instanceof Nt||w instanceof un?w:I?new Ne:new ct({message:kg(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 J=`retrying, ${r} attempts remaining`;return await Wa(w.body),Q(this).info(`${S} - ${J}`),Q(this).debug(`[${l}] response error (${J})`,Ge({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";Q(this).info(`${S} - ${I}`);let k=await w.text().catch(J=>ln(J).message),U=gu(k),q=U?void 0:k;throw Q(this).debug(`[${l}] response error (${I})`,Ge({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 Q(this).info(S),Q(this).debug(`[${l}] response start`,Ge({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 fn(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 ${Cg}`){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,Mn,"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,Mn,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ti=O,Mn=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=W;O.APIConnectionError=ct;O.APIConnectionTimeoutError=Ne;O.APIUserAbortError=H;O.NotFoundError=Tr;O.ConflictError=Sr;O.RateLimitError=kr;O.BadRequestError=xr;O.AuthenticationError=Ir;O.InternalServerError=Er;O.PermissionDeniedError=vr;O.UnprocessableEntityError=Cr;O.InvalidWebhookSignatureError=$e;O.toFile=gn;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=Ce;O.Graders=vt;O.VectorStores=Ye;O.Webhooks=lr;O.Beta=Se;O.Batches=Bt;O.Uploads=Tt;O.Admin=yt;O.Responses=Ue;O.Realtime=Ze;O.Conversations=xt;O.Evals=It;O.Containers=At;O.Skills=Qe;O.Videos=ir;function kg(t){if(Eg(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 Eg(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 Mg(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===H.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",Et(e,!1)):Mg(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(sn(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=Et(sn(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=Et(sn(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=Et(sn(t,"MODEL_NOT_FOUND"),!1):e=t,e}var ke=t=>t();function Xe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Pg(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 Og="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'."),Og)}function et(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 Pg(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 tt(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=ke(()=>{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 rt(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 br(t)?r=va(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Rg(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
|
-
`)}function
|
|
67
|
-
`)}function
|
|
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 Lo(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 Pn=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])=>[Pn(n),{def:Pn(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 Ng(t,e)}}var Ng=(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 $g=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($g(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"?zg(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":Ee(r,"email",n.message,e);break;case"format:idn-email":Ee(r,"idn-email",n.message,e);break;case"pattern:zod":Me(r,dr.email,n.message,e);break}break;case"url":Ee(r,"uri",n.message,e);break;case"uuid":Ee(r,"uuid",n.message,e);break;case"regex":Me(r,n.regex,n.message,e);break;case"cuid":Me(r,dr.cuid,n.message,e);break;case"cuid2":Me(r,dr.cuid2,n.message,e);break;case"startsWith":Me(r,RegExp(`^${o(n.value)}`),n.message,e);break;case"endsWith":Me(r,RegExp(`${o(n.value)}$`),n.message,e);break;case"datetime":Ee(r,"date-time",n.message,e);break;case"date":Ee(r,"date",n.message,e);break;case"time":Ee(r,"time",n.message,e);break;case"duration":Ee(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":{Me(r,RegExp(o(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&Ee(r,"ipv4",n.message,e),n.version!=="v4"&&Ee(r,"ipv6",n.message,e);break}case"emoji":Me(r,dr.emoji,n.message,e);break;case"ulid":{Me(r,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ee(r,"binary",n.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Me(r,dr.base64,n.message,e);break}}break}case"nanoid":Me(r,dr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var zg=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ee=(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)},Me=(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
|
|
64
|
+
`);this.baseURL=f.baseURL,this.timeout=f.timeout??Ci.DEFAULT_TIMEOUT,this.logger=f.logger??console;let x="warn";this.logLevel=x,this.logLevel=oi(f.logLevel,"ClientOptions.logLevel",this)??oi(ve("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??x,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??cs(),P(this,On,Tu,"f");let w=r?void 0:ve("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 ys(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 Nu(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ka()}`}makeStatusError(e,r,o,n){return W.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,Si,"m",kc).call(this)&&o||this.baseURL,s=hu(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Va(a)||!Va(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 jt(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(Q(this).debug(`[${l}] sending request`,Ge({retryOfRequestLogID:o,method:n.method,url:i,options:n,headers:a.headers})),n.signal?.aborted)throw new H;let f=n.__security??{bearerAuth:!0},x=new AbortController,w=await this.fetchWithAuth(i,a,u,x,f).catch(cn),b=Date.now();if(w instanceof globalThis.Error){let h=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new H;let I=un(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Q(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${h}`),Q(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${h})`,Ge({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),this.retryRequest(n,r,o??l);throw Q(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),Q(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Ge({retryOfRequestLogID:o,url:i,durationMs:b-p,message:w.message})),w instanceof zt||w instanceof dn?w:I?new Ne:new ct({message:Mg(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 Ja(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 J=`retrying, ${r} attempts remaining`;return await Ja(w.body),Q(this).info(`${S} - ${J}`),Q(this).debug(`[${l}] response error (${J})`,Ge({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";Q(this).info(`${S} - ${I}`);let k=await w.text().catch(J=>cn(J).message),U=_u(k),q=U?void 0:k;throw Q(this).debug(`[${l}] response error (${I})`,Ge({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 Q(this).info(S),Q(this).debug(`[${l}] response start`,Ge({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 gn(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 ${Eg}`){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&&yu("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))}:{},...Iu(),"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,On,"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:ds(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,On,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ci=O,On=new WeakMap,Si=new WeakSet,kc=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=Ci;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=C;O.APIError=W;O.APIConnectionError=ct;O.APIConnectionTimeoutError=Ne;O.APIUserAbortError=H;O.NotFoundError=Cr;O.ConflictError=kr;O.RateLimitError=Mr;O.BadRequestError=vr;O.AuthenticationError=Tr;O.InternalServerError=Pr;O.PermissionDeniedError=Sr;O.UnprocessableEntityError=Er;O.InvalidWebhookSignatureError=$e;O.toFile=_n;O.Completions=Zt;O.Chat=ht;O.Embeddings=Yt;O.Files=er;O.Images=nr;O.Audio=De;O.Moderations=ar;O.Models=sr;O.FineTuning=Ce;O.Graders=vt;O.VectorStores=Ye;O.Webhooks=cr;O.Beta=Se;O.Batches=Gt;O.Uploads=Tt;O.Admin=yt;O.Responses=Ue;O.Realtime=Ze;O.Conversations=xt;O.Evals=It;O.Containers=At;O.Skills=Qe;O.Videos=ur;function Mg(t){if(Pg(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 Pg(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 Og(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 Ie(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",Pt(e,!0)):t.constructor.name===H.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",Pt(e,!1)):Og(t)?e=Tl.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Pt(ln(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=Pt(ln(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=Pt(ln(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=Pt(ln(t,"MODEL_NOT_FOUND"),!1):e=t,e}var ke=t=>t();function Xe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Rg(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 js(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Ng="LC_AUTOGENERATED";function dr(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'."),Ng)}function et(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(!Wn.isInstance(t))throw new Error("Invalid generic chat message");return Rg(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ec(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function tt(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 Ei(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Mc(t){let e=ke(()=>{if(Ei(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ei(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 Pc(){let t=Il();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function rt(t,e=!1,r="1.0.0"){let o=Mc(t),n=Pc(),s=`langchainjs${e?"-azure":""}-openai`;return{...o,"User-Agent":o["User-Agent"]?`${s}/${r} (${n})${o["User-Agent"]}`:`${s}/${r} (${n})`}}function Oc(t,e){let r;return xr(t)?r=Sa(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function $g(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Rc(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(Nc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
66
|
+
`)}function Nc(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}: ${Ds(n,e)},`):r.push(`${o}?: ${Ds(n,e)},`);return r.map(o=>" ".repeat(e)+o).join(`
|
|
67
|
+
`)}function Ds(t,e){if($g(t))return t.anyOf.map(r=>Ds(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["{",Nc(t,e+2),"}"].join(`
|
|
68
|
+
`);case"array":return t.items?`${Ds(t.items,e)}[]`:"any[]";default:return""}}function Fs(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 Do(t){return"type"in t&&t.type!=="function"}function $c(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 zc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function pr(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 Us(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Lc(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 jc(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 Dc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Fc(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 Uc(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 qc(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 Kc=Symbol("Let zodToJsonSchema decide on which parser to use"),Bc={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"},Gc=t=>typeof t=="string"?{...Bc,basePath:["#"],definitions:{},name:t}:{...Bc,basePath:["#"],definitions:{},...t};var Rn=t=>"_def"in t?t._def:t;function Vc(t){if(!t)return!0;for(let e in t)return!1;return!0}var Wc=t=>{let e=Gc(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])=>[Rn(n),{def:Rn(n),path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function Mi(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function j(t,e,r,o,n){t[e]=r,Mi(t,e,o,n)}function Hc(){return{}}function Jc(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 Zc(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 Qc(){return{type:"boolean"}}function Yc(t,e,r){return R(t.type._def,e,r)}var Xc=(t,e,r)=>R(t.innerType._def,e,r);function Pi(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,s)=>Pi(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 zg(t,e)}}var zg=(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 ed(t,e,r){return{...R(t.innerType._def,e,r),default:t.defaultValue()}}function td(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function rd(t){return{type:"string",enum:[...t.values]}}var Lg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function od(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(Lg(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 nd(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 Oi,mr={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:()=>(Oi===void 0&&(Oi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Oi),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 qs(t,e){let r={type:"string"};function o(n){return e.patternStrategy==="escape"?jg(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":Ee(r,"email",n.message,e);break;case"format:idn-email":Ee(r,"idn-email",n.message,e);break;case"pattern:zod":Me(r,mr.email,n.message,e);break}break;case"url":Ee(r,"uri",n.message,e);break;case"uuid":Ee(r,"uuid",n.message,e);break;case"regex":Me(r,n.regex,n.message,e);break;case"cuid":Me(r,mr.cuid,n.message,e);break;case"cuid2":Me(r,mr.cuid2,n.message,e);break;case"startsWith":Me(r,RegExp(`^${o(n.value)}`),n.message,e);break;case"endsWith":Me(r,RegExp(`${o(n.value)}$`),n.message,e);break;case"datetime":Ee(r,"date-time",n.message,e);break;case"date":Ee(r,"date",n.message,e);break;case"time":Ee(r,"time",n.message,e);break;case"duration":Ee(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":{Me(r,RegExp(o(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&Ee(r,"ipv4",n.message,e),n.version!=="v4"&&Ee(r,"ipv6",n.message,e);break}case"emoji":Me(r,mr.emoji,n.message,e);break;case"ulid":{Me(r,mr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ee(r,"binary",n.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Me(r,mr.base64,n.message,e);break}}break}case"nanoid":Me(r,mr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var jg=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ee=(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)},Me=(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:sd(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):j(t,"pattern",sd(e,o),r,o)},sd=(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 On={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 On&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,s)=>{let a=On[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:On[t.innerType._def.typeName],nullable:!0}:{type:[On[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 Lg(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:Lg(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=jg(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=Ug(t,t.typeName,e,r);return s&&qg(t,e,s),n.jsonSchema=s,s}finally{r&&o&&e.seen.set(t,o)}}var jg=(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:Dg(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:Fg(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_",Dg=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},Fg=(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("/")},Ug=(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)}},qg=(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(Pn(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 ot(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 ot(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))ot(x,[...e,"$defs",f],r);let n=t.definitions;if(pr(n))for(let[f,x]of Object.entries(n))ot(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,ot(x,[...e,"properties",f],r)]))}let u=t.items;pr(u)&&(t.items=ot(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,x)=>ot(f,[...e,"anyOf",String(x)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=ot(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,x)=>ot(f,[...e,"allOf",String(x)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Kg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=Bg(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,ot(t,e,r)}return t}function Bg(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 Kg(t,e){let r=0;for(let o in t)if(r++,r>e)return!0;return!1}function Gg(t,e){return Pi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Vg(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 Wg(t){return"_zod"in t}function Id(t,e,r){return Gu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Wg(t)?Vg(t):Gg(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 Hg(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 Hg({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 jo(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(!Xe(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=tt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=rt(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(Lo(o)||cr(o))return o;if(Rc(o))return o.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(o,{strict:r});return br(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(et(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=lt.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 Rn={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(_r(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 it({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=et(t);if(r==="system"&&Xe(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=et(r);o==="system"&&Xe(e)&&(o="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(a=>Bn(a)?Kn(a,Rn):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(jo(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),Xe(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}:{}},at(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 on({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 on({message:new it({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 Zg(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 Do=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}},Nn=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(_r(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(_r(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=zc(i);u?r.push(u):o.push(_r(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:Do(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=Nn(t.response);if(o=Do(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 on({text:e.map(u=>u.text).join(""),message:new it({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=ke(()=>{try{let h=et(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=ke(()=>{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=ke(()=>{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=ke(()=>{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())},Fo=({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=et(o);if(a==="system"&&Xe(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:ke(()=>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(Zg)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:ke(()=>{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,Rn)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:ke(()=>{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:ke(()=>{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=Qg(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=Do(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 Qg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Js=class extends mr{constructor(t,e){super(jo(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:Fo({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:Nn(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:Fo({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:Fo({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(Lo(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=jo(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(Lo),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=tt({baseURL:this.clientConfig.baseURL}),o={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=rt(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 ty=v.object({type:v.literal("screenshot")}),ry=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),oy=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),ny=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),sy=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),ay=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),iy=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),ly=v.object({type:v.literal("type"),text:v.string()}),uy=v.object({type:v.literal("wait"),duration:v.number().optional()}),cy=v.union([ty,ry,oy,ny,sy,ay,iy,ly,uy]),fG=v.object({action:cy});var dy=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()}),_G=v.union([dy]);var xG=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 py=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),my=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),fy=v.object({type:v.literal("delete_file"),path:v.string()}),SG=v.union([py,my,fy]);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,wy=()=>{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=wy();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},by=async(t="default")=>await Fd(Dd[t]),Ud=async(t="default")=>await Fd(Di[t]),Ay=M.Root({agentExecutionContext:M({default:ka,reducer:Sa}),currentIntent:M({default:()=>"none",reducer:Ke}),routing:M({default:()=>({mode:"auto"}),reducer:Ke}),lastExecutedAgent:M({default:()=>"",reducer:Ke}),requiresFollowUp:M({default:()=>!0,reducer:Ke}),stepCount:M({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:M({default:()=>"",reducer:Ca})});var xy=t=>typeof t=="string"&&t.length>0?t:void 0,Iy=()=>hl(),vy=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Ty=t=>{let e=t?.configurable;return{conversationId:xy(e?.thread_id),abortSignal:t?.signal,requestId:Iy(),requestSource:vy(_y.applicationName)}},Sy=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 yy.getCredential(`${e.url}/sharing`))?.token;return async(o,n)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Ty(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:Sy(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 by(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})},Cy=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(Cy);var Kd="0.1",Uo=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 Bs(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(qs(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 ad(t,e){if(e.mapStrategy==="record")return Bs(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 id(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 ld(){return{not:{}}}function ud(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Nn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function dd(t,e){if(e.target==="openApi3")return cd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in Nn&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,s)=>{let a=Nn[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 cd(t,e)}var cd=(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 pd(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:Nn[t.innerType._def.typeName],nullable:!0}:{type:[Nn[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 md(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",Mi(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 Dg(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 fd(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:Dg(t,e)};return r.required.length||delete r.required,r}var hd=(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 gd=(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 yd(t,e,r){return R(t.type._def,e,r)}function _d(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 wd(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 bd(){return{not:{}}}function Ad(){return{}}var xd=(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!==Kc)return s}if(o&&!r){let s=Fg(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=Bg(t,t.typeName,e,r);return s&&Kg(t,e,s),n.jsonSchema=s,s}finally{r&&o&&e.seen.set(t,o)}}var Fg=(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:Ug(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:qg(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}},Id="_x_",Ug=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Id))return t;let e=Id;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},qg=(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("/")},Bg=(t,e,r,o)=>{switch(e){case $.ZodString:return qs(t,r);case $.ZodNumber:return md(t,r);case $.ZodObject:return fd(t,r);case $.ZodBigInt:return Zc(t,r);case $.ZodBoolean:return Qc();case $.ZodDate:return Pi(t,r);case $.ZodUndefined:return bd();case $.ZodNull:return ud(r);case $.ZodArray:return Jc(t,r);case $.ZodUnion:case $.ZodDiscriminatedUnion:return dd(t,r);case $.ZodIntersection:return od(t,r);case $.ZodTuple:return wd(t,r);case $.ZodRecord:return Bs(t,r);case $.ZodLiteral:return nd(t,r);case $.ZodEnum:return rd(t);case $.ZodNativeEnum:return id(t);case $.ZodNullable:return pd(t,r,o);case $.ZodOptional:return hd(t,r,o);case $.ZodMap:return ad(t,r);case $.ZodSet:return _d(t,r);case $.ZodLazy:return R(t.getter()._def,r,o);case $.ZodPromise:return yd(t,r,o);case $.ZodNaN:case $.ZodNever:return ld();case $.ZodEffects:return td(t,r,o);case $.ZodAny:return Hc();case $.ZodUnknown:return Ad();case $.ZodDefault:return ed(t,r,o);case $.ZodBranded:return Yc(t,r,o);case $.ZodReadonly:return xd(t,r,o);case $.ZodCatch:return Xc(t,r,o);case $.ZodPipeline:return gd(t,r,o);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(n=>{})(e)}},Kg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ri=(t,e)=>{let r=Wc(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(Vc(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(Rn(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 vd(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 ot(e,[],e)}function Ni(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Ni(e))return!0;for(let e of t.anyOf??[])if(Ni(e))return!0;return!1}function ot(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!fr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let o=t.$defs;if(fr(o))for(let[f,x]of Object.entries(o))ot(x,[...e,"$defs",f],r);let n=t.definitions;if(fr(n))for(let[f,x]of Object.entries(n))ot(x,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(fr(i)){for(let[f,x]of Object.entries(i))if(!Ni(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,ot(x,[...e,"properties",f],r)]))}let u=t.items;fr(u)&&(t.items=ot(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,x)=>ot(f,[...e,"anyOf",String(x)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=ot(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,x)=>ot(f,[...e,"allOf",String(x)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Vg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=Gg(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!fr(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,ot(t,e,r)}return t}function Gg(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(!fr(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 fr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Vg(t,e){let r=0;for(let o in t)if(r++,r>e)return!0;return!1}function Wg(t,e){return Ri(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Hg(t){return vd(Ol(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 Jg(t){return"_zod"in t}function Td(t,e,r){return Wu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Jg(t)?Hg(t):Wg(t,{name:e})}},o=>t.parse(JSON.parse(o)))}var Sd=["jsonSchema","functionCalling","jsonMode"];function Cd(t,e){if(typeof e<"u"&&!Sd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Sd.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 Zg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function kd(t,e,r){if(Rl(t))return Td(t,e,r);if(Zn(t))return Zg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Rt(t,{cycles:"ref",reused:"ref",override(o){o.jsonSchema.title=e}})}},o=>Ml(t,JSON.parse(o)));throw new Error("Unsupported schema response format")}function Ed(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 Md={"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 Ks="**REDACTED**";function Fo(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var hr=class extends es{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=Ks),"authorization"in o&&(o.authorization=Ks),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=Ks),"authorization"in o&&(o.authorization=Ks),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=Ca({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(!Xe(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&&Ot(t.json_schema.schema)?kd(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=tt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=rt(r.defaultHeaders),this.client=new O(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return pr(t)?qc(t.metadata.customTool):Yn(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Oc(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(Do(o)||pr(o))return o;if($c(o))return o.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(o,{strict:r});return xr(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(et(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=Rc(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 Ie(n)}})}get profile(){return Md[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=Cd(this.model,e?.method);if(i==="jsonMode"){o=va(n);let u=Rt(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=Rt(n),l={name:s??"extract",description:xa(u),schema:Ot(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}}}),Ot(n)||Jn(n)){let d=va(n);o=lt.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:d.invoke(p.content))}else o=new zl}else{let u=s??"extract",l=Rt(n),d;Ot(n)||Jn(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=Ll(n,u)}return jl(r,o,a)}};var $n={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=wa({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=_a(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=_a(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=wa({dataUrl:t.url}),r=dr(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=dr(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`)}},Gs=({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(Xn(l,{returnId:!0}))}catch(d){a.push(br(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:Ed(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 Wn(t.content||"",t.role??"unknown")}},Vs=({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 Aa({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 it({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return n==="system"?new Hn({content:s,response_metadata:i}):n==="developer"?new Hn({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new Cl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):n==="tool"?new ba({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new Sl({content:s,role:n,response_metadata:i})},$i=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=kl(()=>{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=dr(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}}}},zi=({message:t,model:e})=>{let r=et(t);if(r==="system"&&Xe(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(Ia):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=$i(s);a&&(yield a)}}return{role:"user",content:Array.from(o(t.contentBlocks))}},gr=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return zi({message:r});let o=et(r);o==="system"&&Xe(e)&&(o="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(a=>Gn(a)?Vn(a,$n):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(Ia):(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 Ws=class extends hr{constructor(t,e){super(Fo(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:Fs(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),Xe(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=gr({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}:{}},at(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=gr({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*ts(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=gr({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 sn({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 sn({message:new it({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 Ie(a)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Vs({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Gs({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Hs="__openai_function_call_ids__",Js="__openai_custom_tool_call_ids__";function Ld(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 Yg(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 Uo=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}},zn=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(Ld),...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(Xn(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),o.push(br(u,d))}a[Hs]??={},i.id&&(a[Hs][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=Lc(i);u?(r.push(u),a[Js]??={},i.id&&i.call_id&&(a[Js][i.call_id]=i.id)):o.push(br(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=jc(i);u?r.push(u):o.push(br(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:Uo(t.usage),additional_kwargs:a,response_metadata:s})},Li=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}},Zs=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:[Ld(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[Hs]={[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[Js]={[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=zn(t.response);if(o=Uo(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 sn({text:e.map(u=>u.text).join(""),message:new it({id:i,content:e,tool_call_chunks:n,usage_metadata:o,additional_kwargs:a,response_metadata:s}),generationInfo:r})},ji=t=>{let e=F.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let o=ke(()=>{try{let h=et(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=ke(()=>{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=js(h);return{type:"input_file",file_id:h.fileId,...I?{filename:I}:{}}}if(h.url){let I=js(h);return{...I?{filename:I}:{},type:"input_file",file_url:h.url}}if(h.data){let I=dr(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=ke(()=>{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=ke(()=>{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())},qo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(o=>{let n=o.response_metadata;if(n?.output_version==="v1")return ji(o);let s=o.additional_kwargs,a=et(o);if(a==="system"&&Xe(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=Li(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:ke(()=>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(Yg)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:ke(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let p=s?.[Hs],f=s?.[Js];F.isInstance(o)&&o.tool_calls?.length?i.push(...o.tool_calls.map(b=>Fc(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}:Dc(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}),Gn(l)){if(l.type==="file"){let d=js(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:dr(l)}}return Vn(l,$n)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:ke(()=>{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:ke(()=>{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*Di(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:Dl(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=Xg(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=Uo(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 Xg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Qs=class extends hr{constructor(t,e){super(Fo(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:zc(t?.tool_choice)?t?.tool_choice:(()=>{let n=Fs(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:qo({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:zn(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:qo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Di(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:qo({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=Zs(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 Ie(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 Ie(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let o of t)if(Do(o))o.type==="image_generation"&&e?.stream&&(o.partial_images=1),r.push(o);else if(pr(o)){let n=o.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Yn(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 Us(o)&&r.push(Uc(o));return r}};var Ys=class jd extends hr{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=Fo(e,r);super(o),this.fields=o,this.useResponsesApi=o?.useResponsesApi??!1,this.responses=o?.responses??new Qs(o),this.completions=o?.completions??new Ws(o)}_useResponsesApi(e){let r=e?.tools?.some(Do),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(Us)||e?.tools?.some(pr);return this.useResponsesApi||r||o||n||Ec(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 jd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Xs=class extends Nl{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=Ta(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=tt({baseURL:this.clientConfig.baseURL}),o={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=rt(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 Ie(r)}})}};var oy=v.object({type:v.literal("screenshot")}),ny=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),sy=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),ay=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),iy=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),ly=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),uy=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),cy=v.object({type:v.literal("type"),text:v.string()}),dy=v.object({type:v.literal("wait"),duration:v.number().optional()}),py=v.union([oy,ny,sy,ay,iy,ly,uy,cy,dy]),_G=v.object({action:py});var my=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()}),xG=v.union([my]);var SG=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 fy=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),hy=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),gy=v.object({type:v.literal("delete_file"),path:v.string()}),MG=v.union([fy,hy,gy]);var Ud={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Ui={default:"text-embedding-ada-002"},Fi=new Map,ea=null,Ay=()=>{let t=Dd.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},qd=async t=>{let e=Ay();Fi.size===0&&(ea||(ea=(async()=>{try{(await Fd(`${e}/models`)).data.models.forEach(o=>Fi.set(o.name,o))}catch(o){throw ea=null,o}})()),await ea);let r=Fi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},xy=async(t="default")=>await qd(Ud[t]),Bd=async(t="default")=>await qd(Ui[t]),Iy=M.Root({agentExecutionContext:M({default:Ma,reducer:ka}),currentIntent:M({default:()=>"none",reducer:Ke}),routing:M({default:()=>({mode:"auto"}),reducer:Ke}),lastExecutedAgent:M({default:()=>"",reducer:Ke}),requiresFollowUp:M({default:()=>!0,reducer:Ke}),stepCount:M({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:M({default:()=>"",reducer:Ea})});var vy=t=>typeof t=="string"&&t.length>0?t:void 0,Ty=()=>yl(),Sy=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Cy=t=>{let e=t?.configurable;return{conversationId:vy(e?.thread_id),abortSignal:t?.signal,requestId:Ty(),requestSource:Sy(by.applicationName)}},ky=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)}`)},Kd=async({config:t})=>{let e=Dd.getDefault(),r=(await wy.getCredential(`${e.url}/sharing`))?.token;return async(o,n)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Cy(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 Fd(o instanceof Request?o.url:o.toString(),{body:ky(n?.body),headers:Object.fromEntries(l),responseType:"native",signal:d})).data}},qi=async(t={})=>{let{modelTier:e="default",config:r}=t,o=Ud[e],n=await xy(e);return new Ys({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await Kd({config:r})}})},Gd=async(t={})=>{let{tier:e="default",config:r}=t,o=Ui[e],n=await Bd(e);return new Xs({modelName:o,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await Kd({config:r})},batchSize:2048,maxConcurrency:10})},Ey=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(Ey);var Vd="0.1",Bo=1536,Wd="openai",Hd=Ui.default,Jd=`Name: {name}
|
|
73
73
|
Title: {title}
|
|
74
|
-
Description: {description}`,
|
|
74
|
+
Description: {description}`,Zd=`Name: {name}
|
|
75
75
|
Alias: {alias}
|
|
76
|
-
Description: {description}`,
|
|
77
|
-
Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Oy(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(Py(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(at(l)){i=l;break}}if(i==null||!at(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 X2=M.Root({llmInputMessages:M({reducer:(t,e)=>nn([],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 Ny=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."},$y=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return Ny(r)},zy=E($y,{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 Ly=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."},jy=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return await Ly(r)},Dy=E(jy,{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 qo(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(qo(t)){let{point:r}=t;return{geometry:new Fy({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"}},Uy=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Ie=c.enum(Uy);var Ky=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)}}},Gy=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 qy({filter:new By({...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 Ky(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}`},Vy=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 Gy(t,a,o,n,e,r)},Wy=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.")}),Hy=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.")}),Jy=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([Wy,Hy]).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.")}),Zy=E(Vy,{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:Jy});var Xy=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 Xy.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},e_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,t_=t=>{if(typeof t=="string"&&t)return t;let e=Ui(t);return e?e.toISOString().slice(0,10):null};var r_=(t,e,r)=>{let o=e?.toLowerCase();if(o&&!rp(o))return t;if(o==="date-only"){let s=t_(t);return s?Qy(s,Xs("short-date")):t}if(o==="time-only"){if(typeof t=="string"&&t)return Yy(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:e_(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},o_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,n_=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},s_=(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}},a_=(t,e,r)=>{let o=n_(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=o_(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"?s_(r,s):s?.type==="date-time"?!o||rp(o)?a_(r,s,n):r:r_(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 i_=(t,e,r)=>{let o=t.createQuery();return o.outFields=[e],o.where=r||"1=1",o.num=1,o},l_=async(t,e,r,o)=>{let n=o.map?.allLayers.find(d=>d.id===t),s=i_(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 u_({layerId:t,fieldName:e,query:r},o){let{mapView:n}=D(o,["mapView"]),s=await l_(t,e,r,n);return JSON.stringify(s,null,2)}var c_=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(u_,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:c_});var Bo=(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 f_=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 qo(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new m_({geometry:S.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let x=Bo(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 d_(S);let h=["string","small-integer","integer"],I=l.domain?.type==="coded-value"?l.domain:null;(h.includes(l.type)||I)&&(b=(await p_({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 h_({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:o},n){let s=Ct(n,"layersAndFieldsRegistry"),{mapView:a}=D(n,["mapView"]),i=await f_({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:o});return JSON.stringify(i,null,2)}var g_=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.")}),y_=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.")}),__=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([g_,y_]).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(h_,{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}`,Qd=v.object({schemaVersion:v.literal(Vd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Wd),model:v.literal(Hd),dimensions:v.literal(Bo),templates:v.object({layer:v.string().default(Jd),field:v.string().default(Zd)})}),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(Bo,{message:`Layer vector must be exactly ${Bo} 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(Bo,{message:`Field vector must be exactly ${Bo} dimensions`})}))})).default([])});var My=(t,e)=>{let r=Fl.fromTemplate(t);return Ar.fromMessages([r,...e])};var Ln=async t=>{let{promptText:e,modelTier:r="default",messages:o,inputVariables:n,schema:s,config:a}=t,i=My(e,o??[]),u=(await qi({modelTier:r,config:a})).withStructuredOutput(s);return await i.pipe(u).invoke(n??{},a)};var Py=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),t2=c.object({fields:c.array(Py)});var r2=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var Yd=async t=>{try{return await(await Gd()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var ep=t=>Array.isArray(t)&&t.every(nn),Ry=t=>typeof t=="object"&&t!=null&&"messages"in t&&ep(t.messages),Ny=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,nt=class extends Ul{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 nn(a)&&a.getType()==="tool"||Mt(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||Kn(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(Ny(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(ep(t))s=t;else if(Ry(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(at(l)){i=l;break}}if(i==null||!at(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(Mt))return Array.isArray(t)?r:{messages:r};let o=[],n=null;for(let s of r)Mt(s)?s.graph===Be.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>xl(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 oW=M.Root({llmInputMessages:M({reducer:(t,e)=>an([],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 zy=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."},Ly=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return zy(r)},jy=E(Ly,{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 Dy=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."},Fy=async(t,e)=>{let{mapView:r}=D(e,["mapView"]);return await Dy(r)},Uy=E(Fy,{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 tp=750;function Ko(t){return"point"in t&&t.point!==void 0}function yr(t){return"layerId"in t&&t.layerId!==void 0}var St=async(t,e)=>{if(Ko(t)){let{point:r}=t;return{geometry:new qy({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(yr(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:tp+1});if(!s.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${n}`};if(s.features.length>tp)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]:rp.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"}},By=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Ae=c.enum(By),Ky=c.object({id:c.string()}),Gy=c.object({id:c.string(),kind:c.literal("point"),payload:c.object({x:c.number(),y:c.number(),spatialReference:c.object({wkid:c.number()}).optional()})}),Ct=c.object({sharedResourceId:c.string().describe("ID of a point returned by listSharedResources for a previously geocoded address or place."),distance:c.number().optional().describe("Optional buffer distance around the point."),units:Ae.optional().describe("The units for the distance buffer.")}),kt=(t,e)=>{if(!t||!("sharedResourceId"in t))return t;if(!e)throw new Error("Shared resources are unavailable in the tool runtime state.");let r=e.find(n=>{let s=Ky.safeParse(n);return s.success&&s.data.id===t.sharedResourceId});if(!r)throw new Error(`Shared resource not found: ${t.sharedResourceId}`);let o=Gy.safeParse(r);if(!o.success)throw new Error(`Shared resource ${t.sharedResourceId} does not contain a valid point.`);return{point:o.data.payload,distance:t.distance,units:t.units}};var Hy=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)}}},Jy=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 Vy({filter:new Wy({...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 Hy(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}`},Zy=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"]),i=kt(e,s.state?.agentExecutionContext?.sharedResources);return await Jy(t,a,o,n,i,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:Ae.optional().describe("The units for the distance buffer.")}),Yy=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:Ae.optional().describe("The units for the distance buffer.")}),Xy=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,Yy,Ct]).optional().describe("Optional spatial filter. Use 'sharedResourceId' with an ID from listSharedResources for a previously geocoded location."),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.")}),e_=E(Zy,{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:Xy});var o_=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),np=t=>{if(!t)return!1;let e=t.toLowerCase();return o_.has(e)},Bi=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},n_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,s_=t=>{if(typeof t=="string"&&t)return t;let e=Bi(t);return e?e.toISOString().slice(0,10):null};var a_=(t,e,r)=>{let o=e?.toLowerCase();if(o&&!np(o))return t;if(o==="date-only"){let s=s_(t);return s?t_(s,ta("short-date")):t}if(o==="time-only"){if(typeof t=="string"&&t)return r_(t,ta("long-time"));let s=Bi(t);return s?op(s,{...ta("long-time"),timeZone:"UTC"}):t}let n=Bi(t);return n?op(n,{...ta("short-date-short-time"),timeZone:n_(r)}):t},sp=(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},i_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,l_=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},u_=(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}},c_=(t,e,r)=>{let o=l_(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=i_(r);try{return new Intl.DateTimeFormat(void 0,n).format(o)}catch{return t}},ap=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,ip=(t,e,r,o,n)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?u_(r,s):s?.type==="date-time"?!o||np(o)?c_(r,s,n):r:a_(r,o,n)},lp=(t,e,r,o)=>{let n=t.fieldsIndex?.get(e),s=sp(e,r,t)??r;return ip(t,e,s,n?.type,o)},up=(t,e)=>ap(t,e),ra=(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=sp(l.name,d,t)??d,f=ap(t,l.name);u[f]=ip(t,l.name,p,l.type,r)}),u});return{objectIds:n,attributes:s}};var d_=(t,e,r)=>{let o=t.createQuery();return o.outFields=[e],o.where=r||"1=1",o.num=1,o},p_=async(t,e,r,o)=>{let n=o.map?.allLayers.find(d=>d.id===t),s=d_(n,e,r.where),a=(await n.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=lp(n,e,i,o.timeZone),l=up(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 m_({layerId:t,fieldName:e,query:r},o){let{mapView:n}=D(o,["mapView"]),s=await p_(t,e,r,n);return JSON.stringify(s,null,2)}var f_=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.")})}),cp=E(m_,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:f_});var Go=(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 _r(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Et=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};var __=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 yr(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(yr(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 Ko(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new y_({geometry:S.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let x=Go(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:_r(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[o]}};w=await h_(S);let h=["string","small-integer","integer"],I=l.domain?.type==="coded-value"?l.domain:null;(h.includes(l.type)||I)&&(b=(await g_({layer:i,useFeaturesInView:x,view:x?n:void 0,field:r,sqlWhere:_r(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 w_({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:o},n){let s=Et(n,"layersAndFieldsRegistry"),{mapView:a}=D(n,["mapView"]),i=kt(o,n.state?.agentExecutionContext?.sharedResources),u=await __({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:i});return JSON.stringify(u,null,2)}var b_=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:Ae.optional().describe("The units for the distance buffer.")}),A_=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:Ae.optional().describe("The units for the distance buffer.")}),x_=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([b_,A_,Ct]).optional().describe("Geometry filter for spatial queries. Use 'sharedResourceId' with an ID from listSharedResources for a previously geocoded location. Use 'point' for inline coordinates or 'layerId/where' for 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.")}),dp=E(w_,{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
|
|
@@ -86,7 +86,7 @@ DO NOT USE FOR:
|
|
|
86
86
|
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
87
87
|
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
88
88
|
|
|
89
|
-
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:__});var A_=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),x_=async(t,e,r,o,n)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(o){let f=await St(o,r);if("error"in f)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in o?o.where:"unknown criteria"}`}};u=f.geometry}else n&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new w_({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new b_({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=gr(s.definitionExpression,t.where||"1=1"),b.outFields=p.length?p:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),o?.distance&&(b.distance=o.distance),o?.units&&(b.units=o.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...A_(e.orderByFields)])],S=Bo(a,y,n??!1);try{f=S?await a.queryFeatures(b):await s.queryFeatures(b)}catch(h){console.warn("Client-side query failed, falling back to server:",h),f=await s.queryFeatures(b)}}let x=f.features.map(b=>b.attributes[d]),{attributes:w}=ea(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:x,objectIdField:d,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},I_=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:o},n)=>{let{mapView:s}=D(n,["mapView"]),a=await x_(t,e,s,r,o);return JSON.stringify(a,null,2)},v_=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.")}),T_=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.")}),S_=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."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([v_,T_]).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."),topFilter:c.object({topCount:c.number().describe("Number of top features to return per group."),orderByFields:c.array(c.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:c.array(c.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),cp=E(I_,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:S_});var qi=25,C_=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),k_=async(t,e,r,o)=>{let n=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(n),a=n.title??t.layerId,i;if(r){let y=await St(r,e);if("error"in y){let S={error:y.error};if(hr(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else qo(r)&&(S.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:S}}if(!y.geometry){let S={};if(hr(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.error=`No features found matching: ${r.where}`,S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else qo(r)&&(S.error="Failed to create point geometry",S.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:S}}i=y.geometry}else o&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...C_(t.orderByFields)])],l=Bo(s,u,o??!1),d=n.objectIdField,p=n.createQuery();p.where=gr(n.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],p.orderByFields=t.orderByFields,i&&(p.geometry=i,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let f,x;try{f=l?await s.queryFeatureCount(p):await n.queryFeatureCount(p),f>0&&f<=qi&&(x=l?await s.queryFeatures(p):await n.queryFeatures(p))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await n.queryFeatureCount(p),f>0&&f<=qi&&(x=await n.queryFeatures(p))}let{objectIds:w,attributes:b}=x?ea(n,x,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...w&&{objectIds:w,objectIdField:d},...b&&{attributes:b},...f>qi&&{note:`${f} features found.`}}}};async function E_({targetLayer:t,geometryFilter:e,useCurrentExtent:r},o){let{mapView:n}=D(o,["mapView"]),s=await k_(t,n,e,r);return JSON.stringify(s,null,2)}var M_=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.")}),O_=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("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([M_,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."),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),dp=E(E_,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
89
|
+
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:x_});var T_=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),S_=async(t,e,r,o,n)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(o){let f=await St(o,r);if("error"in f)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in o?o.where:"unknown criteria"}`}};u=f.geometry}else n&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new I_({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new v_({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=_r(s.definitionExpression,t.where||"1=1"),b.outFields=p.length?p:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),o?.distance&&(b.distance=o.distance),o?.units&&(b.units=o.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...T_(e.orderByFields)])],S=Go(a,y,n??!1);try{f=S?await a.queryFeatures(b):await s.queryFeatures(b)}catch(h){console.warn("Client-side query failed, falling back to server:",h),f=await s.queryFeatures(b)}}let x=f.features.map(b=>b.attributes[d]),{attributes:w}=ra(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:x,objectIdField:d,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},C_=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:o},n)=>{let{mapView:s}=D(n,["mapView"]),a=kt(r,n.state?.agentExecutionContext?.sharedResources),i=await S_(t,e,s,a,o);return JSON.stringify(i,null,2)},k_=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:Ae.optional().describe("The units for the distance buffer.")}),E_=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:Ae.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."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([k_,E_,Ct]).optional().describe("Geometry filter for spatial queries. Use 'sharedResourceId' with an ID from listSharedResources for a previously geocoded location. Use 'point' for inline coordinates or 'layerId/where' for features from another layer."),topFilter:c.object({topCount:c.number().describe("Number of top features to return per group."),orderByFields:c.array(c.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:c.array(c.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),pp=E(C_,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:M_});var Ki=25,P_=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),O_=async(t,e,r,o)=>{let n=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(n),a=n.title??t.layerId,i;if(r){let y=await St(r,e);if("error"in y){let S={error:y.error};if(yr(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else Ko(r)&&(S.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:S}}if(!y.geometry){let S={};if(yr(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.error=`No features found matching: ${r.where}`,S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else Ko(r)&&(S.error="Failed to create point geometry",S.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:S}}i=y.geometry}else o&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...P_(t.orderByFields)])],l=Go(s,u,o??!1),d=n.objectIdField,p=n.createQuery();p.where=_r(n.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],p.orderByFields=t.orderByFields,i&&(p.geometry=i,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let f,x;try{f=l?await s.queryFeatureCount(p):await n.queryFeatureCount(p),f>0&&f<=Ki&&(x=l?await s.queryFeatures(p):await n.queryFeatures(p))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await n.queryFeatureCount(p),f>0&&f<=Ki&&(x=await n.queryFeatures(p))}let{objectIds:w,attributes:b}=x?ra(n,x,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...w&&{objectIds:w,objectIdField:d},...b&&{attributes:b},...f>Ki&&{note:`${f} features found.`}}}};async function R_({targetLayer:t,geometryFilter:e,useCurrentExtent:r},o){let{mapView:n}=D(o,["mapView"]),s=kt(e,o.state?.agentExecutionContext?.sharedResources),a=await O_(t,n,s,r);return JSON.stringify(a,null,2)}var N_=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:Ae.optional().describe("The units for the distance buffer.")}),$_=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:Ae.optional().describe("The units for the distance buffer.")}),z_=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("SQL-92 where clause. IMPORTANT: When using geometryFilter.point or geometryFilter.sharedResourceId for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([N_,$_,Ct]).optional().describe("Geometry filter for spatial queries. Use 'sharedResourceId' with an ID from listSharedResources for a previously geocoded location. Use 'point' for inline coordinates or 'layerId/where' for features from another layer."),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),mp=E(R_,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
90
90
|
|
|
91
91
|
USE THIS TOOL FOR:
|
|
92
92
|
- "Show / display / list features where..." \u2014 finding and listing features
|
|
@@ -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:
|
|
98
|
+
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:z_});var jn=(t,e)=>e??t,aw=M.Root({...ns(),intent:M({reducer:jn}),vectorSearchLayerResults:M({reducer:jn,default:()=>[]}),vectorSearchFieldResults:M({reducer:jn}),navigationInternalState:M({reducer:jn,default:()=>({toolCallMessage:void 0})})}),_p=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 st(t){let e=Object.entries(_p).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
99
99
|
Available prompts:
|
|
100
|
-
${Object.keys(
|
|
101
|
-
`)}`);return await e[1]()}var
|
|
100
|
+
${Object.keys(_p).join(`
|
|
101
|
+
`)}`);return await e[1]()}var iw=M.Root({...Nt(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),queryResponse:M(),dataExplorationMessages:M({reducer:an,default:()=>[]})}),Ap=[cp,dp,pp,mp];var u4=new nt(Ap,{handleToolErrors:!1});async function lw(t){let{fields:e,layer:r,view:o,styleName:n,colorSchemeTags:s}=t,a;return s?a=j_({basemapTheme:await gp(o),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=D_({basemapTheme:await gp(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 uw(t){return await L_(t)}async function cw({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 lw(u),d=await uw(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 dw=["mapView"];function Pe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=dw.filter(o=>!(o in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function pw({layerId:t,fields:e,colorSchemes:r,includeSize:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await cw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:o})}var mw=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)")}),fw=E(pw,{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.
|
|
@@ -108,19 +108,19 @@ ${Object.keys(gp).join(`
|
|
|
108
108
|
Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
|
|
109
109
|
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
110
110
|
Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
|
|
111
|
-
Fields: This style requires 2-8 number fields.`,schema:
|
|
111
|
+
Fields: This style requires 2-8 number fields.`,schema:mw});function hw(t){let{fields:e,layer:r,view:o,theme:n,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Yi({geometryType:r.geometryType,includedTags:s,theme:n||"high-to-low"})[0]),{layer:r,view:o,startTime:a,endTime:new Date,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function gw(t){return await F_(t)}async function yw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,theme: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:"color-age",fields:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=hw(u),d=await gw(l);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function _w({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await yw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var ww=c.object({layerId:c.string().describe("The id of the layer to apply the color-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),bw=E(_w,{name:"color-age",description:`Label: Age (color)
|
|
112
112
|
Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
113
113
|
Keywords: since, age, how old, how long
|
|
114
114
|
Example: Show the age of each feature based on its reported date.
|
|
115
|
-
Fields: This style requires at least one field with a date type.`,schema:
|
|
115
|
+
Fields: This style requires at least one field with a date type.`,schema:ww});function Aw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,{theme:s}=t,a=e[1],i=e[0],u;return n&&(u=Yi({geometryType:r.geometryType,includedTags:n,theme:s||"high-to-low"})[0]),{layer:r,view:o,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function xw(t){return await U_(t)}async function Iw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,theme: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:"color",fields:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=Aw(u),d=await xw(l);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function vw({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await Iw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var Tw=c.object({layerId:c.string().describe("The id of the layer to apply the color renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Sw=E(vw,{name:"color",description:`Label: Counts and Amounts (color)
|
|
116
116
|
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
117
117
|
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
118
118
|
Example: Color each feature based on the population density.
|
|
119
|
-
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:
|
|
119
|
+
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:Tw});function Cw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n,theme:s}=t,a,i,u=e[0];return n&&(i=Yi({geometryType:r.geometryType,includedTags:n,theme:s||"high-to-low"})[0]),{layer:r,view:o,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function kw(t){return await q_(t)}async function Ew({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,theme: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:"color-size-univariate",fields:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=Cw(u),d=await kw(l);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function Mw({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await Ew({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var Pw=c.object({layerId:c.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:c.array(c.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Ow=E(Mw,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
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:
|
|
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:Pw});function Rw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s;return n&&(s=K_({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 Nw(t){return await B_(t)}async function $w({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=Rw(i),l=await Nw(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 zw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Pe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await $w({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var Lw=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")}),jw=E(zw,{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:
|
|
134
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:Lw});function Dw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s,a=e[0];return n&&(s=V_({includedTags:n,basemap:o.map?.basemap||"topo"})[0]),{layer:r,view:o,field:a,heatmapScheme:s}}async function Fw(t){return await G_(t)}async function Uw({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=Dw(i),l=await Fw(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 qw({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Pe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await Uw({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var Bw=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")}),Kw=E(qw,{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:Bw});function Gw(t){let{fields:e,layer:r,view:o,styleName:n,colorSchemeTags:s}=t,a;return s&&(a=H_({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 Vw(t){return await W_(t)}async function Ww({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=Gw(u),d=await Vw(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 Hw({layerId:t,fields:e,colorSchemes:r,includeSize:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await Ww({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:o})}var Jw=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)")}),Zw=E(Hw,{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.
|
|
@@ -145,15 +145,15 @@ Fields: This typically requires zero or one field of type number.`,schema:Dw});f
|
|
|
145
145
|
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
|
|
146
146
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
147
147
|
Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
|
|
148
|
-
Fields: This style relies on 2-10 number fields.`,schema:
|
|
148
|
+
Fields: This style relies on 2-10 number fields.`,schema:Jw});function Qw(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s,a={field:e[0]},i={field:e[1]};return n&&(s=Z_({geometryType:r.geometryType,includedTags:n})[0]),{layer:r,view:o,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function Yw(t){return await J_(t)}async function Xw({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:"relationship",fields:o,layer:a,view:s,colorSchemeTags:n};try{let u=Qw(i),l=await Yw(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${o.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function eb({layerId:t,fields:e,colorSchemes:r},o){let{mapView:n}=Pe(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await Xw({arcgisMap:n.map,arcgisMapView:n,layerId:t,fields:e,colorSchemes:r})}var tb=c.object({layerId:c.string().describe("The id of the layer to apply the relationship renderer to"),fields:c.array(c.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),rb=E(eb,{name:"relationship",description:`Label: Relationship
|
|
149
149
|
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
150
150
|
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
151
151
|
Example: Show the relationship between tree height and carbon storage
|
|
152
|
-
Fields: This style requires two number fields.`,schema:
|
|
152
|
+
Fields: This style requires two number fields.`,schema:tb});function ob(t){let{fields:e,layer:r,view:o,theme:n}=t,s=e[0];return{layer:r,view:o,startTime:s,endTime:new Date,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function nb(t){return await Q_(t)}async function sb({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,theme: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:"size-age",fields:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=ob(u),d=await nb(l);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function ab({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await sb({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var ib=c.object({layerId:c.string().describe("The id of the layer to apply the size-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),lb=E(ab,{name:"size-age",description:`Label: Age (size)
|
|
153
153
|
Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
154
154
|
Keywords: since, age, how old, how long
|
|
155
155
|
Example: Change the size of features so older features are larger than new features.
|
|
156
|
-
Fields: This style requires at least one field with a date type.`,schema:
|
|
156
|
+
Fields: This style requires at least one field with a date type.`,schema:ib});function ub(t){let{fields:e,layer:r,view:o}=t,{theme:n}=t,s=e[1],a=e[0];return{layer:r,view:o,field:a,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function cb(t){return await Y_(t)}async function db({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,theme: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:"size",fields:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=ub(u),d=await cb(l);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function pb({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await db({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var mb=c.object({layerId:c.string().describe("The id of the layer to apply the size renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),fb=E(pb,{name:"size",description:`Label: Counts and Amounts (size)
|
|
157
157
|
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
158
158
|
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
159
159
|
Example: Vary the size of each point based on the total population.
|
|
@@ -163,27 +163,27 @@ Fields: This typically requires zero or one field of type number.`,schema:Dw});f
|
|
|
163
163
|
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
164
164
|
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
165
165
|
Example: Vary the size of each feature based on the date a ticket was completed.
|
|
166
|
-
Fields: This style requires a single field with a date type.`,schema:
|
|
166
|
+
Fields: This style requires a single field with a date type.`,schema:mb});function hb(t){let{fields:e,layer:r,view:o,colorSchemeTags:n}=t,s=e[0],a=e[1],i=e[2],u;return n&&(u=ew({geometryType:r.geometryType,includedTags:n})[0]),{layer:r,view:o,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function gb(t){return await X_(t)}async function yb({arcgisMap:t,arcgisMapView:e,layerId:r,fields:o,colorSchemes:n,theme: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:"type",fields:o,layer:i,view:a,colorSchemeTags:n,theme:s};try{let l=hb(u),d=await gb(l);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${o.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function _b({layerId:t,fields:e,colorSchemes:r,theme:o},n){let{mapView:s}=Pe(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await yb({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:o})}var wb=c.object({layerId:c.string().describe("The id of the layer to apply the type renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),bb=E(_b,{name:"type",description:`Label: Types (unique symbols)
|
|
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:
|
|
171
|
-
Relationship Types: ${o}.`}},
|
|
170
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:wb}),Ab=M.Root({...Nt(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),selectedLayerId:M()}),xb=M.Root({...Nt(),helpInternalState:M({reducer:jn,default:()=>({toolCallMessage:void 0})})}),Ib=M.Root({...Nt(),intent:M({reducer:(t,e)=>e}),arcgisKnowledgeMessages:M({reducer:an,default:()=>[]}),arcgisKnowledgeToolResult:M({reducer:(t,e)=>e,default:()=>null})});function xp(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 Jo(t){return!!t?.map&&"activeLinkChartLayer"in t.map}async function aa(t){!Jo(t)||!t.map.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Fn(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)&&xp(r),{view:r}}async function Zo(t){let e=t?.configurable?.context;if(vb(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 yp(o)}}else{xp(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 yp(o)}}}}function vb(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 Gi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=sa.fromDataModel(e)}},sa=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(Dn.fromEntityType(o));for(let o of e.relationshipTypes)r.relationshipTypes.push(Vi.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:Tb(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
|
+
Relationship Types: ${o}.`}},Dn=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=Sb(e.role);for(let o of e.properties){let n={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:Cb(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}},Vi=class extends Dn{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Dn.fromEntityType(e);r.observedEndPoints=[];for(let o of e.endPoints)r.observedEndPoints.push({originEntityType:o.originEntityType,destinationEntityType:o.destinationEntityType});return r}},Tb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Sb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Cb(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 ia(t){return t?.signal}async function kb(t,e){let r=await st("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.
|
|
174
174
|
|
|
175
175
|
Attempt Number: ${e.attemptCount}
|
|
176
176
|
Execution Error: ${e.executionError}
|
|
177
177
|
Failed Query:
|
|
178
|
-
${e.failedGraphQuery}`:`${t} ${r}`}async function
|
|
178
|
+
${e.failedGraphQuery}`:`${t} ${r}`}async function Eb(t,e,r,o){let{graphQuery:n,explanation:s}=await Xi(t,e,r,o);return{graphQuery:n,explanation:s}}async function Xi(t,e,r,o,n){let s={message:await kb(t,n),context:new Gi(e)},a=ia(o);await Z({text:"Attempting to generate a cypher query from your prompt..."},o);let i=await hp(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json","X-Esri-Authorization":`Bearer ${fp.findCredential(Ho.getDefault().url)?.token??""}`},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),d=i.data.sequenceNumber,p="",f="",x=1;for(;!u;){await new Promise(b=>setTimeout(b,1e3)),await Z({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,x)}`},o),x=x%3+1;let w=await hp(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json","X-Esri-Authorization":`Bearer ${fp.findCredential(Ho.getDefault().url)?.token??""}`},signal:a});if(w.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${w.httpStatus}`,{cause:w.data});if(w.data.context?.kind){if(w.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${w.data.message}`,{cause:w.data});p=w.data.context.graphQuery,f=w.data.message||"",u=!0}else if(!w.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=w.data.sequenceNumber}return{graphQuery:p,explanation:f}}function Mb(t,e){Vo(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Vo(t,e){if(!(!t||typeof t!="object")){if(Ob(t))for(let r of t.path)Vo(r,e);else if(Pb(t))e(t);else if(Array.isArray(t))for(let r of t)Vo(r,e);else if(Rb(t))for(let r of Object.values(t.properties??{}))Vo(r,e)}}function Pb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Ob(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Rb(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Nb(t,e){let r=[],o=[],n=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,o]];for(let[s,a]of n)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:o}}function $b(t,e){let r={entityIds:new Array,relationshipIds:new Array},o=[],n=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!n)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:o};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let d=n.namedTypeDefinitions.get(l.name);if(!d){a=!1,o.push(l.name);continue}if(!d.useAllData){a=!1,o.push(l.name);for(let[p]of d.members||[])u.push(p)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:o}}var Wo=3;function Ip(t,e=100){let r={};for(let o of Object.entries(t.properties??{})){let[n,s]=o;typeof s=="string"&&s.length>e?r[n]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[n]=s}return t.properties=r,t}function Qo(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var zb=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:o,requestOptions:n,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,d=n?.signal,p=()=>{l.abort(d?.reason)};d&&(d.aborted?l.abort(d.reason):d.addEventListener("abort",p,{once:!0}));try{let f=await rw(t,e,n);i=f.resultHeader;let x=f.resultRowsStream.getReader(),w=0,b=Date.now(),y=!1;for(;;){let{done:S,value:h}=await x.read();if(S)break;if(!y&&a&&Date.now()-b>a)return l.abort(),{type:"timeout"};for(let I of h){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=o(u,I)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Qo(f),error:f}}finally{d?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function vp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:o,targetStructure:n,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let d;for(let p=1;p<=Wo;p++){let f;try{f=await Xi(t,r.dataModel,o,l,d)}catch(y){return{type:"generation-error",errorMessage:Qo(y),error:y}}await Z({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let x=await Lb(f.graphQuery,e),w=await zb({kg:r,queryParams:new bp({openCypherQuery:f.graphQuery,bindParameters:x}),targetStructure:n,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),b=w.type==="aborted"?"Query execution was aborted.":w.type==="timeout"?"Query execution timed out.":w.type==="error"?`Query failed with error: ${w.errorMessage}`:"";if(w.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:w.rowLimitReached,resultHeader:w.resultHeader,processedResult:w.processedResult};if(w.type==="aborted")return{type:"aborted",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation};if(p>=Wo)return w.type==="timeout"?{type:"timeout",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:b,error:w.error,graphQuery:f.graphQuery,explanation:f.explanation};d={failedGraphQuery:f.graphQuery,executionError:b,attemptCount:p},await Z({text:`Attempt ${p} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Wo} attempts.`)}var Lb=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:o}=await sw(t);if(o)return e;let n={};for(let s of r)s in e&&(n[s]=e[s]);return n},jb=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:o,searchResultLimit:n,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=n??1/0;try{for(let l of i){let d=u-a.length;if(d<=0)break;let p=(await ow(t,new nw({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:o??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:x,value:w}=await p.read();if(x){f=!0;break}for(let b of w)for(let y of b)a.push(y)}}}catch(l){let d=Qo(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},Tp="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Sp({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:o=!1}){let n=[t];if(o&&n.push(Tp),Jo(e)){let d=await st("arcgis_knowledge_current_lc_context"),p=Nb(e.map,r);return n.push(d),{enhancedPrompt:n.join(`
|
|
179
179
|
|
|
180
|
-
`),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}
|
|
180
|
+
`),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=$b(s,r);if(a)return{enhancedPrompt:n.join(`
|
|
181
181
|
|
|
182
182
|
`),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await st("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return n.push(l),{enhancedPrompt:n.join(`
|
|
183
183
|
|
|
184
|
-
`),bindParameters:i,allNamedTypesFullyDynamic:a}}async function
|
|
184
|
+
`),bindParameters:i,allNamedTypesFullyDynamic:a}}async function Db(t,e,r,o,n,s){let{view:a}=n,i=await vp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:o,targetStructure:new Map,targetStructureReducer:(f,x)=>{for(let w of x)Mb(w,f);return f},requestOptions:{signal:ia(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let f=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:u,explanation:l,processedResult:d}=i,p=Array.from(d.values());return await Z({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),Jo(a)?(await a.map.addRecords(p),await aa(a),{generatedQuery:u,explanation:l,addedIdTypePairs:p}):(await a?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(p),{generatedQuery:u,explanation:l,addedIdTypePairs:p})}var oa="addRecords",Fb=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 add records to the link chart.")}),Ub=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Zo(e),o=Fn(e),{view:n}=o,s=Ho.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await Sp({prompt:t,view:n,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:oa,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:d,addedIdTypePairs:p}=await Db(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,o,e);return{toolName:oa,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
|
|
185
185
|
|
|
186
|
-
Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:p}}}catch(l){let d=
|
|
186
|
+
Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:p}}}catch(l){let d=Qo(l);return{toolName:oa,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},qb=E(Ub,{name:oa,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
|
|
187
187
|
|
|
188
188
|
example prompts:
|
|
189
189
|
- "add all suppliers and the parts they produce to the link chart"
|
|
@@ -193,15 +193,15 @@ 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:
|
|
196
|
+
`,schema:Fb});async function Bb(t,e){return await e.map?.applyLayout(t),await aa(e),{appliedLayout:t}}var Wi="applyLayout",Kb=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")}),Gb=async({layout:t},e)=>{let{view:r}=Fn(e);if(Jo(r)){let{appliedLayout:o}=await Bb(t,r);return{toolName:Wi,status:"success",summary:`Successfully applied layout: ${o}.`,details:{appliedLayout:o}}}else return{toolName:Wi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error}},Vb=E(Gb,{name:Wi,description:"Apply a diagram layout to the link chart",schema:Kb});async function Wb(t,e){return e.map?.changeNonspatialDataDisplay(t),await aa(e),{appliedNonspatialDataDisplayMode:t}}var Hi="changeNonspatialVisibility",Hb=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Jb=async({setting:t},e)=>{let{view:r}=Fn(e);if(Jo(r)){let{appliedNonspatialDataDisplayMode:o}=await Wb(t,r);return{toolName:Hi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${o}.`,details:{appliedNonspatialDataDisplayMode:o}}}else return{toolName:Hi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error}},Zb=E(Jb,{name:Hi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Hb});async function Qb(t,e,r,o,n){let s,a="";for(let i=1;i<=Wo;i++){let{graphQuery:u,explanation:l}=await Xi(t,e.dataModel,r,n,s);try{await Z({text:`Attempting to create link chart from derived query: ${u}`},n);let d=await tw.fromCypherQuery(e,new bp({openCypherQuery:u}));await Z({text:"Link chart created successfully, loading..."},n),await d.load();let p=o.map;return o.map=d,await o.when(),await wp.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
|
-
Explanation: ${l}`}):(await
|
|
199
|
+
Explanation: ${l}`}):(await aa(o),{type:"success",graphQuery:u,explanation:l})}catch(d){let p=Qo(d);if(i>=Wo){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await Z({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},n)}}return{type:"error",errorMessage:`Failed to create link chart after ${Wo} attempts. Last error: ${a}`}}var na="createLinkChart",Yb=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.")}),Xb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Zo(e),{view:o}=Fn(e);if(Jo(o)){let n=Ho.getDefault().helperServices,s=await Qb(`${t}
|
|
200
200
|
|
|
201
|
-
${
|
|
201
|
+
${Tp}`,r,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,o,e);if(s.type==="error")return{toolName:na,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:na,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
|
|
202
202
|
${a}
|
|
203
203
|
|
|
204
|
-
Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}else return{toolName:
|
|
204
|
+
Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}else return{toolName:na,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error}},eA=E(Xb,{name:na,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:Yb}),Ji="queryGraphData",tA=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),rA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Zo(e),o=Ho.getDefault().helperServices,n=t,s=null,a=null;try{({view:a}=Fn(e))}catch{}a&&({enhancedPrompt:n,bindParameters:s}=await Sp({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await vp({prompt:n,bindParameters:s,kg:r,graphQueryServiceUrl:`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,y)=>(b.push(y),b),requestOptions:{signal:ia(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let b=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:Ji,status:"error",errorMessage:`Failed to query the knowledge graph. ${b}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:d,resultHeader:p}=i,f=p.headerKeys;for(let b of d)for(let y of b)Vo(y,S=>Ip(S));let x=50,w=d.slice(0,x).map(b=>JSON.stringify(b));return{toolName:Ji,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
205
205
|
|
|
206
206
|
\`\`\`cypher
|
|
207
207
|
${u}
|
|
@@ -218,16 +218,16 @@ ${w.length>x?`Showing top ${x} results:
|
|
|
218
218
|
|
|
219
219
|
`}${w.join(`
|
|
220
220
|
`)}
|
|
221
|
-
`,details:{generatedQuery:u,explanation:l,resultHeader:{headerKeys:f,exceededTransferLimit:p.exceededTransferLimit,outSpatialReference:p.outSpatialReference},queryResults:d}}},
|
|
221
|
+
`,details:{generatedQuery:u,explanation:l,resultHeader:{headerKeys:f,exceededTransferLimit:p.exceededTransferLimit,outSpatialReference:p.outSpatialReference},queryResults:d}}},oA=E(rA,{name:Ji,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:tA}),Zi="generateCypher",nA=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),sA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Zo(e),o=Ho.getDefault().helperServices;try{let{graphQuery:n,explanation:s}=await Eb(t,r.dataModel,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Zi,status:"success",summary:`Generated Graph Query:
|
|
222
222
|
${n}
|
|
223
223
|
|
|
224
|
-
Explanation: ${s}`,details:{generatedQuery:n,explanation:s}}}catch(n){let s=
|
|
224
|
+
Explanation: ${s}`,details:{generatedQuery:n,explanation:s}}}catch(n){let s=Qo(n);return{toolName:Zi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:n}}},aA=E(sA,{name:Zi,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:nA}),iA=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let d=r.get(u)??new Set;l.propertyNames.forEach(p=>d.add(p)),r.set(u,d)}let o=e.entityTypes.filter(i=>r.has(i.name)),n=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
|
|
225
225
|
${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
226
226
|
`)}`,a=`Relationship Types:
|
|
227
227
|
${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
228
228
|
`)}`;return`${s}
|
|
229
229
|
|
|
230
|
-
${a}`};async function
|
|
230
|
+
${a}`};async function lA(t,e,r){let o=await st("arcgis_knowledge_lucene_generation_prompt"),n={inquiry:t,dataModelForSearch:iA(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 Ln({promptText:o,inputVariables:n,schema:u,config:r})}var Qi="searchGraphData",uA=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.")}),cA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Zo(e);await Z({text:"Generating search query for the user inquiry"},e);let o=await lA(t,r,e);await Z({text:"Executing graph search with generated search query"},e);let n=await jb({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:ia(e),timeout:e?.timeout}});if(n.type!=="success")return{toolName:Qi,status:"error",errorMessage:n.errorMessage,error:"error"in n?n.error:null};for(let i of n.results)Vo(i,u=>Ip(u));let s=10,a=n.results.slice(0,s);return{toolName:Qi,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"}
|
|
@@ -238,7 +238,7 @@ ${a}`};async function nA(t,e,r){let o=await st("arcgis_knowledge_lucene_generati
|
|
|
238
238
|
${n.results.length>s?`Showing top ${s} results:
|
|
239
239
|
|
|
240
240
|
`:""}${a.map(i=>JSON.stringify(i)).join(`
|
|
241
|
-
`)}`,details:{generatedSearchQuery:o,searchResults:n.results}}},
|
|
241
|
+
`)}`,details:{generatedSearchQuery:o,searchResults:n.results}}},dA=E(cA,{name:Qi,description:`
|
|
242
242
|
Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
|
|
243
243
|
Example prompts:
|
|
244
244
|
- "Find 'Bradley'"
|
|
@@ -247,7 +247,7 @@ ${a}`};async function nA(t,e,r){let o=await st("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:
|
|
250
|
+
- "Search for all john smiths and show their global ids`,schema:uA});async function gA(t,e){let r=mA.getDefault().helperServices,o=r.geocode.find(p=>p.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let n=o.url,s=`${el.assetsPath?.endsWith("/")?el.assetsPath:`${el.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await fA(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 hA({url:s,width:24,height:24}),u=new pA({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??t,location:a.location.toJSON(),extent:a.extent.toJSON()},d={value:l,sharedStatePatch:{lastResolvedLocation:{value:l}},sharedResourceAdditions:[{kind:"point",description:l.address,payload:l.location}]};return[`Successfully zoomed to ${l.address}.`,d]}async function yA({address:t},e){let{mapView:r}=D(e,["mapView"]);return await gA(t,r)}var _A=c.object({address:c.string().describe("The full address or place name to locate.")}),wA=E(yA,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:_A,responseFormat:"content_and_artifact"});async function bA(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 AA({bookmarkName:t},e){let{mapView:r}=D(e,["mapView"]);return await Promise.resolve(bA(t,r))}var xA=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),IA=E(AA,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:xA});async function vA(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 TA({layerId:t,where:e},r){let{mapView:o}=D(r,["mapView"]);return await vA(t,e,o)}var SA=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.")}),CA=E(TA,{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:SA});async function EA(t){let e=new kA({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 MA(t,e){let{mapView:r}=D(e,["mapView"]);return await EA(r)}var PA=v.object({}),OA=E(MA,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:PA});async function RA(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 NA(t,e){let{mapView:r}=D(e,["mapView"]);return await RA(r)}var $A=c.object({}),zA=E(NA,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:$A});async function LA(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 jA({layerId:t},e){let{mapView:r}=D(e,["mapView"]);return await LA(t,r)}var DA=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),FA=E(jA,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:DA});async function UA(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function qA({scale:t},e){let{mapView:r}=D(e,["mapView"]);return await UA(t,r)}var BA=c.object({scale:c.number().describe("The map scale of the view to go to.")}),KA=E(qA,{name:"goToScale",description:"Go to the specified view scale.",schema:BA});async function VA(t,e,r){let o={target:new GA({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 WA({center:t,zoom:e,scale:r},o){let{mapView:n}=D(o,["mapView"]);return await VA(t,n,{zoom:e,scale:r})}var HA=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.")}),JA=E(WA,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:HA});async function ZA(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 ZA(t,r)}var YA=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),XA=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:YA});var qJ=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 nA(t,e,r){let o=await st("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 i3=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 j3=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”_
|
|
@@ -280,10 +280,10 @@ ${a}`};async function nA(t,e,r){let o=await st("arcgis_knowledge_lucene_generati
|
|
|
280
280
|
_Example: “What’s the average population?”_
|
|
281
281
|
_Example: “Which values are in the status field?”_
|
|
282
282
|
|
|
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
|
|
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 ex=(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}`},
|
|
286
|
+
${n}`},tx=({layerTitle:t},e)=>{let r=Et(e,"layersAndFieldsRegistry");return ex(r,t)},rx=E(tx,{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 u5=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}`},QA=({layerTitle:t},e)=>{let r=Ct(e,"layersAndFieldsRegistry");return ZA(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 k5=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 Oe
|
|
337
|
+
_example: "What is the average age of all people who work for Esri?"_`;var Oe=Ln;var G=Z,kp=Yd;var Yo=()=>ns(),ua=async(t,e)=>await fe(t,e),ca=async({modelTier:t="default",config:e}={})=>await qi({modelTier:t,config:e});var em=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function wr(t){if(!em(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var sx=`
|
|
338
338
|
Write a concise, friendly success message for adding members to a group.
|
|
339
339
|
|
|
340
340
|
Rules:
|
|
@@ -349,12 +349,12 @@ Added members:
|
|
|
349
349
|
|
|
350
350
|
Not added members:
|
|
351
351
|
{notAddedMembers}
|
|
352
|
-
`,
|
|
352
|
+
`,ax=t=>t.map(e=>`"${e}"`).join(", "),ix=c.object({successMessage:c.string().default("")}),Pp="portal-group-creation",Op="approveAddMembers",lx=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let o=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!o.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let n=`The following member(s) will be added to the newly created group:
|
|
353
353
|
|
|
354
354
|
${o.map(p=>`- **@${p}**`).join(`
|
|
355
355
|
`)}
|
|
356
356
|
|
|
357
|
-
Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==
|
|
357
|
+
Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Pp||s.id!==Op){let p={agentId:Pp,id:Op,kind:"booleanChoice",message:n,metadata:{action:"addMembers",groupId:r,members:[...o]}};throw new on(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await G({text:`Adding members ${ax(o)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;wr(a);let{result:i,error:u}=await Kl(a.portal,r,o);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:d}=i;try{let p=(await Oe({promptText:sx,schema:ix,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},ux=`
|
|
358
358
|
Write a concise, friendly success message after creating a portal group.
|
|
359
359
|
|
|
360
360
|
Rules:
|
|
@@ -365,7 +365,7 @@ Rules:
|
|
|
365
365
|
|
|
366
366
|
Group title:
|
|
367
367
|
{groupTitle}
|
|
368
|
-
`,
|
|
368
|
+
`,cx=`
|
|
369
369
|
Write a concise, friendly failure message after an attempt to create a portal group.
|
|
370
370
|
|
|
371
371
|
Rules:
|
|
@@ -380,7 +380,7 @@ Group title:
|
|
|
380
380
|
|
|
381
381
|
Failure reason:
|
|
382
382
|
{failureReason}
|
|
383
|
-
`,
|
|
383
|
+
`,Rp="portal-group-creation",Np="approveCreateGroup",dx=c.object({successMessage:c.string().default("")}),px=c.object({failureMessage:c.string().default("")}),mx=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let o=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:n}=e?.configurable;if(n?.agentId!==Rp||n.id!==Np){let l={agentId:Rp,id:Np,kind:"booleanChoice",message:o,metadata:{action:"createGroup",title:r,access:"private"}};throw new on(l)}if(n.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await G({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;wr(s);let{result:a,error:i}=await Bl(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let d=(await Oe({promptText:cx,schema:px,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(d)return{status:"success",outputMessage:d}}catch(d){console.error("Error generating create-group failure message:",d)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Oe({promptText:ux,schema:dx,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},qe=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let o=r.content;if(typeof o=="string")return o;if(Array.isArray(o))return o.map(n=>typeof n=="string"?n:"text"in n&&typeof n.text=="string"?n.text:"").join(" ").trim()}return""},fx=`
|
|
384
384
|
You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
|
|
385
385
|
|
|
386
386
|
Rules:
|
|
@@ -406,17 +406,17 @@ Examples:
|
|
|
406
406
|
|
|
407
407
|
User message:
|
|
408
408
|
{userMessage}
|
|
409
|
-
`,
|
|
409
|
+
`,hx=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),gx=async(t,e)=>{await G({text:"Thinking about groups...",agentName:"group-creation"},e);let r=qe(t.agentExecutionContext.messages).trim(),o=await Oe({promptText:fx,schema:hx,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:""}},yx=["general","about","homePage","gallery","aiAssistants","map","items","groups","webhooks","utilityServices","agol","esriContent","livingAtlas","servers","memberRoles","newMemberDefaults","marketplace","collaborations","credits","security","openData","hub","orgExtensions"],_x=["newItem","createLayer","developerCredentials"],wx=["favorites","group","living-atlas","org"],bx=["featured","my","organization"],Ax=["overview","content","members","settings"],xx=["licenses","members","overview","reports","settings","status"],Ix=c.object({destinationType:c.literal("portal-content"),hash:c.enum(wx).optional(),queryParams:c.object({newItem:c.enum(_x).optional()}).optional()}),vx=c.object({destinationType:c.literal("portal-groups"),hash:c.enum(bx).optional()}),Tx=c.object({destinationType:c.literal("portal-org"),hash:c.enum(xx).optional(),queryParams:c.object({tab:c.enum(yx).optional(),section:c.string().optional(),subsection:c.string().optional(),period:c.string().optional(),startTime:c.string().optional(),endTime:c.string().optional()}).optional()}),Sx=c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),Cx=c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1),hash:c.enum(Ax).optional(),queryParams:c.record(c.string(),c.string()).optional()}),kx=c.union([Ix,c.object({destinationType:c.literal("portal-gallery")}),Cx,vx,Sx,c.object({destinationType:c.literal("portal-map-viewer")}),c.object({destinationType:c.literal("portal-notebooks")}),Tx,c.object({destinationType:c.literal("portal-scene-viewer")})]),tm="portal-navigation",ha=async(t,e)=>{let r=e?.configurable?.context;!em(r)||!r.navigationTargetMap?.[t.destinationType]||await ua({type:tm,data:{...t}},e)},Ex=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await G({text:"Preparing navigation...",agentName:"group-creation"},e),await ha({destinationType:"portal-group",groupId:r},e),{}):{}},$p=(t,e)=>e??t,rm=M.Root({...Yo(),intentParams:M({reducer:$p,default:()=>({intent:"clarify"})}),createdGroupId:M({reducer:$p,default:()=>""})}),Mx=()=>new ce(rm).addNode("detectGroupCreationIntent",gx).addNode("createPortalGroup",mx).addNode("addMembersToPortalGroup",lx).addNode("suggestCreatedGroupNavigation",Ex).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),Px=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
|
-
`,
|
|
413
|
-
`)}var
|
|
412
|
+
`,Ox={id:"portal-group-creation",name:"Portal Group Creation",description:Px,createGraph:Mx,workspace:rm},om="portalDocAssistantMemory",Rx=()=>({conversationId:""}),Nx=t=>{let e=t?.[om]?.value;if(!e||typeof e!="object")return Rx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},$x=t=>({[om]:{value:t}}),zx={pipeline:{follow_up:{allow:!1}}};function Lx(t){return{kind:"DocAIAssistantRequest",filters:{...zx,persona:{persona:t}}}}var jx="https://www.arcgis.com/sharing/rest";async function Dx({portal:t,question:e,persona:r,previousConversationId:o,useProdDocAssistant:n,signal:s,skillId:a}){a??="doc_ai_assistant";let i=Lx(r),u=await Fx({portal:t,skillId:a,message:e,options:{context:i,previousConversationId:o,useProdDocAssistant:n,signal:s}});return{reply:Ux(u,a),conversationId:u[0]?.conversationId??""}}async function Fx({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 Ep.getCredential(jx,{oAuthPopupConfirmation:!1})).token:Ep.findCredential(t.url)?.token??""},i=await Mp(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 bl(500);let b=await Mp(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 Ux(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 rn(e)}}var qx=async(t,e)=>{let r=performance.now();try{await G({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let o=qe(t.agentExecutionContext.messages).trim();if(!o)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;wr(n);let s=Nx(t.agentExecutionContext.sharedState),{reply:a,conversationId:i}=await Dx({portal:n.portal,question:o,previousConversationId:s.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online",useProdDocAssistant:n.useProdDocAssistant});return{status:"success",outputMessage:a.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:$x({conversationId:i||s.conversationId})}}finally{console.info("[arcgis-portal-ai-assistant] node timing",{agent:"portal-doc-assistant",node:"answerDocQuestion",durationMs:Number((performance.now()-r).toFixed(1))})}},nm=E(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;wr(o);try{return(await ql(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.")})}),sm=E(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let o=e?.configurable?.context;wr(o);let{result:n,error:s}=await Gl(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 qn(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 Bx(t){let e=Bn(t).flatMap(r=>{let o=r,n=t[r],s=[o,{description:n.description,hints:n.hints}],a=n.sections?Bn(n.sections).map(i=>{let u=n.sections?.[i];return[`${o}-${i}`,u]}):[];return[s,...a]});return Object.fromEntries(e)}function Kx(t){return Object.entries(t).map(([e,{description:r,hints:o}])=>` - ${e}: ${r} (hints: ${o.join(", ")})`).join(`
|
|
413
|
+
`)}var Gx={"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"]}}}},am=Bx(Gx),Vx=Bn(am),Wx=Kx(am),Hx=`
|
|
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:
|
|
417
417
|
- Decide if a navigation action would help the user complete the task.
|
|
418
418
|
- If yes, choose one destinationType:
|
|
419
|
-
${
|
|
419
|
+
${Wx}
|
|
420
420
|
|
|
421
421
|
Rules:
|
|
422
422
|
- Only suggest navigation when you are highly confident the destination will help complete the user's task.
|
|
@@ -439,20 +439,20 @@ User question:
|
|
|
439
439
|
|
|
440
440
|
Assistant response:
|
|
441
441
|
{response}
|
|
442
|
-
`,
|
|
442
|
+
`,zp=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...Vx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),Lp;async function Jx(){return Lp??=ca({modelTier:"fast"}),await Lp}var Zx=async(t,e)=>{let r=performance.now();try{await G({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let o=t.outputMessage.trim();if(!o)return{};let n=qe(t.agentExecutionContext.messages).trim(),s=await Ar.fromTemplate(Hx).format({question:n,response:o}),a=(await Jx()).withStructuredOutput(zp),i=zp.parse(await a.invoke(s));if(!i.shouldSuggestNavigation||i.destinationType==="none")return{};if(i.destinationType==="portal-item"&&!i.itemId){let l=qn(n,"#");l&&(i.itemId=await sm.invoke({itemTitle:l},e)??"")}if(i.destinationType==="portal-group"&&!i.groupId){let l=qn(n,"$")??qn(n,"#");l&&(i.groupId=await nm.invoke({groupTitle:l},e)??"")}let u=Qx(i);return u?(await ha(u,e),{}):{}}finally{console.info("[arcgis-portal-ai-assistant] node timing",{agent:"portal-doc-assistant",node:"extractNavigationIntent",durationMs:Number((performance.now()-r).toFixed(1))})}};function Qx({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:Yx[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:Xx[t]};case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":return{destinationType:"portal-groups",hash:eI[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:tI[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 rn(t)}}var Yx={"portal-content-new-item":"newItem","portal-content-new-item-feature-layer":"createLayer","portal-content-new-item-developer-credentials":"developerCredentials"},Xx={"portal-content-favorites":"favorites","portal-content-group":"group","portal-content-living-atlas":"living-atlas","portal-content-organization":"org"},eI={"portal-groups-featured":"featured","portal-groups-my":"my","portal-groups-organization":"organization"},tI={"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"},im=M.Root({...Yo()}),rI=()=>new ce(im).addNode("answerDocQuestion",qx).addNode("extractNavigationIntent",Zx).addEdge(ue,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",K),oI=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
|
+
`,nI={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:oI,createGraph:rI,workspace:im},sI=()=>({latestGroupId:null,memory:{}}),ga=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:sI()},lm=`
|
|
446
446
|
Shared markdown formatting rules:
|
|
447
447
|
- Use clear markdown headings (##) to separate sections.
|
|
448
448
|
- Use concise bullet points for lists of facts, counts, or signals.
|
|
449
449
|
- Emphasize key metrics with bold labels (for example: **Recent items:** 4).
|
|
450
450
|
- Keep wording direct and analytical; avoid filler language but make sure the language is friendly.
|
|
451
451
|
- Do not include raw internal IDs unless explicitly requested.
|
|
452
|
-
`,
|
|
452
|
+
`,aI=`
|
|
453
453
|
You answer follow-up questions about ArcGIS group analytics.
|
|
454
454
|
|
|
455
|
-
${
|
|
455
|
+
${lm}
|
|
456
456
|
|
|
457
457
|
Ground your answer in the provided group analytics summary and context.
|
|
458
458
|
If the answer is not available from the provided context, state that clearly and suggest what to check next.
|
|
@@ -474,7 +474,7 @@ Group full context:
|
|
|
474
474
|
|
|
475
475
|
Question:
|
|
476
476
|
{question}
|
|
477
|
-
`,
|
|
477
|
+
`,iI=async(t,e)=>{await G({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=ga(t),o=t.groupSummaryGroupId??r.latestGroupId,n=o?r.memory[o]:void 0,s=t.groupSummaryQuestion||qe(t.agentExecutionContext.messages);return n?{status:"success",outputMessage:(await Oe({promptText:aI,schema:lI,modelTier:"default",inputVariables:{summary:n.summary,question:s,fullContext:JSON.stringify(n.fullContext)}})).answer}:{status:"success",outputMessage:"I do not have group analytics context yet. Ask me to analyze a group first with analyze group <group id>."}},lI=c.object({answer:c.string(),isRelevant:c.boolean()}),uI=`
|
|
478
478
|
Classify the user's request for ArcGIS Portal group analytics.
|
|
479
479
|
|
|
480
480
|
Rules:
|
|
@@ -503,10 +503,10 @@ hasAnalyticsContext:
|
|
|
503
503
|
|
|
504
504
|
User message:
|
|
505
505
|
{userMessage}
|
|
506
|
-
`,
|
|
506
|
+
`,cI=async(t,e)=>{await G({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=qe(t.agentExecutionContext.messages),o=!!ga(t).latestGroupId,n=await Ar.fromTemplate(uI).format({userMessage:r,hasAnalyticsContext:String(o)}),s=(await ca({modelTier:"fast"})).withStructuredOutput(jp),a=jp.parse(await s.invoke(n)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let x=qn(r,"$");x&&(i=await nm.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":""}},jp=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),dI=async(t,e)=>{let r=ga(t),o=t.groupSummaryGroupId??r.latestGroupId;return await G({text:"Preparing navigation...",agentName:"group-analytics"},e),await ha(o?{destinationType:"portal-group",groupId:o}:{destinationType:"portal-groups"},e),{status:"success"}};function um({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var pI=720*60*60*1e3;function mI(t){let e=Wl(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:Hl(t),membershipAccess:Jl(t),isOpenData:Zl(t),isDistributedCollaborationGroup:Ql(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function fI(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 hI(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 gI(t,e){return t.filter(r=>r.modified?um({timestamp:r.modified,now:e,windowMs:pI}):!1)}function yI(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 _I(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=hI(e.results),o=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:gI(r,o),topItemTypes:yI(r)}}async function wI(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=mI(r),n=await fI(r),s=await _I(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 bI=`
|
|
507
507
|
You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
|
|
508
508
|
|
|
509
|
-
${
|
|
509
|
+
${lm}
|
|
510
510
|
|
|
511
511
|
Output format requirements:
|
|
512
512
|
- Return concise markdown with clear sections in this order:
|
|
@@ -542,11 +542,11 @@ Group context:
|
|
|
542
542
|
|
|
543
543
|
Deterministic signals:
|
|
544
544
|
{deterministicSignals}
|
|
545
|
-
`,
|
|
545
|
+
`,AI=2160*60*60*1e3,xI=async(t,e)=>{let r=t.groupSummaryGroupId;if(!r)return{status:"success",outputMessage:'Please clarify with analyze group <group id>, analyze group $<title>, or analyze group $"<title with spaces>".'};await G({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let o=e?.configurable?.context;wr(o);let{result:n,error:s}=await wI(o.portal,r);if(s||!n)return await G({text:"Failed to fetch group context",agentName:"group-analytics"},e),{status:"success",outputMessage:"Unable to retrieve group context for analytics."};let{group:a,items:i}=n,u=Date.now(),l=a.modified,d=l?um({timestamp:l,now:u,windowMs:AI}):!1,p=i.recentlyModifiedItems.length,f=p>0,x=d||f,w=await Oe({promptText:bI,schema:II,modelTier:"default",inputVariables:{context:JSON.stringify(n),deterministicSignals:JSON.stringify({isGroupActive:x,isGroupRecentlyModified:d,hasRecentlyAddedOrUpdatedContent:f,recentItemCount:p})}}),{followUpQuestions:b,summary:y}=w,S=ga(t),h={latestGroupId:r,memory:{...S.memory,[r]:{summary:y,followUpQuestions:b,fullContext:n}}};return b.length&&await ua({type:"suggested-prompts",data:{prompts:b}},e),{status:"success",outputMessage:y,sharedStatePatch:{portalGroupSummaryMemory:{value:h}}}},II=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),ol=(t,e)=>e??t,cm=M.Root({...Yo(),groupSummaryIntent:M({reducer:ol,default:()=>"clarify"}),groupSummaryGroupId:M({reducer:ol,default:()=>null}),groupSummaryQuestion:M({reducer:ol,default:()=>""})}),vI=()=>new ce(cm).addNode("detectGroupSummaryIntent",cI).addNode("summarizePortalGroup",xI).addNode("answerGroupSummaryFollowUp",iI).addNode("suggestGroupSummaryNavigation",dI).addEdge(ue,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":K).addEdge("summarizePortalGroup",K).addEdge("answerGroupSummaryFollowUp",K).addEdge("suggestGroupSummaryNavigation",K),TI=String.raw`- **portal-group-analytics** - Portal group analytics assistant:
|
|
546
546
|
- summarizes ArcGIS portal groups from group context and sourceJSON details
|
|
547
547
|
- answers follow-up questions grounded in the summarized group
|
|
548
548
|
- suggests navigation to groups when relevant
|
|
549
|
-
`,
|
|
549
|
+
`,SI={id:"portal-group-analytics",name:"Portal Group Analytics",description:TI,createGraph:vI,workspace:cm},CI=()=>({latestItemId:null,memory:{}}),cl=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:CI()},Dp=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),kI=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),EI=c.object({answer:c.string(),isRelevant:c.boolean()}),MI=`
|
|
550
550
|
You answer follow-up questions about an ArcGIS item.
|
|
551
551
|
|
|
552
552
|
Ground your answer in the provided item context.
|
|
@@ -566,7 +566,7 @@ Item full context
|
|
|
566
566
|
|
|
567
567
|
Question:
|
|
568
568
|
{question}
|
|
569
|
-
`,
|
|
569
|
+
`,PI=async(t,e)=>{await G({text:"Answering follow-up...",agentName:"analytics"},e);let r=cl(t),o=t.analyticsItemId??r.latestItemId,n=o?r.memory[o]:void 0,s=t.analyticsQuestion||qe(t.agentExecutionContext.messages);return n?{status:"success",outputMessage:(await Oe({promptText:MI,schema:EI,modelTier:"default",inputVariables:{summary:n.summary,question:s,fullContext:JSON.stringify(n.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},OI=`
|
|
570
570
|
Classify the user analytics request.
|
|
571
571
|
|
|
572
572
|
Rules:
|
|
@@ -596,7 +596,7 @@ hasSummaryContext:
|
|
|
596
596
|
|
|
597
597
|
User message:
|
|
598
598
|
{userMessage}
|
|
599
|
-
`,
|
|
599
|
+
`,RI=async(t,e)=>{await G({text:"Analyzing intent...",agentName:"analytics"},e);let r=qe(t.agentExecutionContext.messages),o=!!cl(t).latestItemId,n=await Ar.fromTemplate(OI).format({userMessage:r,hasSummaryContext:String(o)}),s=(await ca({modelTier:"fast"})).withStructuredOutput(Dp),a=Dp.parse(await s.invoke(n)),i=a.itemId;if(a.intent==="summarize"&&!i){let p=qn(r,"#");p&&(i=await sm.invoke({itemTitle:p},e)??"")}let{intent:u,question:l}=a,d=u==="clarify"||u==="summarize"&&!i||u==="followUp"&&!l;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:d?"clarify":u,analyticsItemId:i||null,analyticsQuestion:l||"",status:"success",outputMessage:d?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},NI=`
|
|
600
600
|
You are a item summary tool for ArcGIS. Your job is to summarize an item's info based on the provided context.
|
|
601
601
|
Summary rules:
|
|
602
602
|
- The summary should be concise markdown, make sure to format the output nicely so it's easy to read.
|
|
@@ -611,12 +611,12 @@ Do not include internal identifiers.
|
|
|
611
611
|
If the user asks for a detailed summary, you may expand the response up to 300 words.
|
|
612
612
|
Item context:
|
|
613
613
|
{context}
|
|
614
|
-
|
|
614
|
+
`,$I=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await G({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let o=e?.configurable?.context;wr(o);let{portal:n,user:s}=o,{result:a,error:i}=await Vl(s,n,r);if(i||!a)return await G({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await Oe({promptText:NI,schema:kI,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:p}=l,f=cl(t),x={latestItemId:r,memory:{...f.memory,[r]:{summary:p,followUpQuestions:d,fullContext:u}}};return d.length&&await ua({type:"suggested-prompts",data:{prompts:d}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:x}}}},nl=(t,e)=>e??t,dm=M.Root({...Yo(),analyticsIntent:M({reducer:nl,default:()=>"clarify"}),analyticsItemId:M({reducer:nl,default:()=>null}),analyticsQuestion:M({reducer:nl,default:()=>""})}),zI=()=>new ce(dm).addNode("detectAnalyticsIntent",RI).addNode("summarizePortalItem",$I).addNode("answerAnalyticsFollowUp",PI).addEdge(ue,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":K).addEdge("summarizePortalItem",K).addEdge("answerAnalyticsFollowUp",K),LI=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
|
|
615
615
|
- answers questions about one specific ArcGIS portal item when item context is present
|
|
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
|
-
`,
|
|
619
|
+
`,jI={id:"portal-item-analytics",name:"Portal Item Analytics",description:LI,createGraph:zI,workspace:dm},DI=/^(?:take me to|navigate to|go to|show me|open)\s+(?:the\s+)?/u;function fa(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim().replace(DI,"").trim()}var FI=c.object({capabilityIds:c.array(c.string()).default([]),confidence:c.number().min(0).max(1).default(0),reason:c.string().default("")}),Fp=.8,UI=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}`,
|
|
629
|
+
{candidates}`,qI=async(t,e)=>{if(t.outputMessage||t.targets.length===0)return{};let r=qe(t.agentExecutionContext.messages).trim(),o=BI(r,t);if(o.length===1)return await G({text:`Selected navigation capability by exact match: ${o[0]}`,agentName:"navigation"},e),console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"exact-match",request:r,selectedCapabilityIds:o}),{chosenCapabilityIds:o};await G({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 Oe({promptText:UI,schema:FI,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 await G({text:`Navigation selection: ${i.join(", ")||"none"} (confidence: ${s.confidence.toFixed(2)}, reason: ${s.reason})`,agentName:"navigation"},e),console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{confidence:s.confidence,method:"structured-model",reason:s.reason,request:r,selectedCapabilityIds:i}),s.confidence<Fp?{chosenCapabilityIds:[],status:"failed",summary:`Navigation selection confidence ${s.confidence} is below the required ${Fp}; defer to the Portal Doc Assistant.`}:{chosenCapabilityIds:i}}catch{return await G({text:"Navigation selection model unavailable; using retrieval order.",agentName:"navigation"},e),console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"structured-model-unavailable",request:r,selectedCapabilityIds:[]}),{chosenCapabilityIds:[]}}};function BI(t,e){let r=fa(t);return e.targets.filter(({capability:o})=>[o.title,...o.hints].some(n=>fa(n)===r)).map(({capability:o})=>o.id)}var pm=new Set(["1d","7d","14d","30d","3m","6m"]),KI=c.object({period:c.string(),startTime:c.string(),endTime:c.string()}),GI=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
|
|
@@ -651,7 +651,7 @@ Now UTC:
|
|
|
651
651
|
- Epoch ms: {nowEpochMs}
|
|
652
652
|
|
|
653
653
|
User request:
|
|
654
|
-
{userRequest}`;async function qI(t,e=new Date){let r=t.trim();if(!r)return{};try{let o=await Oe({promptText:UI,schema:FI,modelTier:"fast",inputVariables:{nowEpochMs:String(e.getTime()),nowIso:e.toISOString(),userRequest:r}});return BI(o,e)}catch(o){return console.error(o),{}}}function BI(t,e=new Date){let r=Dp(t.startTime),o=Dp(t.endTime),n=KI(t.period);if(n){if(r!==void 0&&o!==void 0&&r<o)return{period:n,startTime:String(r),endTime:String(o)};let s=cm.has(n);if(!s||o!==void 0&&!VI(o,e.getTime())){let a=o??e.getTime(),i=GI(n,new Date(a));if(i!==void 0)return{period:n,startTime:String(i),endTime:String(a)}}return s?{period:n,...r!==void 0?{startTime:String(r)}:{},...o!==void 0?{endTime:String(o)}:{}}:{period:n}}return r!==void 0&&o!==void 0&&r<o?{startTime:String(r),endTime:String(o)}:r!==void 0?{startTime:String(r),endTime:String(e.getTime())}:{}}function KI(t){let e=t?.trim().match(/^(\d+)\s*([dwm])$/iu);if(!e)return;let r=Number.parseInt(e[1],10);if(!Number.isFinite(r)||r<=0)return;let o=e[2].toLowerCase();if(o==="w"){let n=r*7;if(cm.has(`${n}d`))return`${n}d`}return`${r}${o}`}function GI(t,e){let r=t.match(/^(\d+)([dwm])$/u);if(!r)return;let o=Number.parseInt(r[1],10);if(!Number.isFinite(o)||o<=0)return;let n=r[2];if(n==="d")return e.getTime()-o*24*60*60*1e3;if(n==="w")return e.getTime()-o*7*24*60*60*1e3;let s=new Date(e.getTime());return s.setUTCMonth(s.getUTCMonth()-o),s.getTime()}function Dp(t){if(!t)return;let e=Number.parseInt(t,10);if(!(!Number.isFinite(e)||e<=0))return e}function VI(t,e){let r=new Date(t),o=new Date(e);return r.getUTCFullYear()===o.getUTCFullYear()&&r.getUTCMonth()===o.getUTCMonth()&&r.getUTCDate()===o.getUTCDate()}var WI={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"}}}]},HI={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"}}}]},JI={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"}}}]},ZI={"contentRouteRegistry.ts":WI,"groupsRouteRegistry.ts":HI,"orgSettingsRouteRegistry.ts":JI};function Fp(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 Qo(t){return t?ua=Fp({customCapabilities:t}):ua||(ua=Fp(ZI)),ua}async function QI(t,e,r,o){let n=Qo().find(a=>a.id===t);if(!n)return;let s=await XI(YI(n,o),r);return s&&tv(s,e)?{capability:n,target:s}:void 0}function YI(t,e){let r=t.resolutions.navigate;switch(r.routeKey){case"content":return{destinationType:"portal-content",hash:r.hash,queryParams:r.queryParams,buttonLabel:t.buttonLabel};case"groups":if(r.hash==="featured")return{destinationType:"portal-groups",hash:"featured"};if(r.hash==="organization")return{destinationType:"portal-groups",hash:"organization"};switch(t.id){case"my groups":return{destinationType:"portal-groups",hash:"my"};case"create-group":return{destinationType:"portal-groups"};default:return{destinationType:"portal-groups"}}case"group":{let o=e?.trim();return o?{destinationType:"portal-group",groupId:o,hash:r.hash,queryParams:r.queryParams,buttonLabel:t.buttonLabel}:void 0}case"organization":return{destinationType:"portal-org",hash:r.hash,queryParams:r.queryParams,buttonLabel:t.buttonLabel};default:return}}async function XI(t,e){if(!t||!e||!ev(t))return t;let r=await qI(e);if(!r.period&&!r.startTime&&!r.endTime)return t;let o={...t.queryParams??{},...r.period?{period:r.period}:{},...r.startTime?{startTime:r.startTime}:{},...r.endTime?{endTime:r.endTime}:{}};return{...t,queryParams:o}}function ev(t){return t.destinationType==="portal-org"&&t.hash==="status"}function tv(t,e){return!e||!!e[t.destinationType]}function Up(t){return t.match(/\b[a-f0-9]{32}\b/iu)?.[0]}var qp="navigation",Bp="provideGroupId",rv=async(t,e)=>{if(t.outputMessage||t.status==="failed")return{};let r=t.targets.find(({capability:a})=>t.chosenCapabilityIds.includes(a.id))??t.targets[0];if(!r)return{outputMessage:"I couldn't find a matching Portal page. Try asking to open your content, groups, or organization settings.",sharedStatePatch:{navLastAnsweredRequest:{value:Kp(t)}},status:"success",summary:"Navigation could not find a matching capability; route another agent if appropriate."};let o=Kp(t),n=ov(r.capability.resolutions.navigate,o,e),s=await QI(r.capability.id,void 0,o,n);return s?(await G({text:"Preparing navigation...",agentName:"navigation"},e),await ma(s.target,e),{outputMessage:t.chosenCapabilityIds.length?r.capability.description:`The closest place to start is ${r.capability.title}. Click the button below to open it.`,status:"success",summary:`Navigation suggested ${r.capability.id}${t.retrievalDegraded?" using keyword-only retrieval":""}.`,sharedStatePatch:{navLastAnsweredRequest:{value:o}}}):(console.warn(`Navigation capability ${r.capability.id} was not found in the resolver.`),{outputMessage:"I found a possible destination, but couldn't resolve a valid Portal navigation target. Try asking to open your content, groups, or organization settings.",status:"success",summary:`Navigation resolver could not map ${r.capability.id}.`,sharedStatePatch:{navLastAnsweredRequest:{value:o}}})};function Kp(t){return qe(t.agentExecutionContext.messages)||t.agentExecutionContext.userRequest}function ov(t,e,r){if(t.routeKey!=="group")return;let o=Up(e);if(o)return o;let n=nv(r);if(n?.agentId===qp&&n.id===Bp){let a=typeof n.payload=="string"?Up(n.payload):void 0;if(a)return a}let s={agentId:qp,id:Bp,kind:"textInput",message:"Enter the group ID to open."};throw new tn(s)}function nv(t){let e=t?.configurable;if(!e||typeof e!="object"||!("hitlResponse"in e))return;let r=e.hitlResponse;if(!r||typeof r!="object"||!("agentId"in r)||!("id"in r)||!("payload"in r))return;let{agentId:o,id:n,payload:s}=r;return typeof o=="string"&&typeof n=="string"?{agentId:o,id:n,payload:s}:void 0}async function dm(t){return t.length===0?[]:(await ex.getDefault().load(),await Sp(t))}var sv=Object.freeze(Object.defineProperty({__proto__:null,generateEmbeddings:dm},Symbol.toStringTag,{value:"Module"}));function av(t){let e=[],r=`${t.title}. ${t.description}`;r.trim().length>0&&e.push({field:"summary",text:r});let o=t.hints;if(Array.isArray(o))for(let n of o)typeof n=="string"&&n.trim().length>0&&e.push({field:"hint",text:n});return e}var ca,ul,da=0;async function iv(t={}){let e=da;return ca??=uv(t.embed??cv).then(r=>(e===da&&(ul=r),r)).catch(r=>{throw e===da&&(ca=void 0),r}),await ca}function lv(){return ul}function Gp(){da+=1,ul=void 0,ca=void 0}async function uv(t){let e=dv(),r=await t(e.map(o=>o.text));if(r.length!==e.length)throw new Error(`Expected ${e.length} vectors, got ${r.length}`);return e.map((o,n)=>({...o,vector:r[n]}))}async function cv(t){let{generateEmbeddings:e}=await Promise.resolve().then(()=>sv);return await e(t)}function dv(){return Qo().flatMap(t=>av(t).map(({field:e,text:r})=>({capabilityId:t.id,field:e,text:r})))}var Vp=1.2,Wp=.75,pv=60,mv=.65,ol={description:1,hint:2,title:3},al;function fv(){al=void 0}async function hv(t,e={}){let r=wv(pm(t)),o=[],n=!1,s;if(t.trim()){let a=e.loadEmbeddings,i=lv();if(!a&&!i)n=!0,s="Capability embeddings are still loading.";else try{if(a){let[u,l]=await Promise.all([(e.embedQuery??Jp)(t),a()]);o=Hp(u,l)}else if(i){let u=await(e.embedQuery??Jp)(t);o=Hp(u,i)}}catch{n=!0,s="Semantic search is unavailable."}}return{degraded:n,...s?{degradedReason:s}:{},matches:Av(r,o,e.topN??5)}}function gv(){return al??=yv(Qo()),al}function yv(t){let e=new Map,r=t.map(o=>{let n=new Map;nl(n,o.title,ol.title),nl(n,o.description,ol.description);for(let s of o.hints)nl(n,s,ol.hint);for(let s of n.keys())e.set(s,(e.get(s)??0)+1);return{capability:o,length:_v(n),termFrequencies:n}});return{averageDocumentLength:r.length?r.reduce((o,n)=>o+n.length,0)/r.length:0,documentFrequency:e,documents:r}}function nl(t,e,r){for(let o of pm(e))t.set(o,(t.get(o)??0)+r)}function _v(t){return[...t.values()].reduce((e,r)=>e+r,0)}function pm(t){return t.toLowerCase().split(/[^a-z0-9]+/u).filter(Boolean)}function wv(t){let e=gv(),r=new Set(t),o=e.documents.length;return e.documents.map(({capability:n,length:s,termFrequencies:a})=>{let i=0;for(let u of r){let l=a.get(u),d=e.documentFrequency.get(u);if(!l||!d)continue;let p=Math.log(1+(o-d+.5)/(d+.5)),f=Vp*(1-Wp+Wp*(s/e.averageDocumentLength));i+=p*(l*(Vp+1)/(l+f))}return{capability:n,score:i}}).filter(({score:n})=>n>0).sort(mm)}function Hp(t,e){let r=new Map;for(let n of e){let s=bv(t,n.vector);if(s===void 0)continue;let a=r.get(n.capabilityId);(a===void 0||s>a)&&r.set(n.capabilityId,s)}let o=new Map(Qo().map(n=>[n.id,n]));return[...r.entries()].flatMap(([n,s])=>{let a=o.get(n);return a&&s>=mv?[{capability:a,score:s}]:[]}).sort(mm)}function bv(t,e){if(t.length===0||t.length!==e.length)return;let r=0,o=0,n=0;for(let a=0;a<t.length;a+=1)r+=t[a]*e[a],o+=t[a]**2,n+=e[a]**2;let s=Math.sqrt(o)*Math.sqrt(n);return s===0?void 0:r/s}async function Jp(t){let[e]=await dm([t]);if(!e)throw new Error("Expected one query embedding.");return e}function Av(t,e,r){let o=new Map;return Zp(o,t,"keyword"),Zp(o,e,"semantic"),[...o.values()].sort((n,s)=>s.score!==n.score?s.score-n.score:(s.semanticScore??0)!==(n.semanticScore??0)?(s.semanticScore??0)-(n.semanticScore??0):(s.keywordScore??0)!==(n.keywordScore??0)?(s.keywordScore??0)-(n.keywordScore??0):n.capability.id.localeCompare(s.capability.id)).slice(0,Math.max(0,r))}function Zp(t,e,r){for(let[o,{capability:n,score:s}]of e.entries()){let a=o+1,i=t.get(n.id)??{capability:n,score:0};i.score+=1/(pv+a),r==="keyword"?(i.keywordRank=a,i.keywordScore=s):(i.semanticRank=a,i.semanticScore=s),t.set(n.id,i)}}function mm(t,e){return e.score-t.score||t.capability.id.localeCompare(e.capability.id)}var xv=async(t,e)=>{await G({text:"Finding a place to navigate...",agentName:"navigation"},e);let r=qe(t.agentExecutionContext.messages).trim();try{let o=await hv(r,{topN:5});return await G({text:`Navigation candidates: ${vv(o.matches)}`,agentName:"navigation"},e),console.table(o.matches.map(({capability:n,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u,score:l})=>({capability:n.title,fusedScore:l,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u}))),o.degradedReason&&console.info("[arcgis-portal-ai-assistant] navigation semantic search:",o.degradedReason),{chosenCapabilityIds:[],retrievalDegraded:o.degradedReason??"",targets:Iv(r,o.matches)}}catch{return{chosenCapabilityIds:[],outputMessage:"I couldn't look up a Portal page right now. Please try again.",status:"failed",targets:[]}}};function Iv(t,e){let r=pa(t),o=e.filter(({capability:s})=>[s.title,...s.hints].some(a=>pa(a)===r));if(o.length!==1)return e;let[n]=o;return[n,...e.filter(s=>s!==n)]}function vv(t){return t.map(({capability:e,keywordScore:r,semanticScore:o})=>`${e.title} (keyword: ${Qp(r)}, semantic: ${Qp(o)})`).join("; ")||"none"}function Qp(t){return t?.toFixed(3)??"none"}var sl=(t,e)=>e??t,fm=M.Root({...Zo(),chosenCapabilityIds:M({reducer:sl,default:()=>[]}),retrievalDegraded:M({reducer:sl,default:()=>""}),targets:M({reducer:sl,default:()=>[]})}),Tv=()=>new ce(fm).addNode("retrieveNavigationTargets",xv).addNode("chooseNavigationTargets",jI).addNode("respondWithNavigation",rv).addEdge(ue,"retrieveNavigationTargets").addEdge("retrieveNavigationTargets","chooseNavigationTargets").addEdge("chooseNavigationTargets","respondWithNavigation").addEdge("respondWithNavigation",K);function Sv(){return String.raw`- **Navigation** — Takes the user to the portal page or app that fulfills their request. Presenting the button COMPLETES the request — no follow-up step is needed.
|
|
654
|
+
{userRequest}`;async function VI(t,e=new Date){let r=t.trim();if(!r)return{};try{let o=await Oe({promptText:GI,schema:KI,modelTier:"fast",inputVariables:{nowEpochMs:String(e.getTime()),nowIso:e.toISOString(),userRequest:r}});return WI(o,e)}catch(o){return console.error(o),{}}}function WI(t,e=new Date){let r=Up(t.startTime),o=Up(t.endTime),n=HI(t.period);if(n){if(r!==void 0&&o!==void 0&&r<o)return{period:n,startTime:String(r),endTime:String(o)};let s=pm.has(n);if(!s||o!==void 0&&!ZI(o,e.getTime())){let a=o??e.getTime(),i=JI(n,new Date(a));if(i!==void 0)return{period:n,startTime:String(i),endTime:String(a)}}return s?{period:n,...r!==void 0?{startTime:String(r)}:{},...o!==void 0?{endTime:String(o)}:{}}:{period:n}}return r!==void 0&&o!==void 0&&r<o?{startTime:String(r),endTime:String(o)}:r!==void 0?{startTime:String(r),endTime:String(e.getTime())}:{}}function HI(t){let e=t?.trim().match(/^(\d+)\s*([dwm])$/iu);if(!e)return;let r=Number.parseInt(e[1],10);if(!Number.isFinite(r)||r<=0)return;let o=e[2].toLowerCase();if(o==="w"){let n=r*7;if(pm.has(`${n}d`))return`${n}d`}return`${r}${o}`}function JI(t,e){let r=t.match(/^(\d+)([dwm])$/u);if(!r)return;let o=Number.parseInt(r[1],10);if(!Number.isFinite(o)||o<=0)return;let n=r[2];if(n==="d")return e.getTime()-o*24*60*60*1e3;if(n==="w")return e.getTime()-o*7*24*60*60*1e3;let s=new Date(e.getTime());return s.setUTCMonth(s.getUTCMonth()-o),s.getTime()}function Up(t){if(!t)return;let e=Number.parseInt(t,10);if(!(!Number.isFinite(e)||e<=0))return e}function ZI(t,e){let r=new Date(t),o=new Date(e);return r.getUTCFullYear()===o.getUTCFullYear()&&r.getUTCMonth()===o.getUTCMonth()&&r.getUTCDate()===o.getUTCDate()}var QI={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"}}}]},YI={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"}}}]},XI={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"}}}]},ev={"contentRouteRegistry.ts":QI,"groupsRouteRegistry.ts":YI,"orgSettingsRouteRegistry.ts":XI};function qp(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 da;function Xo(t){return t?da=qp({customCapabilities:t}):da||(da=qp(ev)),da}async function tv(t,e,r,o){let n=Xo().find(a=>a.id===t);if(!n)return;let s=await ov(rv(n,o),r);return s&&sv(s,e)?{capability:n,target:s}:void 0}function rv(t,e){let r=t.resolutions.navigate;switch(r.routeKey){case"content":return{destinationType:"portal-content",hash:r.hash,queryParams:r.queryParams,buttonLabel:t.buttonLabel};case"groups":if(r.hash==="featured")return{destinationType:"portal-groups",hash:"featured"};if(r.hash==="organization")return{destinationType:"portal-groups",hash:"organization"};switch(t.id){case"my groups":return{destinationType:"portal-groups",hash:"my"};case"create-group":return{destinationType:"portal-groups"};default:return{destinationType:"portal-groups"}}case"group":{let o=e?.trim();return o?{destinationType:"portal-group",groupId:o,hash:r.hash,queryParams:r.queryParams,buttonLabel:t.buttonLabel}:void 0}case"organization":return{destinationType:"portal-org",hash:r.hash,queryParams:r.queryParams,buttonLabel:t.buttonLabel};default:return}}async function ov(t,e){if(!t||!e||!nv(t))return t;let r=await VI(e);if(!r.period&&!r.startTime&&!r.endTime)return t;let o={...t.queryParams??{},...r.period?{period:r.period}:{},...r.startTime?{startTime:r.startTime}:{},...r.endTime?{endTime:r.endTime}:{}};return{...t,queryParams:o}}function nv(t){return t.destinationType==="portal-org"&&t.hash==="status"}function sv(t,e){return!e||!!e[t.destinationType]}function Bp(t){return t.match(/\b[a-f0-9]{32}\b/iu)?.[0]}var Kp="navigation",Gp="provideGroupId",av=async(t,e)=>{if(t.outputMessage||t.status==="failed")return{};let r=t.targets.find(({capability:a})=>t.chosenCapabilityIds.includes(a.id))??t.targets[0];if(!r)return{outputMessage:"I couldn't find a matching Portal page. Try asking to open your content, groups, or organization settings.",sharedStatePatch:{navLastAnsweredRequest:{value:Vp(t)}},status:"success",summary:"Navigation could not find a matching capability; route another agent if appropriate."};let o=Vp(t),n=iv(r.capability.resolutions.navigate,o,e),s=await tv(r.capability.id,void 0,o,n);return s?(await G({text:"Preparing navigation...",agentName:"navigation"},e),await ha(s.target,e),{outputMessage:t.chosenCapabilityIds.length?r.capability.description:`The closest place to start is ${r.capability.title}. Click the button below to open it.`,status:"success",summary:`Navigation suggested ${r.capability.id}${t.retrievalDegraded?" using keyword-only retrieval":""}.`,sharedStatePatch:{navLastAnsweredRequest:{value:o}}}):(console.warn(`Navigation capability ${r.capability.id} was not found in the resolver.`),{outputMessage:"I found a possible destination, but couldn't resolve a valid Portal navigation target. Try asking to open your content, groups, or organization settings.",status:"success",summary:`Navigation resolver could not map ${r.capability.id}.`,sharedStatePatch:{navLastAnsweredRequest:{value:o}}})};function Vp(t){return qe(t.agentExecutionContext.messages)||t.agentExecutionContext.userRequest}function iv(t,e,r){if(t.routeKey!=="group")return;let o=Bp(e);if(o)return o;let n=lv(r);if(n?.agentId===Kp&&n.id===Gp){let a=typeof n.payload=="string"?Bp(n.payload):void 0;if(a)return a}let s={agentId:Kp,id:Gp,kind:"textInput",message:"Enter the group ID to open."};throw new on(s)}function lv(t){let e=t?.configurable;if(!e||typeof e!="object"||!("hitlResponse"in e))return;let r=e.hitlResponse;if(!r||typeof r!="object"||!("agentId"in r)||!("id"in r)||!("payload"in r))return;let{agentId:o,id:n,payload:s}=r;return typeof o=="string"&&typeof n=="string"?{agentId:o,id:n,payload:s}:void 0}async function mm(t){return t.length===0?[]:(await nx.getDefault().load(),await kp(t))}var uv=Object.freeze(Object.defineProperty({__proto__:null,generateEmbeddings:mm},Symbol.toStringTag,{value:"Module"}));function cv(t){let e=[],r=`${t.title}. ${t.description}`;r.trim().length>0&&e.push({field:"summary",text:r});let o=t.hints;if(Array.isArray(o))for(let n of o)typeof n=="string"&&n.trim().length>0&&e.push({field:"hint",text:n});return e}var pa,dl,ma=0;async function dv(t={}){let e=ma;return pa??=mv(t.embed??fv).then(r=>(e===ma&&(dl=r),r)).catch(r=>{throw e===ma&&(pa=void 0),r}),await pa}function pv(){return dl}function Wp(){ma+=1,dl=void 0,pa=void 0}async function mv(t){let e=hv(),r=await t(e.map(o=>o.text));if(r.length!==e.length)throw new Error(`Expected ${e.length} vectors, got ${r.length}`);return e.map((o,n)=>({...o,vector:r[n]}))}async function fv(t){let{generateEmbeddings:e}=await Promise.resolve().then(()=>uv);return await e(t)}function hv(){return Xo().flatMap(t=>cv(t).map(({field:e,text:r})=>({capabilityId:t.id,field:e,text:r})))}var Hp=1.2,Jp=.75,gv=60,yv=.65,sl={description:1,hint:2,title:3},ll;function _v(){ll=void 0}async function wv(t,e={}){let r=Iv(fm(t)),o=[],n=!1,s;if(t.trim()){let a=e.loadEmbeddings,i=pv();if(!a&&!i)n=!0,s="Capability embeddings are still loading.";else try{if(a){let[u,l]=await Promise.all([(e.embedQuery??Qp)(t),a()]);o=Zp(u,l)}else if(i){let u=await(e.embedQuery??Qp)(t);o=Zp(u,i)}}catch{n=!0,s="Semantic search is unavailable."}}return{degraded:n,...s?{degradedReason:s}:{},matches:Tv(r,o,e.topN??5)}}function bv(){return ll??=Av(Xo()),ll}function Av(t){let e=new Map,r=t.map(o=>{let n=new Map;al(n,o.title,sl.title),al(n,o.description,sl.description);for(let s of o.hints)al(n,s,sl.hint);for(let s of n.keys())e.set(s,(e.get(s)??0)+1);return{capability:o,length:xv(n),termFrequencies:n}});return{averageDocumentLength:r.length?r.reduce((o,n)=>o+n.length,0)/r.length:0,documentFrequency:e,documents:r}}function al(t,e,r){for(let o of fm(e))t.set(o,(t.get(o)??0)+r)}function xv(t){return[...t.values()].reduce((e,r)=>e+r,0)}function fm(t){return t.toLowerCase().split(/[^a-z0-9]+/u).filter(Boolean)}function Iv(t){let e=bv(),r=new Set(t),o=e.documents.length;return e.documents.map(({capability:n,length:s,termFrequencies:a})=>{let i=0;for(let u of r){let l=a.get(u),d=e.documentFrequency.get(u);if(!l||!d)continue;let p=Math.log(1+(o-d+.5)/(d+.5)),f=Hp*(1-Jp+Jp*(s/e.averageDocumentLength));i+=p*(l*(Hp+1)/(l+f))}return{capability:n,score:i}}).filter(({score:n})=>n>0).sort(hm)}function Zp(t,e){let r=new Map;for(let n of e){let s=vv(t,n.vector);if(s===void 0)continue;let a=r.get(n.capabilityId);(a===void 0||s>a)&&r.set(n.capabilityId,s)}let o=new Map(Xo().map(n=>[n.id,n]));return[...r.entries()].flatMap(([n,s])=>{let a=o.get(n);return a&&s>=yv?[{capability:a,score:s}]:[]}).sort(hm)}function vv(t,e){if(t.length===0||t.length!==e.length)return;let r=0,o=0,n=0;for(let a=0;a<t.length;a+=1)r+=t[a]*e[a],o+=t[a]**2,n+=e[a]**2;let s=Math.sqrt(o)*Math.sqrt(n);return s===0?void 0:r/s}async function Qp(t){let[e]=await mm([t]);if(!e)throw new Error("Expected one query embedding.");return e}function Tv(t,e,r){let o=new Map;return Yp(o,t,"keyword"),Yp(o,e,"semantic"),[...o.values()].sort((n,s)=>s.score!==n.score?s.score-n.score:(s.semanticScore??0)!==(n.semanticScore??0)?(s.semanticScore??0)-(n.semanticScore??0):(s.keywordScore??0)!==(n.keywordScore??0)?(s.keywordScore??0)-(n.keywordScore??0):n.capability.id.localeCompare(s.capability.id)).slice(0,Math.max(0,r))}function Yp(t,e,r){for(let[o,{capability:n,score:s}]of e.entries()){let a=o+1,i=t.get(n.id)??{capability:n,score:0};i.score+=1/(gv+a),r==="keyword"?(i.keywordRank=a,i.keywordScore=s):(i.semanticRank=a,i.semanticScore=s),t.set(n.id,i)}}function hm(t,e){return e.score-t.score||t.capability.id.localeCompare(e.capability.id)}var Sv=async(t,e)=>{await G({text:"Finding a place to navigate...",agentName:"navigation"},e);let r=qe(t.agentExecutionContext.messages).trim();try{let o=await wv(r,{topN:5});return await G({text:`Navigation candidates: ${kv(o.matches)}`,agentName:"navigation"},e),console.table(o.matches.map(({capability:n,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u,score:l})=>({capability:n.title,fusedScore:l,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u}))),o.degradedReason&&console.info("[arcgis-portal-ai-assistant] navigation semantic search:",o.degradedReason),{chosenCapabilityIds:[],retrievalDegraded:o.degradedReason??"",targets:Cv(r,o.matches)}}catch{return{chosenCapabilityIds:[],outputMessage:"I couldn't look up a Portal page right now. Please try again.",status:"failed",targets:[]}}};function Cv(t,e){let r=fa(t),o=e.filter(({capability:s})=>[s.title,...s.hints].some(a=>fa(a)===r));if(o.length!==1)return e;let[n]=o;return[n,...e.filter(s=>s!==n)]}function kv(t){return t.map(({capability:e,keywordScore:r,semanticScore:o})=>`${e.title} (keyword: ${Xp(r)}, semantic: ${Xp(o)})`).join("; ")||"none"}function Xp(t){return t?.toFixed(3)??"none"}var il=(t,e)=>e??t,gm=M.Root({...Yo(),chosenCapabilityIds:M({reducer:il,default:()=>[]}),retrievalDegraded:M({reducer:il,default:()=>""}),targets:M({reducer:il,default:()=>[]})}),Ev=()=>new ce(gm).addNode("retrieveNavigationTargets",Sv).addNode("chooseNavigationTargets",qI).addNode("respondWithNavigation",av).addEdge(ue,"retrieveNavigationTargets").addEdge("retrieveNavigationTargets","chooseNavigationTargets").addEdge("chooseNavigationTargets","respondWithNavigation").addEdge("respondWithNavigation",K);function Mv(){return String.raw`- **Navigation** — Takes the user to the portal page or app that fulfills their request. Presenting the button COMPLETES the request — no follow-up step is needed.
|
|
655
655
|
|
|
656
656
|
Route here for **navigation intent** ("take me to the map viewer", "open content", "where is X?") and for **action intent** ("publish a scene layer", "create a web map", "share this item") — for an action, Navigation takes the user to the page where that workflow starts. Navigation searches the capability registry itself, so don't rule it out because a page isn't named here.
|
|
657
657
|
|
|
@@ -661,4 +661,4 @@ User request:
|
|
|
661
661
|
- An action another agent actually performs — e.g. "create group" is EXECUTED by group agent. Route it here only when the user explicitly asks to navigate ("take me to create group")
|
|
662
662
|
- Requests that mix navigation with a question or explanation ("take me there and explain how") → use Help
|
|
663
663
|
|
|
664
|
-
Do not dispatch Navigation again for the same request in the same turn: once it has responded, the task is done.`}var
|
|
664
|
+
Do not dispatch Navigation again for the same request in the same turn: once it has responded, the task is done.`}var Pv={id:"navigation",name:"Portal Navigation",get description(){return Mv()},createGraph:Ev,workspace:gm},Ov=fl`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`;function Rv(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":return e[r]?.(t.hash,t.queryParams);case"portal-groups":return e[r]?.(t.hash);case"portal-org":return e[r]?.(t.hash,t.queryParams);case"portal-gallery":return e[r];case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId,t.hash,t.queryParams);default:return rn(r)}}function Nv(t){let e=kx.safeParse(t);return e.success?e.data:void 0}function $v(t,e){let r=e.navigation;switch(t.destinationType){case"portal-content":switch(t.hash){case"favorites":return r.openContentFavorites;case"group":return r.openContentGroup;case"living-atlas":return r.openContentLivingAtlas;case"org":return r.openContentOrganization;default:return r.openContent}case"portal-gallery":return r.openGallery;case"portal-groups":switch(t.hash){case"featured":return r.openGroupsFeatured;case"my":return r.openGroupsMy;case"organization":return r.openGroupsOrganization;default:return r.openGroups}case"portal-map-viewer":return r.openMapViewer;case"portal-notebooks":return r.openNotebooks;case"portal-scene-viewer":return r.openSceneViewer;case"portal-org":return r.openOrgSettings;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return rn(t)}}var ul=class extends _l{constructor(){super(),this.t9n=Al({blocking:!0}),this.assistantEl=en(),this.formEl=en(),this.voiceInputEl=en(),this.inputEl=en(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,o=r.data?.block;if(!o)return;let n=this.getNavigationAction(o);n&&this.upsertNavigationSlotElement(r.slotName,n)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.useProdDocAssistant=!1,this.arcgisPortalNavigationRequest=gl(),Xo()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,disabledAgents:0,defaultClosed:5,navigationCapabilities:0,useProdDocAssistant:5}}static{this.styles=Ov}async load(){await this.refreshCapabilityEmbeddings()}willUpdate(e){!this.hasUpdated||!e.has("navigationCapabilities")||this.refreshCapabilityEmbeddings()}async clearEmbeddingsCache(){Wp()}isAgentEnabled(e){return!this.disabledAgents?.[e]}async refreshCapabilityEmbeddings(){try{Xo(this.navigationCapabilities),_v(),Wp(),await dv()}catch(e){console.warn("[arcgis-portal-ai-assistant] embeddings warm-up failed:",e)}}getNavigationAction(e){if(e?.type!==tm)return;let r=e.data,o=Nv(r);if(!o)return;let n=Rv(r,this.navigationTargetMap);if(n)return{href:n,targetDetail:r,label:r?.buttonLabel||$v(o,this.t9n)}}upsertNavigationSlotElement(e,r){let o=this.assistantEl.value;if(!o)return;let n=`navigation:${e}`,s=this.navigationSlotElements.get(n);s||(s=document.createElement("div"),s.slot=e,this.navigationSlotElements.set(n,s),o.append(s)),hl(Re`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${a=>{a.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?Re`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,s)}render(){let{t9n:e,inputText:r,portal:o,user:n,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u,useProdDocAssistant:l}=this;return Re`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisPromptSelect=${({detail:d})=>{this.inputText=d.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${tn(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${d=>{d.preventDefault();let p=r.trim();p&&(this.assistantEl.value?.submitMessage(p),this.inputText="")}} ${tn(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${o} .user=${n} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:d})=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:d})=>{this.inputText=d??""}} ${tn(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${d=>{d.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${d=>{this.inputText=d.detail.text}} ${tn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&Re`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let d=this.voiceInputEl.value;i?await d?.stopListening():await d?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form>${this.isAgentEnabled("itemAnalytics")&&Re`<arcgis-assistant-agent .agent=${jI} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupCreation")&&Re`<arcgis-assistant-agent .agent=${Ox} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("docAssistant")&&Re`<arcgis-assistant-agent .agent=${nI} .context=${{portal:o,user:n,navigationTargetMap:s,useProdDocAssistant:l}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupAnalytics")&&Re`<arcgis-assistant-agent .agent=${SI} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("navigation")&&Re`<arcgis-assistant-agent .agent=${Pv} .context=${{portal:o,user:n,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}</arcgis-assistant>`}};wl("arcgis-portal-ai-assistant",ul);return ul},"identity/IdentityManager","portal/Portal","portal/Portal","request","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/Point","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","layers/support/FeatureFilter","rest/support/TopFeaturesQuery","rest/support/TopFilter","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","config","Graphic","portal/Portal","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","request","portal/Portal",a,b,c)
|