@arcgis/portal-components 5.2.0-next.66 → 5.2.0-next.68
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,12 +1,12 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import c from"./55FL7WQV.js";import b from"./5KDFY5KE.js";import{a as Cl,c as El,e as Pl,f as Ml,g as Ol}from"./UZCHLKLO.js";import a from"./DALGPO36.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as Vn,b as tl,d as rl}from"./2GBRZSEC.js";import{a as nl}from"./7ZXEX3LI.js";import"./SKUPHVNO.js";import"./TNLGQ7HL.js";import{K as Gn,L as Wn,M as Xi,S as el,h as Ji,j as xe,n as Zi,w as Qi,z as Yi}from"./TSTTPCWU.js";import{$ as ul,Aa as bl,Ba as Go,Ca as Wo,Da as xl,Db as Vo,Ea as gr,Eb as Ho,Fa as yr,Fb as ue,Ga as v,Ha as $,Ia as ma,J as sl,Ja as fa,K as Ae,L as al,M as zo,N as aa,O as ia,P as jo,Q as Hn,R as q,S as la,T as D,Ta as C,U as ot,V as st,W as Lo,X as il,Y as ll,Z as ua,_ as Do,a as le,aa as cl,b as U,ba as Jn,ca as Fo,da as dl,ea as pl,fa as ml,g as ol,ga as Uo,ha as fl,ia as kt,j as qe,ja as ca,k as St,ka as qo,la as N,ma as A,mb as Al,na as Ct,oa as at,pa as hl,qa as Bo,ra as gl,s as $o,sa as yl,ta as Ko,ua as da,va as hr,wa as pa,xa as _l,y as No,ya as wl,zb as Zn}from"./PGCNY5GO.js";import"./UZLQALHY.js";export default $arcgis.t(([
|
|
2
|
+
import c from"./55FL7WQV.js";import b from"./5KDFY5KE.js";import{a as Cl,c as El,e as Pl,f as Ml,g as Ol}from"./UZCHLKLO.js";import a from"./DALGPO36.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as Vn,b as tl,d as rl}from"./2GBRZSEC.js";import{a as nl}from"./7ZXEX3LI.js";import"./SKUPHVNO.js";import"./TNLGQ7HL.js";import{K as Gn,L as Wn,M as Xi,S as el,h as Ji,j as xe,n as Zi,w as Qi,z as Yi}from"./TSTTPCWU.js";import{$ as ul,Aa as bl,Ba as Go,Ca as Wo,Da as xl,Db as Vo,Ea as gr,Eb as Ho,Fa as yr,Fb as ue,Ga as v,Ha as $,Ia as ma,J as sl,Ja as fa,K as Ae,L as al,M as zo,N as aa,O as ia,P as jo,Q as Hn,R as q,S as la,T as D,Ta as C,U as ot,V as st,W as Lo,X as il,Y as ll,Z as ua,_ as Do,a as le,aa as cl,b as U,ba as Jn,ca as Fo,da as dl,ea as pl,fa as ml,g as ol,ga as Uo,ha as fl,ia as kt,j as qe,ja as ca,k as St,ka as qo,la as N,ma as A,mb as Al,na as Ct,oa as at,pa as hl,qa as Bo,ra as gl,s as $o,sa as yl,ta as Ko,ua as da,va as hr,wa as pa,xa as _l,y as No,ya as wl,zb as Zn}from"./PGCNY5GO.js";import"./UZLQALHY.js";export default $arcgis.t(([p2,f2,bd,xd,Tg,Sg,Lg,b2,A2,R4,ix,Dd,pr,Fd,Ii,Wd,,qg,{addressToLocations:Bg},Kg,Gg,Vd,{createRenderer:Wg},{getSchemesByTag:Vg,getSchemes:Hg},{getBackgroundColorTheme:Ud},{createAgeRenderer:Jg,createContinuousRenderer:Zg},{getSchemesByTag:Ri},{createContinuousRenderer:Qg},{createRenderer:Yg},{getSchemesByTag:Xg},{createRenderer:ey},{getSchemesByTag:ty},{createRenderer:ry},{getSchemesByTag:ny},{createRenderer:oy},{getSchemesByTag:sy},{createAgeRenderer:ay,createContinuousRenderer:iy},{createRenderer:ly},{getSchemesByTag:uy},cy,Hd,Jd,{formatDateOnly:dy,convertDateFormatToIntlOptions:Us,formatTimeOnly:py,formatDate:qd},my,fy,hy,gy,yy,Zd,,{fetchKnowledgeGraph:Bd,executeQueryStreaming:_y,executeSearchStreaming:wy},by,{getBindParametersFromCypherQuery:xy},,,,,,,,,,,,,,,,,,,,,,,,,RH,NH,,,,,,,,,,,,,lx,cp,ux,,{a:Sl,b:kl},{a:Il,b:vl,c:Tl}])=>{var c=v;async function ha(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
|
|
3
3
|
|
|
4
4
|
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
5
5
|
|
|
6
6
|
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
7
7
|
|`,`
|
|
8
8
|
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
9
|
-
`].join(" "));let n=await cl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var H=async(t,e)=>{await ha("trace_message",t,e)},me=async(t,e)=>{await ha("graph_ux_suggestion",t,e)};var
|
|
9
|
+
`].join(" "));let n=await cl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var H=async(t,e)=>{await ha("trace_message",t,e)},me=async(t,e)=>{await ha("graph_ux_suggestion",t,e)};var Zp={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},GI=Object.keys(Zp);var _a=Symbol.for("langgraph-zod");_a in globalThis||(globalThis[_a]=new WeakSet);function Nl(t){let e=globalThis[_a];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return Ho(r,{jsonSchemaExtra:n})},reducer(n,o){return Ho(r,{default:qo(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{Nl(A.ZodType.prototype),Nl(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 zl=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 n=qo(t);n!=null&&(r.default=n)}return super.add(t,...e)}},em=new zl(Vo);var gm=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),ym=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),_m=["approve","edit","reject"],wm=A.enum(_m),bm=A.object({allowedDecisions:A.array(wm),description:A.union([A.string(),ym]).optional(),argsSchema:A.record(A.any()).optional(),when:gm.optional()}),ek=A.object({interruptOn:A.record(A.union([A.boolean(),bm])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var Im=`<role>
|
|
10
10
|
Context Extraction Assistant
|
|
11
11
|
</role>
|
|
12
12
|
|
|
@@ -32,23 +32,23 @@ Respond ONLY with the extracted context. Do not include any additional informati
|
|
|
32
32
|
<messages>
|
|
33
33
|
Messages to summarize:
|
|
34
34
|
{messages}
|
|
35
|
-
</messages>`;var
|
|
35
|
+
</messages>`;var vm=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),va=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"}),Gl=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"}),_k=A.object({model:A.custom(),trigger:A.union([va,A.array(va)]).optional(),keep:Gl.optional(),tokenCounter:vm.optional(),summaryPrompt:A.string().default(Im),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var Ek=A.object({model:A.string().or(A.instanceof(gl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var zk=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var Uk=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Tm=["continue","error","end"],Sm="continue";var km=A.enum(Tm).default(Sm);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:km});var Yk=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Cm=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Em=A.object({content:A.string().describe("Content of the todo item"),status:Cm}),aC=A.object({todos:A.array(Em).default([])});var dC=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),pC=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var Jo=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(()=>()=>!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 SC=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(Jo);var $C=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(Jo);var JC=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var XC=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function Qn(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
36
36
|
|
|
37
37
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
38
|
-
`,t}function E(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function _(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Ta=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Ta=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Yn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Xn=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 k=class extends Error{},G=class t extends k{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new lt({message:n,cause:Xn(r)});let s=r?.error;return e===400?new wr(e,s,n,o):e===401?new br(e,s,n,o):e===403?new xr(e,s,n,o):e===404?new Ar(e,s,n,o):e===409?new Ir(e,s,n,o):e===422?new vr(e,s,n,o):e===429?new Tr(e,s,n,o):e>=500?new Sr(e,s,n,o):new t(e,s,n,o)}},W=class extends G{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},lt=class extends G{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Oe=class extends lt{constructor({message:e}={}){super({message:e??"Request timed out."})}},wr=class extends G{},br=class extends G{},xr=class extends G{},Ar=class extends G{},Ir=class extends G{},vr=class extends G{},Tr=class extends G{},Sr=class extends G{},kr=class extends k{constructor(){super("Could not parse response content as the length limit was reached")}},Cr=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},Pt=class extends G{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},eo=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Lm=/^[a-z][a-z0-9+.-]*:/i,Wl=t=>Lm.test(t),ce=t=>(ce=Array.isArray,ce(t)),Sa=ce;function Zo(t){return typeof t!="object"?{}:t??{}}function ka(t){if(!t)return!0;for(let e in t)return!1;return!0}function Vl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function to(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Hl=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e};var Jl=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var ut="6.45.0";var Xl=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Dm(){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 Fm=()=>{let t=Dm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ut,"X-Stainless-OS":Ql(Deno.build.os),"X-Stainless-Arch":Zl(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":ut,"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":ut,"X-Stainless-OS":Ql(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Zl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Um();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ut,"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":ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Um(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var Zl=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Ql=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"),Yl,eu=()=>Yl??(Yl=Fm());function Qo(){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 Ca(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Yo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ca({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Ea(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 Pa(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 ru=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ma="RFC3986",Oa=t=>String(t),Ra={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Oa},nu="RFC1738";var Xo=(t,e)=>(Xo=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Xo(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var $a=1024,ou=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=$a){let u=s.length>=$a?s.slice(i,i+$a):s,l=[];for(let d=0;d<u.length;++d){let m=u.charCodeAt(d);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===nu&&(m===40||m===41)){l[l.length]=u.charAt(d);continue}if(m<128){l[l.length]=Ne[m];continue}if(m<2048){l[l.length]=Ne[192|m>>6]+Ne[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Ne[224|m>>12]+Ne[128|m>>6&63]+Ne[128|m&63];continue}d+=1,m=65536+((m&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&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 Na(t,e){if(ce(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var iu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},lu=function(t,e){Array.prototype.push.apply(t,ce(e)?e:[e])},au,X={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ou,encodeValuesOnly:!1,format:Ma,formatter:Oa,indices:!1,serializeDate(t){return(au??(au=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Bm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var za={};function uu(t,e,r,n,o,s,a,i,u,l,d,m,f,I,w,b,y,h){let x=t,S=h,M=0,F=!1;for(;(S=S.get(za))!==void 0&&!F;){let Z=S.get(t);if(M+=1,typeof Z<"u"){if(Z===M)throw new RangeError("Cyclic object value");F=!0}typeof S.get(za)>"u"&&(M=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&ce(x)&&(x=Na(x,function(Z){return Z instanceof Date?f?.(Z):Z})),x===null){if(s)return u&&!b?u(e,X.encoder,y,"key",I):e;x=""}if(Bm(x)||su(x)){if(u){let Z=b?e:u(e,X.encoder,y,"key",I);return[w?.(Z)+"="+w?.(u(x,X.encoder,y,"value",I))]}return[w?.(e)+"="+w?.(String(x))]}let B=[];if(typeof x>"u")return B;let K;if(r==="comma"&&ce(x))b&&u&&(x=Na(x,u)),K=[{value:x.length>0?x.join(",")||null:void 0}];else if(ce(l))K=l;else{let Z=Object.keys(x);K=d?Z.sort(d):Z}let V=i?String(e).replace(/\./g,"%2E"):String(e),ie=n&&ce(x)&&x.length===1?V+"[]":V;if(o&&ce(x)&&x.length===0)return ie+"[]";for(let Z=0;Z<K.length;++Z){let Y=K[Z],Vi=typeof Y=="object"&&typeof Y.value<"u"?Y.value:x[Y];if(a&&Vi===null)continue;let sa=m&&i?Y.replace(/\./g,"%2E"):Y,Vp=ce(x)?typeof r=="function"?r(ie,sa):ie:ie+(m?"."+sa:"["+sa+"]");h.set(t,M);let Hi=new WeakMap;Hi.set(za,h),lu(B,uu(Vi,Vp,r,n,o,s,a,i,r==="comma"&&b&&ce(x)?null:u,l,d,m,f,I,w,b,y,Hi))}return B}function Km(t=X){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||X.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=Ma;if(typeof t.format<"u"){if(!Xo(Ra,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Ra[r],o=X.filter;(typeof t.filter=="function"||ce(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in iu?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=X.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:X.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:X.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:X.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:X.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?X.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:X.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:X.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:X.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:X.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:X.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:X.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:X.strictNullHandling}}function cu(t,e={}){let r=t,n=Km(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ce(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=iu[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let f=0;f<o.length;++f){let I=o[f];n.skipNulls&&r[I]===null||lu(a,uu(r[I],I,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let d=a.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),d.length>0?m+d:""}function du(t){return cu(t,{arrayFormat:"brackets"})}function fu(t){let e=0;for(let o of t)e+=o.length;let r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var pu;function Er(t){let e;return(pu??(e=new globalThis.TextEncoder,pu=e.encode.bind(e)))(t)}var mu;function ja(t){let e;return(mu??(e=new globalThis.TextDecoder,mu=e.decode.bind(e)))(t)}var he,ge,Mt=class{constructor(){he.set(this,void 0),ge.set(this,void 0),E(this,he,new Uint8Array,"f"),E(this,ge,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Er(e):e;E(this,he,fu([_(this,he,"f"),r]),"f");let n=[],o;for(;(o=Wm(_(this,he,"f"),_(this,ge,"f")))!=null;){if(o.carriage&&_(this,ge,"f")==null){E(this,ge,o.index,"f");continue}if(_(this,ge,"f")!=null&&(o.index!==_(this,ge,"f")+1||o.carriage)){n.push(ja(_(this,he,"f").subarray(0,_(this,ge,"f")-1))),E(this,he,_(this,he,"f").subarray(_(this,ge,"f")),"f"),E(this,ge,null,"f");continue}let s=_(this,ge,"f")!==null?o.preceding-1:o.preceding,a=ja(_(this,he,"f").subarray(0,s));n.push(a),E(this,he,_(this,he,"f").subarray(o.index),"f"),E(this,ge,null,"f")}return n}flush(){return _(this,he,"f").length?this.decode(`
|
|
38
|
+
`,t}function E(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function _(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Ta=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Ta=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Yn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Xn=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 k=class extends Error{},G=class t extends k{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new lt({message:n,cause:Xn(r)});let s=r?.error;return e===400?new wr(e,s,n,o):e===401?new br(e,s,n,o):e===403?new xr(e,s,n,o):e===404?new Ar(e,s,n,o):e===409?new Ir(e,s,n,o):e===422?new vr(e,s,n,o):e===429?new Tr(e,s,n,o):e>=500?new Sr(e,s,n,o):new t(e,s,n,o)}},W=class extends G{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},lt=class extends G{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Oe=class extends lt{constructor({message:e}={}){super({message:e??"Request timed out."})}},wr=class extends G{},br=class extends G{},xr=class extends G{},Ar=class extends G{},Ir=class extends G{},vr=class extends G{},Tr=class extends G{},Sr=class extends G{},kr=class extends k{constructor(){super("Could not parse response content as the length limit was reached")}},Cr=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},Pt=class extends G{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},eo=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Dm=/^[a-z][a-z0-9+.-]*:/i,Wl=t=>Dm.test(t),ce=t=>(ce=Array.isArray,ce(t)),Sa=ce;function Zo(t){return typeof t!="object"?{}:t??{}}function ka(t){if(!t)return!0;for(let e in t)return!1;return!0}function Vl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function to(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Hl=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e};var Jl=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var ut="6.45.0";var Xl=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Fm(){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 Um=()=>{let t=Fm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ut,"X-Stainless-OS":Ql(Deno.build.os),"X-Stainless-Arch":Zl(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":ut,"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":ut,"X-Stainless-OS":Ql(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Zl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=qm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ut,"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":ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qm(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var Zl=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Ql=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"),Yl,eu=()=>Yl??(Yl=Um());function Qo(){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 Ca(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Yo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ca({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Ea(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 Pa(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 ru=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ma="RFC3986",Oa=t=>String(t),Ra={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Oa},nu="RFC1738";var Xo=(t,e)=>(Xo=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Xo(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var $a=1024,ou=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=$a){let u=s.length>=$a?s.slice(i,i+$a):s,l=[];for(let d=0;d<u.length;++d){let m=u.charCodeAt(d);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===nu&&(m===40||m===41)){l[l.length]=u.charAt(d);continue}if(m<128){l[l.length]=Ne[m];continue}if(m<2048){l[l.length]=Ne[192|m>>6]+Ne[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Ne[224|m>>12]+Ne[128|m>>6&63]+Ne[128|m&63];continue}d+=1,m=65536+((m&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&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 Na(t,e){if(ce(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var iu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},lu=function(t,e){Array.prototype.push.apply(t,ce(e)?e:[e])},au,X={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ou,encodeValuesOnly:!1,format:Ma,formatter:Oa,indices:!1,serializeDate(t){return(au??(au=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Km(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var za={};function uu(t,e,r,n,o,s,a,i,u,l,d,m,f,I,w,b,y,h){let x=t,S=h,M=0,F=!1;for(;(S=S.get(za))!==void 0&&!F;){let Z=S.get(t);if(M+=1,typeof Z<"u"){if(Z===M)throw new RangeError("Cyclic object value");F=!0}typeof S.get(za)>"u"&&(M=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&ce(x)&&(x=Na(x,function(Z){return Z instanceof Date?f?.(Z):Z})),x===null){if(s)return u&&!b?u(e,X.encoder,y,"key",I):e;x=""}if(Km(x)||su(x)){if(u){let Z=b?e:u(e,X.encoder,y,"key",I);return[w?.(Z)+"="+w?.(u(x,X.encoder,y,"value",I))]}return[w?.(e)+"="+w?.(String(x))]}let B=[];if(typeof x>"u")return B;let K;if(r==="comma"&&ce(x))b&&u&&(x=Na(x,u)),K=[{value:x.length>0?x.join(",")||null:void 0}];else if(ce(l))K=l;else{let Z=Object.keys(x);K=d?Z.sort(d):Z}let V=i?String(e).replace(/\./g,"%2E"):String(e),ie=n&&ce(x)&&x.length===1?V+"[]":V;if(o&&ce(x)&&x.length===0)return ie+"[]";for(let Z=0;Z<K.length;++Z){let Y=K[Z],Vi=typeof Y=="object"&&typeof Y.value<"u"?Y.value:x[Y];if(a&&Vi===null)continue;let sa=m&&i?Y.replace(/\./g,"%2E"):Y,Hp=ce(x)?typeof r=="function"?r(ie,sa):ie:ie+(m?"."+sa:"["+sa+"]");h.set(t,M);let Hi=new WeakMap;Hi.set(za,h),lu(B,uu(Vi,Hp,r,n,o,s,a,i,r==="comma"&&b&&ce(x)?null:u,l,d,m,f,I,w,b,y,Hi))}return B}function Gm(t=X){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||X.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=Ma;if(typeof t.format<"u"){if(!Xo(Ra,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Ra[r],o=X.filter;(typeof t.filter=="function"||ce(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in iu?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=X.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:X.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:X.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:X.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:X.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?X.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:X.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:X.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:X.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:X.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:X.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:X.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:X.strictNullHandling}}function cu(t,e={}){let r=t,n=Gm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ce(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=iu[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let f=0;f<o.length;++f){let I=o[f];n.skipNulls&&r[I]===null||lu(a,uu(r[I],I,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let d=a.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),d.length>0?m+d:""}function du(t){return cu(t,{arrayFormat:"brackets"})}function fu(t){let e=0;for(let o of t)e+=o.length;let r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var pu;function Er(t){let e;return(pu??(e=new globalThis.TextEncoder,pu=e.encode.bind(e)))(t)}var mu;function ja(t){let e;return(mu??(e=new globalThis.TextDecoder,mu=e.decode.bind(e)))(t)}var he,ge,Mt=class{constructor(){he.set(this,void 0),ge.set(this,void 0),E(this,he,new Uint8Array,"f"),E(this,ge,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Er(e):e;E(this,he,fu([_(this,he,"f"),r]),"f");let n=[],o;for(;(o=Vm(_(this,he,"f"),_(this,ge,"f")))!=null;){if(o.carriage&&_(this,ge,"f")==null){E(this,ge,o.index,"f");continue}if(_(this,ge,"f")!=null&&(o.index!==_(this,ge,"f")+1||o.carriage)){n.push(ja(_(this,he,"f").subarray(0,_(this,ge,"f")-1))),E(this,he,_(this,he,"f").subarray(_(this,ge,"f")),"f"),E(this,ge,null,"f");continue}let s=_(this,ge,"f")!==null?o.preceding-1:o.preceding,a=ja(_(this,he,"f").subarray(0,s));n.push(a),E(this,he,_(this,he,"f").subarray(o.index),"f"),E(this,ge,null,"f")}return n}flush(){return _(this,he,"f").length?this.decode(`
|
|
39
39
|
`):[]}};he=new WeakMap,ge=new WeakMap;Mt.NEWLINE_CHARS=new Set([`
|
|
40
|
-
`,"\r"]);Mt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
41
|
-
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*
|
|
42
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Zm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Zm(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function rs(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return J(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):ze.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 Fa(f,r)}return await r.text()})();return J(t).debug(`[${n}] response parsed`,Be({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function Fa(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 oo,Ot=class t extends Promise{constructor(e,r,n=rs){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,oo.set(this,void 0),E(this,oo,e,"f")}_thenUnwrap(e){return new t(_(this,oo,"f"),this.responsePromise,async(r,n)=>Fa(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,oo,"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)}};oo=new WeakMap;var ns,Pr=class{constructor(e,r,n,o){ns.set(this,void 0),E(this,ns,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,ns,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ns=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},so=class extends Ot{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await rs(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},de=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...Zo(this.options.query),after:r}}:null}},j=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Zo(this.options.query),after:e}}:null}},Q=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Zo(this.options.query),after:e}}:null}};var Ym={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Xm="urn:ietf:params:oauth:grant-type:token-exchange",os=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Qo()}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:Xm,subject_token:e,subject_token_type:Ym[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 n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let u=await n.text(),l;try{l=JSON.parse(u)}catch{}throw n.status===400||n.status===401||n.status===403?new Pt(n.status,l,n.headers):G.generate(n.status,l,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new k("Token exchange response missing 'access_token' field");let s=o.access_token,a=o.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 n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Ba=()=>{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 Mr(t,e,r){return Ba(),new File(t,e??"unknown_file",r)}function ao(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 ss=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",ct=async(t,e)=>Ua(t.body)?{...t,body:await _u(t.body,e)}:t,pe=async(t,e)=>({...t,body:await _u(t.body,e)}),yu=new WeakMap;function ef(t){let e=typeof t=="function"?t:t.fetch,r=yu.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return yu.set(e,n),n}var _u=async(t,e)=>{if(!await ef(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,o])=>qa(r,n,o))),r},wu=t=>t instanceof Blob&&"name"in t,tf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||ss(t)||wu(t)),Ua=t=>{if(tf(t))return!0;if(Array.isArray(t))return t.some(Ua);if(t&&typeof t=="object"){for(let e in t)if(Ua(t[e]))return!0}return!1},qa=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,Mr([await r.blob()],ao(r)));else if(ss(r))t.append(e,Mr([await new Response(Yo(r)).blob()],ao(r)));else if(wu(r))t.append(e,r,ao(r));else if(Array.isArray(r))await Promise.all(r.map(n=>qa(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>qa(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var 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",rf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&bu(t),nf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function io(t,e,r){if(Ba(),t=await t,rf(t))return t instanceof File?t:Mr([await t.arrayBuffer()],t.name);if(nf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Mr(await Ka(o),e,r)}let n=await Ka(t);if(e||(e=ao(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Mr(n,e,r)}async function Ka(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(ss(t))for await(let r of t)e.push(...await Ka(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${of(t)}`)}return e}function of(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function Au(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var xu=Object.freeze(Object.create(null)),af=(t=Au)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],a=r.reduce((d,m,f)=>{/[?#]/.test(m)&&(o=!0);let I=n[f],w=(o?encodeURIComponent:t)(""+I);return f!==n.length&&(I==null||typeof I=="object"&&I.toString===Object.getPrototypeOf(Object.getPrototypeOf(I.hasOwnProperty??xu)??xu)?.toString)&&(w=I+"",s.push({start:d.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(I).slice(8,-1)} is not a valid path parameter`})),d+m+(f===n.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,m)=>d.start-m.start),s.length>0){let d=0,m=s.reduce((f,I)=>{let w=" ".repeat(I.start-d),b="^".repeat(I.length);return d=I.start+I.length,f+w+b},"");throw new k(`Path parameters result in path with invalid segments:
|
|
40
|
+
`,"\r"]);Mt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Vm(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function hu(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var ts={off:0,error:200,warn:300,info:400,debug:500},La=(t,e,r)=>{if(t){if(Vl(ts,t))return t;J(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ts))}`)}};function ro(){}function es(t,e,r){return!e||ts[t]>ts[r]?ro:e[t].bind(e)}var Hm={error:ro,warn:ro,info:ro,debug:ro},gu=new WeakMap;function J(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Hm;let n=gu.get(e);if(n&&n[0]===r)return n[1];let o={error:es("error",e,r),warn:es("warn",e,r),info:es("info",e,r),debug:es("debug",e,r)};return gu.set(e,[r,o]),o}var Be=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 no,ze=class t{constructor(e,r,n){this.iterator=e,no.set(this,void 0),this.controller=r,E(this,no,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,a=n?J(n):console;async function*i(){if(s)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of Jm(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(m){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),m}if(d&&d.error)throw new G(void 0,d.error,void 0,e.headers);yield o?{event:l.event,data:d}:d}else{let d;try{d=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new G(void 0,d.error,d.message,void 0);yield{event:l.event,data:d}}}u=!0}catch(l){if(Yn(l))return;throw l}finally{u||r.abort()}}return new t(i,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let i=new Mt,u=Ea(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(o)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(Yn(u))return;throw u}finally{i||r.abort()}}return new t(a,r,n)}[(no=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>o(e),this.controller,_(this,no,"f")),new t(()=>o(r),this.controller,_(this,no,"f"))]}toReadableStream(){let e=this,r;return Ca({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let a=Er(JSON.stringify(o)+`
|
|
41
|
+
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Jm(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new k("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 k("Attempted to iterate over a response with no body");let r=new Da,n=new Mt,o=Ea(t.body);for await(let s of Zm(o))for(let a of n.decode(s)){let i=r.decode(a);i&&(yield i)}for(let s of n.flush()){let a=r.decode(s);a&&(yield a)}}async function*Zm(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Er(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=hu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Da=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(`
|
|
42
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Qm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Qm(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function rs(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return J(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):ze.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 Fa(f,r)}return await r.text()})();return J(t).debug(`[${n}] response parsed`,Be({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function Fa(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 oo,Ot=class t extends Promise{constructor(e,r,n=rs){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,oo.set(this,void 0),E(this,oo,e,"f")}_thenUnwrap(e){return new t(_(this,oo,"f"),this.responsePromise,async(r,n)=>Fa(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,oo,"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)}};oo=new WeakMap;var ns,Pr=class{constructor(e,r,n,o){ns.set(this,void 0),E(this,ns,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,ns,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ns=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},so=class extends Ot{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await rs(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},de=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...Zo(this.options.query),after:r}}:null}},j=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Zo(this.options.query),after:e}}:null}},Q=class extends Pr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Zo(this.options.query),after:e}}:null}};var Xm={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},ef="urn:ietf:params:oauth:grant-type:token-exchange",os=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Qo()}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:ef,subject_token:e,subject_token_type:Xm[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 n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let u=await n.text(),l;try{l=JSON.parse(u)}catch{}throw n.status===400||n.status===401||n.status===403?new Pt(n.status,l,n.headers):G.generate(n.status,l,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new k("Token exchange response missing 'access_token' field");let s=o.access_token,a=o.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 n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Ba=()=>{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 Mr(t,e,r){return Ba(),new File(t,e??"unknown_file",r)}function ao(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 ss=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",ct=async(t,e)=>Ua(t.body)?{...t,body:await _u(t.body,e)}:t,pe=async(t,e)=>({...t,body:await _u(t.body,e)}),yu=new WeakMap;function tf(t){let e=typeof t=="function"?t:t.fetch,r=yu.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return yu.set(e,n),n}var _u=async(t,e)=>{if(!await tf(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,o])=>qa(r,n,o))),r},wu=t=>t instanceof Blob&&"name"in t,rf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||ss(t)||wu(t)),Ua=t=>{if(rf(t))return!0;if(Array.isArray(t))return t.some(Ua);if(t&&typeof t=="object"){for(let e in t)if(Ua(t[e]))return!0}return!1},qa=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,Mr([await r.blob()],ao(r)));else if(ss(r))t.append(e,Mr([await new Response(Yo(r)).blob()],ao(r)));else if(wu(r))t.append(e,r,ao(r));else if(Array.isArray(r))await Promise.all(r.map(n=>qa(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>qa(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var 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",nf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&bu(t),of=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function io(t,e,r){if(Ba(),t=await t,nf(t))return t instanceof File?t:Mr([await t.arrayBuffer()],t.name);if(of(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Mr(await Ka(o),e,r)}let n=await Ka(t);if(e||(e=ao(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Mr(n,e,r)}async function Ka(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(ss(t))for await(let r of t)e.push(...await Ka(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${sf(t)}`)}return e}function sf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function Au(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var xu=Object.freeze(Object.create(null)),lf=(t=Au)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],a=r.reduce((d,m,f)=>{/[?#]/.test(m)&&(o=!0);let I=n[f],w=(o?encodeURIComponent:t)(""+I);return f!==n.length&&(I==null||typeof I=="object"&&I.toString===Object.getPrototypeOf(Object.getPrototypeOf(I.hasOwnProperty??xu)??xu)?.toString)&&(w=I+"",s.push({start:d.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(I).slice(8,-1)} is not a valid path parameter`})),d+m+(f===n.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,m)=>d.start-m.start),s.length>0){let d=0,m=s.reduce((f,I)=>{let w=" ".repeat(I.start-d),b="^".repeat(I.length);return d=I.start+I.length,f+w+b},"");throw new k(`Path parameters result in path with invalid segments:
|
|
43
43
|
${s.map(f=>f.error).join(`
|
|
44
44
|
`)}
|
|
45
45
|
${a}
|
|
46
|
-
${m}`)}return a},p=af(Au);var Rt=class extends g{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function lo(t){return t!==void 0&&"function"in t&&t.function!==void 0}function vu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function uo(t){return t?.$brand==="auto-parseable-response-format"}function $t(t){return t?.$brand==="auto-parseable-tool"}function Tu(t,e){return!e||!Ga(e)?{...t,choices:t.choices.map(r=>(ku(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:co(t,e)}function co(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new kr;if(n.finish_reason==="content_filter")throw new Cr;return ku(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>cf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?uf(e,n.message.content):null}}});return{...t,choices:r}}function uf(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 cf(t,e){let r=t.tools?.find(n=>lo(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$t(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Su(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>lo(n)&&n.function?.name===e.function.name);return lo(r)&&($t(r)||r?.function.strict||!1)}function Ga(t){return uo(t.response_format)?!0:t.tools?.some(e=>$t(e)||e.type==="function"&&e.function.strict===!0)??!1}function ku(t){for(let e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Cu(t){for(let e of t??[]){if(e.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new k(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Or=t=>t?.role==="assistant",Wa=t=>t?.role==="tool";var as,is,ls,po,mo,us,fo,Ke,cs,ho,ds,ps,Rr,Eu,Pu,dt=class{constructor(){as.add(this),this.controller=new AbortController,is.set(this,void 0),ls.set(this,()=>{}),po.set(this,()=>{}),mo.set(this,void 0),us.set(this,()=>{}),fo.set(this,()=>{}),Ke.set(this,{}),cs.set(this,[]),ho.set(this,!1),ds.set(this,!1),ps.set(this,!1),Rr.set(this,!1),E(this,is,new Promise((e,r)=>{E(this,ls,e,"f"),E(this,po,r,"f")}),"f"),E(this,mo,new Promise((e,r)=>{E(this,us,e,"f"),E(this,fo,r,"f")}),"f"),_(this,is,"f").catch(()=>{}),_(this,mo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,as,"m",Pu).bind(this))},0)}_connected(){this.ended||(_(this,ls,"f").call(this),this._emit("connect"))}get ended(){return _(this,ho,"f")}get errored(){return _(this,ds,"f")}get aborted(){return _(this,ps,"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,cs,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ke,"f")[e]||(_(this,Ke,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,Ke,"f")[e];if(!n)return this;let o=n.findIndex(s=>s.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(_(this,Ke,"f")[e]||(_(this,Ke,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{E(this,Rr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){E(this,Rr,!0,"f"),await _(this,mo,"f")}_emit(e,...r){if(_(this,ho,"f"))return;e==="end"&&(_(this,as,"m",Eu).call(this),E(this,ho,!0,"f"),_(this,us,"f").call(this));let n=_(this,Ke,"f")[e];if(n&&(_(this,Ke,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,Rr,"f")&&!n?.length&&Promise.reject(o),_(this,po,"f").call(this,o),_(this,fo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Rr,"f")&&!n?.length&&Promise.reject(o),_(this,po,"f").call(this,o),_(this,fo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};is=new WeakMap,ls=new WeakMap,po=new WeakMap,mo=new WeakMap,us=new WeakMap,fo=new WeakMap,Ke=new WeakMap,cs=new WeakMap,ho=new WeakMap,ds=new WeakMap,ps=new WeakMap,Rr=new WeakMap,as=new WeakSet,Eu=function(){for(let{signal:e,listener:r}of _(this,cs,"f").splice(0))e.removeEventListener("abort",r)},Pu=function(e){if(E(this,ds,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new W),e instanceof W)return E(this,ps,!0,"f"),this._emit("abort",e);if(e instanceof k)return this._emit("error",e);if(e instanceof Error){let r=new k(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new k(String(e)))};function Mu(t){return typeof t.parse=="function"}var fe,Va,ms,Ha,Ja,Za,Ou,Ru,df=10,$r=class extends dt{constructor(){super(...arguments),fe.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),Wa(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Or(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new k("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,fe,"m",Va).call(this)}async finalMessage(){return await this.done(),_(this,fe,"m",ms).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,fe,"m",Ha).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,fe,"m",Ja).call(this)}async totalUsage(){return await this.done(),_(this,fe,"m",Za).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,fe,"m",ms).call(this);r&&this._emit("finalMessage",r);let n=_(this,fe,"m",Va).call(this);n&&this._emit("finalContent",n);let o=_(this,fe,"m",Ha).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,fe,"m",Ja).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,fe,"m",Za).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),_(this,fe,"m",Ou).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(co(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=df,afterCompletion:m}=o||{},f=r.tools.map(y=>{if($t(y)){if(!y.$callback)throw new k("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}),I={};for(let y of f)y.type==="function"&&(I[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 h=y.id,{name:x,arguments:S}=y.function,M=I[x];if(!M){let K=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(I).map(V=>JSON.stringify(V)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:h,content:K},functionCalled:!1}}if(l&&l!==x){let K=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:h,content:K},functionCalled:!1}}let F;if(Mu(M)){let K;try{K=await M.parse(S)}catch(V){let ie=V instanceof Error?V.message:String(V);return{message:{role:s,tool_call_id:h,content:ie},functionCalled:!1}}F=await M.function(K,n)}else F=await M.function(S,n);let B=_(this,fe,"m",Ru).call(this,F);return{message:{role:s,tool_call_id:h,content:B},functionCalled:!0}};for(let y=0;y<d;++y){let h=await this._createChatCompletion(e,{...u,tool_choice:a,tools:w,messages:[...this.messages]},o),x=h.choices[0]?.message;if(!x)throw new k("missing message in ChatCompletion response");if(!x.tool_calls?.length){await m?.(h,n);return}if(l||r.parallel_tool_calls===!1)for(let S of x.tool_calls){let M=await b(S);if(M.message&&this._addMessage(M.message),l&&M.functionCalled){await m?.(h,n);return}}else{let S=await Promise.allSettled(x.tool_calls.map(b));for(let M of S)if(M.status==="rejected")throw M.reason;for(let M of S)M.status==="fulfilled"&&M.value.message&&this._addMessage(M.value.message)}await m?.(h,n)}}};fe=new WeakSet,Va=function(){return _(this,fe,"m",ms).call(this).content??null},ms=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Or(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},Ha=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Or(r)&&r?.tool_calls?.length)for(let n=r.tool_calls.length-1;n>=0;n--){let o=r.tool_calls[n];if(o?.type==="function")return o.function}}},Ja=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Wa(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(o=>o.type==="function"&&o.id===r.tool_call_id)))return r.content}},Za=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},Ou=function(e){if(e.n!=null&&e.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ru=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var go=class t extends $r{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),Or(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},Qa=class extends Error{},Ya=class extends Error{};function pf(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 mf(t.trim(),e)}var mf=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Qa(`${f} at position ${n}`)},s=f=>{throw new Ya(`${f} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||ne.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ne.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ne.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ne.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ne.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ne.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):d()),i=()=>{let f=n,I=!1;for(n++;n<r&&(t[n]!=='"'||I&&t[n-1]==="\\");)I=t[n]==="\\"?!I:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(I)))}catch(w){s(String(w))}else if(ne.STR&e)try{return JSON.parse(t.substring(f,n-Number(I))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&ne.OBJ&e)return f;let I=i();m(),n++;try{let w=a();Object.defineProperty(f,I,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(ne.OBJ&e)return f;throw w}m(),t[n]===","&&n++}}catch{if(ne.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(a()),m(),t[n]===","&&n++}catch{if(ne.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},d=()=>{if(n===0){t==="-"&&ne.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(I){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(I))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ne.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&ne.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},m=()=>{for(;n<r&&`
|
|
47
|
-
\r `.includes(t[n]);)n++};return a()},Xa=t=>
|
|
46
|
+
${m}`)}return a},p=lf(Au);var Rt=class extends g{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function lo(t){return t!==void 0&&"function"in t&&t.function!==void 0}function vu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function uo(t){return t?.$brand==="auto-parseable-response-format"}function $t(t){return t?.$brand==="auto-parseable-tool"}function Tu(t,e){return!e||!Ga(e)?{...t,choices:t.choices.map(r=>(ku(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:co(t,e)}function co(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new kr;if(n.finish_reason==="content_filter")throw new Cr;return ku(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>df(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?cf(e,n.message.content):null}}});return{...t,choices:r}}function cf(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 df(t,e){let r=t.tools?.find(n=>lo(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$t(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Su(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>lo(n)&&n.function?.name===e.function.name);return lo(r)&&($t(r)||r?.function.strict||!1)}function Ga(t){return uo(t.response_format)?!0:t.tools?.some(e=>$t(e)||e.type==="function"&&e.function.strict===!0)??!1}function ku(t){for(let e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Cu(t){for(let e of t??[]){if(e.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new k(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Or=t=>t?.role==="assistant",Wa=t=>t?.role==="tool";var as,is,ls,po,mo,us,fo,Ke,cs,ho,ds,ps,Rr,Eu,Pu,dt=class{constructor(){as.add(this),this.controller=new AbortController,is.set(this,void 0),ls.set(this,()=>{}),po.set(this,()=>{}),mo.set(this,void 0),us.set(this,()=>{}),fo.set(this,()=>{}),Ke.set(this,{}),cs.set(this,[]),ho.set(this,!1),ds.set(this,!1),ps.set(this,!1),Rr.set(this,!1),E(this,is,new Promise((e,r)=>{E(this,ls,e,"f"),E(this,po,r,"f")}),"f"),E(this,mo,new Promise((e,r)=>{E(this,us,e,"f"),E(this,fo,r,"f")}),"f"),_(this,is,"f").catch(()=>{}),_(this,mo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,as,"m",Pu).bind(this))},0)}_connected(){this.ended||(_(this,ls,"f").call(this),this._emit("connect"))}get ended(){return _(this,ho,"f")}get errored(){return _(this,ds,"f")}get aborted(){return _(this,ps,"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,cs,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Ke,"f")[e]||(_(this,Ke,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,Ke,"f")[e];if(!n)return this;let o=n.findIndex(s=>s.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(_(this,Ke,"f")[e]||(_(this,Ke,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{E(this,Rr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){E(this,Rr,!0,"f"),await _(this,mo,"f")}_emit(e,...r){if(_(this,ho,"f"))return;e==="end"&&(_(this,as,"m",Eu).call(this),E(this,ho,!0,"f"),_(this,us,"f").call(this));let n=_(this,Ke,"f")[e];if(n&&(_(this,Ke,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,Rr,"f")&&!n?.length&&Promise.reject(o),_(this,po,"f").call(this,o),_(this,fo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Rr,"f")&&!n?.length&&Promise.reject(o),_(this,po,"f").call(this,o),_(this,fo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};is=new WeakMap,ls=new WeakMap,po=new WeakMap,mo=new WeakMap,us=new WeakMap,fo=new WeakMap,Ke=new WeakMap,cs=new WeakMap,ho=new WeakMap,ds=new WeakMap,ps=new WeakMap,Rr=new WeakMap,as=new WeakSet,Eu=function(){for(let{signal:e,listener:r}of _(this,cs,"f").splice(0))e.removeEventListener("abort",r)},Pu=function(e){if(E(this,ds,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new W),e instanceof W)return E(this,ps,!0,"f"),this._emit("abort",e);if(e instanceof k)return this._emit("error",e);if(e instanceof Error){let r=new k(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new k(String(e)))};function Mu(t){return typeof t.parse=="function"}var fe,Va,ms,Ha,Ja,Za,Ou,Ru,pf=10,$r=class extends dt{constructor(){super(...arguments),fe.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),Wa(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Or(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new k("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,fe,"m",Va).call(this)}async finalMessage(){return await this.done(),_(this,fe,"m",ms).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,fe,"m",Ha).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,fe,"m",Ja).call(this)}async totalUsage(){return await this.done(),_(this,fe,"m",Za).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,fe,"m",ms).call(this);r&&this._emit("finalMessage",r);let n=_(this,fe,"m",Va).call(this);n&&this._emit("finalContent",n);let o=_(this,fe,"m",Ha).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,fe,"m",Ja).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,fe,"m",Za).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),_(this,fe,"m",Ou).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(co(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:d=pf,afterCompletion:m}=o||{},f=r.tools.map(y=>{if($t(y)){if(!y.$callback)throw new k("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}),I={};for(let y of f)y.type==="function"&&(I[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 h=y.id,{name:x,arguments:S}=y.function,M=I[x];if(!M){let K=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(I).map(V=>JSON.stringify(V)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:h,content:K},functionCalled:!1}}if(l&&l!==x){let K=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:h,content:K},functionCalled:!1}}let F;if(Mu(M)){let K;try{K=await M.parse(S)}catch(V){let ie=V instanceof Error?V.message:String(V);return{message:{role:s,tool_call_id:h,content:ie},functionCalled:!1}}F=await M.function(K,n)}else F=await M.function(S,n);let B=_(this,fe,"m",Ru).call(this,F);return{message:{role:s,tool_call_id:h,content:B},functionCalled:!0}};for(let y=0;y<d;++y){let h=await this._createChatCompletion(e,{...u,tool_choice:a,tools:w,messages:[...this.messages]},o),x=h.choices[0]?.message;if(!x)throw new k("missing message in ChatCompletion response");if(!x.tool_calls?.length){await m?.(h,n);return}if(l||r.parallel_tool_calls===!1)for(let S of x.tool_calls){let M=await b(S);if(M.message&&this._addMessage(M.message),l&&M.functionCalled){await m?.(h,n);return}}else{let S=await Promise.allSettled(x.tool_calls.map(b));for(let M of S)if(M.status==="rejected")throw M.reason;for(let M of S)M.status==="fulfilled"&&M.value.message&&this._addMessage(M.value.message)}await m?.(h,n)}}};fe=new WeakSet,Va=function(){return _(this,fe,"m",ms).call(this).content??null},ms=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Or(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},Ha=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Or(r)&&r?.tool_calls?.length)for(let n=r.tool_calls.length-1;n>=0;n--){let o=r.tool_calls[n];if(o?.type==="function")return o.function}}},Ja=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Wa(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(o=>o.type==="function"&&o.id===r.tool_call_id)))return r.content}},Za=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},Ou=function(e){if(e.n!=null&&e.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ru=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var go=class t extends $r{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),Or(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},Qa=class extends Error{},Ya=class extends Error{};function mf(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 ff(t.trim(),e)}var ff=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Qa(`${f} at position ${n}`)},s=f=>{throw new Ya(`${f} at position ${n}`)},a=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||ne.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ne.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ne.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ne.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ne.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ne.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):d()),i=()=>{let f=n,I=!1;for(n++;n<r&&(t[n]!=='"'||I&&t[n-1]==="\\");)I=t[n]==="\\"?!I:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(I)))}catch(w){s(String(w))}else if(ne.STR&e)try{return JSON.parse(t.substring(f,n-Number(I))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&ne.OBJ&e)return f;let I=i();m(),n++;try{let w=a();Object.defineProperty(f,I,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(ne.OBJ&e)return f;throw w}m(),t[n]===","&&n++}}catch{if(ne.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(a()),m(),t[n]===","&&n++}catch{if(ne.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},d=()=>{if(n===0){t==="-"&&ne.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(I){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(I))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ne.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&ne.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},m=()=>{for(;n<r&&`
|
|
47
|
+
\r `.includes(t[n]);)n++};return a()},Xa=t=>mf(t,ne.ALL^ne.NUM);var ee,Ge,Nr,pt,ei,fs,ti,ri,ni,hs,oi,$u,Nt=class t extends $r{constructor(e){super(),ee.add(this),Ge.set(this,void 0),Nr.set(this,void 0),pt.set(this,void 0),E(this,Ge,e,"f"),E(this,Nr,[],"f")}get currentChatCompletionSnapshot(){return _(this,pt,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion,this._listenForAbort(n?.signal),_(this,ee,"m",ei).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)_(this,ee,"m",ti).call(this,s);if(o.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,ee,"m",hs).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,ee,"m",ei).call(this),this._connected();let n=ze.fromReadableStream(e,this.controller),o;for await(let s of n)o&&o!==s.id&&this._addChatCompletion(_(this,ee,"m",hs).call(this)),_(this,ee,"m",ti).call(this,s),o=s.id;if(n.controller.signal?.aborted)throw new W;return this._addChatCompletion(_(this,ee,"m",hs).call(this))}[(Ge=new WeakMap,Nr=new WeakMap,pt=new WeakMap,ee=new WeakSet,ei=function(){this.ended||E(this,pt,void 0,"f")},fs=function(r){let n=_(this,Nr,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},_(this,Nr,"f")[r.index]=n,n)},ti=function(r){if(this.ended)return;let n=_(this,ee,"m",$u).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index];o.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.delta.content,s.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),o.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=_(this,ee,"m",fs).call(this,s);s.finish_reason&&(_(this,ee,"m",ni).call(this,s),a.current_tool_call_index!=null&&_(this,ee,"m",ri).call(this,s,a.current_tool_call_index));for(let i of o.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(_(this,ee,"m",ni).call(this,s),a.current_tool_call_index!=null&&_(this,ee,"m",ri).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of o.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))}}},ri=function(r,n){if(_(this,ee,"m",fs).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let a=_(this,Ge,"f")?.tools?.find(i=>lo(i)&&i.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:$t(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},ni=function(r){let n=_(this,ee,"m",fs).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,ee,"m",oi).call(this);this._emit("content.done",{content:r.message.content,parsed:o?o.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},hs=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,pt,"f");if(!r)throw new k("request ended without sending any chunks");return E(this,pt,void 0,"f"),E(this,Nr,[],"f"),hf(r,_(this,Ge,"f"))},oi=function(){let r=_(this,Ge,"f")?.response_format;return uo(r)?r:null},$u=function(r){var n,o,s,a;let i=_(this,pt,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=E(this,pt,{...l,choices:[]},"f");for(let{delta:d,finish_reason:m,index:f,logprobs:I=null,...w}of r.choices){let b=i.choices[f];if(b||(b=i.choices[f]={finish_reason:m,index:f,message:{},logprobs:I,...w}),I)if(!b.logprobs)b.logprobs=Object.assign({},I);else{let{content:B,refusal:K,...V}=I;Object.assign(b.logprobs,V),B&&((n=b.logprobs).content??(n.content=[]),b.logprobs.content.push(...B)),K&&((o=b.logprobs).refusal??(o.refusal=[]),b.logprobs.refusal.push(...K))}if(m&&(b.finish_reason=m,_(this,Ge,"f")&&Ga(_(this,Ge,"f")))){if(m==="length")throw new kr;if(m==="content_filter")throw new Cr}if(Object.assign(b,w),!d)continue;let{content:y,refusal:h,function_call:x,role:S,tool_calls:M,...F}=d;if(Object.assign(b.message,F),h&&(b.message.refusal=(b.message.refusal||"")+h),S&&(b.message.role=S),x&&(b.message.function_call?(x.name&&(b.message.function_call.name=x.name),x.arguments&&((s=b.message.function_call).arguments??(s.arguments=""),b.message.function_call.arguments+=x.arguments)):b.message.function_call=x),y&&(b.message.content=(b.message.content||"")+y,!b.message.refusal&&_(this,ee,"m",oi).call(this)&&(b.message.parsed=b.message.content.trim()?Xa(b.message.content):null)),M){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:B,id:K,type:V,function:ie,...Z}of M){let Y=(a=b.message.tool_calls)[B]??(a[B]={});Object.assign(Y,Z),K&&(Y.id=K),V&&(Y.type=V),ie&&(Y.function??(Y.function={name:ie.name??"",arguments:""})),ie?.name&&(Y.function.name=ie.name),ie?.arguments&&(Y.function.arguments+=ie.arguments,Su(_(this,Ge,"f"),Y)&&(Y.function.parsed_arguments=Xa(Y.function.arguments)))}}}return i},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,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 ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function hf(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:a,...i}=t,u={...i,id:r,choices:n.map(({message:l,finish_reason:d,index:m,logprobs:f,...I})=>{if(!d)throw new k(`missing finish_reason for choice ${m}`);let{content:w=null,function_call:b,tool_calls:y,...h}=l,x=l.role;if(!x)throw new k(`missing role for choice ${m}`);if(b){let{arguments:S,name:M}=b;if(S==null)throw new k(`missing function_call.arguments for choice ${m}`);if(!M)throw new k(`missing function_call.name for choice ${m}`);return{...I,message:{content:w,function_call:{arguments:S,name:M},role:x,refusal:l.refusal??null},finish_reason:d,index:m,logprobs:f}}return y?{...I,index:m,finish_reason:d,logprobs:f,message:{...h,role:x,content:w,refusal:l.refusal??null,tool_calls:y.map((S,M)=>{let{function:F,type:B,id:K,...V}=S,{arguments:ie,name:Z,...Y}=F||{};if(K==null)throw new k(`missing choices[${m}].tool_calls[${M}].id
|
|
48
48
|
${gs(t)}`);if(B==null)throw new k(`missing choices[${m}].tool_calls[${M}].type
|
|
49
49
|
${gs(t)}`);if(Z==null)throw new k(`missing choices[${m}].tool_calls[${M}].function.name
|
|
50
50
|
${gs(t)}`);if(ie==null)throw new k(`missing choices[${m}].tool_calls[${M}].function.arguments
|
|
51
|
-
${gs(t)}`);return{...V,id:K,type:B,function:{...Y,name:Z,arguments:ie}}})}}:{...I,message:{...h,content:w,role:x,refusal:l.refusal??null},finish_reason:d,index:m,logprobs:f}}),created:o,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Tu(u,e)}function gs(t){return JSON.stringify(t)}var yo=class t extends Nt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var We=class extends g{constructor(){super(...arguments),this.messages=new Rt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Cu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>co(n,e))}runTools(e,r){return e.stream?yo.runTools(this._client,e,r):go.runTools(this._client,e,r)}stream(e,r){return Nt.createChatCompletion(this._client,e,r)}};We.Messages=Rt;var mt=class extends g{constructor(){super(...arguments),this.completions=new We(this._client)}};mt.Completions=We;var zr=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(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",R,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var jr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Lr=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",de,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",de,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Dr=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 Fr=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(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=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(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",Q,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qr=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(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Br=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 Kr=class extends g{create(e,r,n){return this._client.post(p`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends g{create(e,r,n){return this._client.post(p`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/users`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ft=class extends g{constructor(){super(...arguments),this.users=new Gr(this._client),this.roles=new Kr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",Q,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};ft.Users=Gr;ft.Roles=Kr;var Wr=class extends g{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/api_keys`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends g{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/activate`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/deactivate`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends g{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{create(e,r,n){return this._client.post(p`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/projects/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{create(e,r,n){return this._client.post(p`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/service_accounts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var en=class extends g{create(e,r,n){return this._client.post(p`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/spend_alerts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var tn=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,group_id:s}=r;return this._client.get(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/groups/${e}/roles`,Q,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends g{constructor(){super(...arguments),this.roles=new tn(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(p`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/groups`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};zt.Roles=tn;var rn=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,user_id:s}=r;return this._client.get(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/users/${e}/roles`,Q,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var jt=class extends g{constructor(){super(...arguments),this.roles=new rn(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/users`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};jt.Roles=rn;var oe=class extends g{constructor(){super(...arguments),this.users=new jt(this._client),this.serviceAccounts=new Xr(this._client),this.apiKeys=new Wr(this._client),this.rateLimits=new Qr(this._client),this.modelPermissions=new Zr(this._client),this.hostedToolPermissions=new Jr(this._client),this.groups=new zt(this._client),this.roles=new Yr(this._client),this.dataRetention=new Hr(this._client),this.spendAlerts=new en(this._client),this.certificates=new Vr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};oe.Users=jt;oe.ServiceAccounts=Xr;oe.APIKeys=Wr;oe.RateLimits=Qr;oe.ModelPermissions=Zr;oe.HostedToolPermissions=Jr;oe.Groups=zt;oe.Roles=Yr;oe.DataRetention=Hr;oe.SpendAlerts=en;oe.Certificates=Vr;var nn=class extends g{create(e,r,n){return this._client.post(p`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/users/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Lt=class extends g{constructor(){super(...arguments),this.roles=new nn(this._client)}retrieve(e,r){return this._client.get(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Lt.Roles=nn;var se=class extends g{constructor(){super(...arguments),this.auditLogs=new jr(this._client),this.adminAPIKeys=new zr(this._client),this.usage=new Br(this._client),this.invites=new Fr(this._client),this.users=new Lt(this._client),this.groups=new ft(this._client),this.roles=new Ur(this._client),this.dataRetention=new Dr(this._client),this.spendAlerts=new qr(this._client),this.certificates=new Lr(this._client),this.projects=new oe(this._client)}};se.AuditLogs=jr;se.AdminAPIKeys=zr;se.Usage=Br;se.Invites=Fr;se.Users=Lt;se.Groups=ft;se.Roles=Ur;se.DataRetention=Dr;se.SpendAlerts=qr;se.Certificates=Lr;se.Projects=oe;var ht=class extends g{constructor(){super(...arguments),this.organization=new se(this._client)}};ht.Organization=se;var Nu=Symbol("brand.privateNullableHeaders");function*Kf(t){if(!t)return;if(Nu in t){let{values:n,nulls:o}=t;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Sa(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Sa(n[1])?n[1]:[n[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,i])}}var T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,a]of Kf(n)){let i=s.toLowerCase();o.has(i)||(e.delete(s),o.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[Nu]:!0,values:e,nulls:r}};var on=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 sn=class extends g{create(e,r){return this._client.post("/audio/transcriptions",pe({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var an=class extends g{create(e,r){return this._client.post("/audio/translations",pe({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var je=class extends g{constructor(){super(...arguments),this.transcriptions=new sn(this._client),this.translations=new an(this._client),this.speech=new on(this._client)}};je.Transcriptions=sn;je.Translations=an;je.Speech=on;var Dt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var ln=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(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/assistants/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var un=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 cn=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 gt=class extends g{constructor(){super(...arguments),this.sessions=new un(this._client),this.transcriptionSessions=new cn(this._client)}};gt.Sessions=un;gt.TranscriptionSessions=cn;var dn=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(p`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var pn=class extends g{retrieve(e,r){return this._client.get(p`/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",j,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(p`/chatkit/threads/${e}/items`,j,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var yt=class extends g{constructor(){super(...arguments),this.sessions=new dn(this._client),this.threads=new pn(this._client)}};yt.Sessions=dn;yt.Threads=pn;var mn=class extends g{create(e,r,n){return this._client.post(p`/threads/${e}/messages`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/messages/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/messages`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var fn=class extends g{retrieve(e,r,n){let{thread_id:o,run_id:s,...a}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:a,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(p`/threads/${o}/runs/${e}/steps`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var zu=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var Ie=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 ae,Ut,si,Le,ys,ve,qt,hn,Ft,bs,ye,_s,ws,bo,_o,wo,ju,Lu,Du,Fu,Uu,qu,Bu,Ve=class extends dt{constructor(){super(...arguments),ae.add(this),si.set(this,[]),Le.set(this,{}),ys.set(this,{}),ve.set(this,void 0),qt.set(this,void 0),hn.set(this,void 0),Ft.set(this,void 0),bs.set(this,void 0),ye.set(this,void 0),_s.set(this,void 0),ws.set(this,void 0),bo.set(this,void 0)}[(si=new WeakMap,Le=new WeakMap,ys=new WeakMap,ve=new WeakMap,qt=new WeakMap,hn=new WeakMap,Ft=new WeakMap,bs=new WeakMap,ye=new WeakMap,_s=new WeakMap,ws=new WeakMap,bo=new WeakMap,ae=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,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 Ut;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=ze.fromReadableStream(e,this.controller);for await(let o of n)_(this,ae,"m",_o).call(this,o);if(n.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}toReadableStream(){return new ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Ut;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ae,"m",_o).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}static createThreadAssistantStream(e,r,n){let o=new Ut;return o._run(()=>o._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new Ut;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,_s,"f")}currentRun(){return _(this,ws,"f")}currentMessageSnapshot(){return _(this,ve,"f")}currentRunStepSnapshot(){return _(this,bo,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Le,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ys,"f"))}async finalRun(){if(await this.done(),!_(this,qt,"f"))throw Error("Final run was not received.");return _(this,qt,"f")}async _createThreadAssistantStream(e,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of s)_(this,ae,"m",_o).call(this,a);if(s.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}async _createAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.create(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ae,"m",_o).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}static accumulateDelta(e,r){for(let[n,o]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=o;continue}let s=e[n];if(s==null){e[n]=o;continue}if(n==="index"||n==="type"){e[n]=o;continue}if(typeof s=="string"&&typeof o=="string")s+=o;else if(typeof s=="number"&&typeof o=="number")s+=o;else if(to(s)&&to(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...o);continue}for(let a of o){if(!to(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: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};Ut=Ve,_o=function(e){if(!this.ended)switch(E(this,_s,e,"f"),_(this,ae,"m",Du).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,ae,"m",Bu).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,ae,"m",Lu).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,ae,"m",ju).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},wo=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!_(this,qt,"f"))throw Error("Final run has not been received");return _(this,qt,"f")},ju=function(e){let[r,n]=_(this,ae,"m",Uu).call(this,e,_(this,ve,"f"));E(this,ve,r,"f"),_(this,ys,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,a=r.content[o.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(o.index!=_(this,hn,"f")){if(_(this,Ft,"f"))switch(_(this,Ft,"f").type){case"text":this._emit("textDone",_(this,Ft,"f").text,_(this,ve,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Ft,"f").image_file,_(this,ve,"f"));break}E(this,hn,o.index,"f")}E(this,Ft,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,hn,"f")!==void 0){let o=e.data.content[_(this,hn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,ve,"f"));break;case"text":this._emit("textDone",o.text,_(this,ve,"f"));break}}_(this,ve,"f")&&this._emit("messageDone",e.data),E(this,ve,void 0,"f")}},Lu=function(e){let r=_(this,ae,"m",Fu).call(this,e);switch(E(this,bo,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==_(this,bs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,ye,"f")&&this._emit("toolCallDone",_(this,ye,"f")),E(this,bs,s.index,"f"),E(this,ye,r.step_details.tool_calls[s.index],"f"),_(this,ye,"f")&&this._emit("toolCallCreated",_(this,ye,"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":E(this,bo,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,ye,"f")&&(this._emit("toolCallDone",_(this,ye,"f")),E(this,ye,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Du=function(e){_(this,si,"f").push(e),this._emit("event",e)},Fu=function(e){switch(e.event){case"thread.run.step.created":return _(this,Le,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Le,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=Ut.accumulateDelta(r,n.delta);_(this,Le,"f")[e.data.id]=o}return _(this,Le,"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,Le,"f")[e.data.id]=e.data;break}if(_(this,Le,"f")[e.data.id])return _(this,Le,"f")[e.data.id];throw new Error("No snapshot available")},Uu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=_(this,ae,"m",qu).call(this,s,a)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},qu=function(e,r){return Ut.accumulateDelta(r,e)},Bu=function(e){switch(E(this,ws,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":E(this,qt,e.data,"f"),_(this,ye,"f")&&(this._emit("toolCallDone",_(this,ye,"f")),E(this,ye,void 0,"f"));break;case"thread.run.cancelling":break}};var Bt=class extends g{constructor(){super(...arguments),this.steps=new fn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/runs/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/runs`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(p`/threads/${o}/runs/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return Ve.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await $e(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Ve.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return Ve.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Bt.Steps=fn;var _t=class extends g{constructor(){super(...arguments),this.runs=new Bt(this._client),this.messages=new mn(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(p`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/threads/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/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 n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ve.createThreadAssistantStream(e,this._client.beta.threads,r)}};_t.Runs=Bt;_t.Messages=mn;var Te=class extends g{constructor(){super(...arguments),this.realtime=new gt(this._client),this.chatkit=new yt(this._client),this.assistants=new ln(this._client),this.threads=new _t(this._client)}};Te.Realtime=gt;Te.ChatKit=yt;Te.Assistants=ln;Te.Threads=_t;var Kt=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var gn=class extends g{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Gt=class extends g{constructor(){super(...arguments),this.content=new gn(this._client)}create(e,r,n){return this._client.post(p`/containers/${e}/files`,ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/containers/${e}/files`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(p`/containers/${o}/files/${e}`,{...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Gt.Content=gn;var wt=class extends g{constructor(){super(...arguments),this.files=new Gt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};wt.Files=Gt;var yn=class extends g{create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/conversations/${e}/items`,{query:{include:o},body:s,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{conversation_id:o,...s}=r;return this._client.get(p`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/conversations/${e}/items`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(p`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var bt=class extends g{constructor(){super(...arguments),this.items=new yn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};bt.Items=yn;var Wt=class extends g{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&J(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:o},...r,__security:{bearerAuth:!0}});return n?s:(J(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=zu(u)}),a)))}};var _n=class extends g{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(p`/evals/${o}/runs/${s}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r,n){let{eval_id:o,...s}=r;return this._client.getAPIList(p`/evals/${o}/runs/${e}/output_items`,R,{query:s,...n,__security:{bearerAuth:!0}})}};var Vt=class extends g{constructor(){super(...arguments),this.outputItems=new _n(this._client)}create(e,r,n){return this._client.post(p`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/evals/${e}/runs`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Vt.OutputItems=_n;var xt=class extends g{constructor(){super(...arguments),this.runs=new Vt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};xt.Runs=Vt;var Ht=class extends g{create(e,r){return this._client.post("/files",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(p`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!o.has(a.status);)if(await $e(r),a=await this.retrieve(e),Date.now()-s>n)throw new Oe({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var wn=class extends g{};var bn=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 Jt=class extends g{constructor(){super(...arguments),this.graders=new bn(this._client)}};Jt.Graders=bn;var xn=class extends g{create(e,r,n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(p`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends g{constructor(){super(...arguments),this.permissions=new xn(this._client)}};Zt.Permissions=xn;var An=class extends g{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var Qt=class extends g{constructor(){super(...arguments),this.checkpoints=new An(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/events`,R,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};Qt.Checkpoints=An;var Se=class extends g{constructor(){super(...arguments),this.methods=new wn(this._client),this.jobs=new Qt(this._client),this.checkpoints=new Zt(this._client),this.alpha=new Jt(this._client)}};Se.Methods=wn;Se.Jobs=Qt;Se.Checkpoints=Zt;Se.Alpha=Jt;var In=class extends g{};var At=class extends g{constructor(){super(...arguments),this.graderModels=new In(this._client)}};At.GraderModels=In;var Yt=class extends g{createVariation(e,r){return this._client.post("/images/variations",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",pe({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 Xt=class extends g{retrieve(e,r){return this._client.get(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",de,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var er=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var vn=class extends g{accept(e,r,n){return this._client.post(p`/realtime/calls/${e}/accept`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(p`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(p`/realtime/calls/${e}/refer`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(p`/realtime/calls/${e}/reject`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Tn=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var He=class extends g{constructor(){super(...arguments),this.clientSecrets=new Tn(this._client),this.calls=new vn(this._client)}};He.ClientSecrets=Tn;He.Calls=vn;function Ku(t,e){if(!e||!xh(e)){let r={...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(o=>({...o,parsed:null}))}:n)};return Gu(t,r)&&_e(r),r}return ai(t,e)}function ai(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?vh(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?bh(e,i.text):null}:i);return{...s,content:a}}return s}),o=Object.assign({},t,{output:n});return Gu(t,o)&&_e(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let s of o.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),o}function bh(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function xh(t){return!!uo(t.text?.format)}function Ah(t){return t?.$brand==="auto-parseable-tool"}function Ih(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function vh(t,e){let r=Ih(t.tools??[],e.name);return{...e,...e,parsed_arguments:Ah(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Gu(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function _e(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}function Vu(t,e){if(!e){if(t.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Wu(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&_e(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&_e(e);break}case"response.content_part.added":{let r=z(e,t.output_index),n=r.type,o=t.part;n==="message"&&o.type!=="reasoning_text"?(r.content.push(structuredClone(o)),o.type==="output_text"&&_e(e)):n==="reasoning"&&o.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(o)));break}case"response.content_part.done":{let r=z(e,t.output_index),n=t.part;if(r.type==="message"&&n.type!=="reasoning_text")we(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&_e(e);else if(r.type==="reasoning"&&n.type==="reasoning_text"){let o=r.content;if(!o)throw new k(`missing content at index ${t.content_index}`);we(o,t.content_index),o[t.content_index]=structuredClone(n)}break}case"response.output_text.delta":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.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 n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.text=t.text,_e(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}break}case"response.refusal.done":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.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 k(`missing content at index ${t.content_index}`);let n=we(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.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 k(`missing content at index ${t.content_index}`);let n=we(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.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"&&(we(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 n=we(r.summary,t.summary_index);n.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){let n=we(r.summary,t.summary_index);n.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=Wu(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:Th(t)}return e}function Wu(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&_e(e),e}function z(t,e){let r=t.output[e];if(!r)throw new k(`missing output at index ${e}`);return r}function we(t,e){let r=t[e];if(!r)throw new k(`missing content at index ${e}`);return r}function Th(t){throw new k(`Unhandled response stream event: ${JSON.stringify(t)}`)}var xo,xs,tr,As,Hu,Ju,Zu,Is=class t extends dt{constructor(e){super(),xo.add(this),xs.set(this,void 0),tr.set(this,void 0),As.set(this,void 0),E(this,xs,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){this._listenForAbort(n?.signal),_(this,xo,"m",Hu).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)_(this,xo,"m",Ju).call(this,a,s);if(o.controller.signal?.aborted)throw new W;return _(this,xo,"m",Zu).call(this)}[(xs=new WeakMap,tr=new WeakMap,As=new WeakMap,xo=new WeakSet,Hu=function(){this.ended||E(this,tr,void 0,"f")},Ju=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=Vu(r,_(this,tr,"f"));switch(E(this,tr,s,"f"),o("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new k(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new k(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new k(`expected content to be 'output_text', got ${i.type}`);o("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 k(`missing output at index ${r.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:o(r.type,r);break}},Zu=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,tr,"f");if(!r)throw new k("request ended without sending any events");E(this,tr,void 0,"f");let n=Sh(r,_(this,xs,"f"));return E(this,As,n,"f"),n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,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,As,"f");if(!e)throw new k("stream ended without producing a ChatCompletion");return e}};function Sh(t,e){return Ku(t,e)}var Sn=class extends g{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var kn=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var De=class extends g{constructor(){super(...arguments),this.inputItems=new Sn(this._client),this.inputTokens=new kn(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&_e(n),n))}retrieve(e,r={},n){return this._client.get(p`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&_e(o),o))}delete(e,r){return this._client.delete(p`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>ai(n,e))}stream(e,r){return Is.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(p`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};De.InputItems=Sn;De.InputTokens=kn;var Cn=class extends g{retrieve(e,r){return this._client.get(p`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var En=class extends g{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var rr=class extends g{constructor(){super(...arguments),this.content=new En(this._client)}create(e,r={},n){return this._client.post(p`/skills/${e}/versions`,ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/skills/${e}/versions`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};rr.Content=En;var Je=class extends g{constructor(){super(...arguments),this.content=new Cn(this._client),this.versions=new rr(this._client)}create(e={},r){return this._client.post("/skills",ct({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Je.Content=Cn;Je.Versions=rr;var Pn=class extends g{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,pe({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var It=class extends g{constructor(){super(...arguments),this.parts=new Pn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(p`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};It.Parts=Pn;var Qu=async t=>{let e=await Promise.allSettled(t),r=e.filter(o=>o.status==="rejected");if(r.length){for(let o of r)console.error(o.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let o of e)o.status==="fulfilled"&&n.push(o.value);return n};var Mn=class extends g{create(e,r,n){return this._client.post(p`/vector_stores/${e}/file_batches`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/file_batches/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(p`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(p`/vector_stores/${o}/file_batches/${e}/files`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await $e(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...n];async function d(f){for(let I of f){let w=await i.files.create({file:I,purpose:"assistants"},o);l.push(w.id)}}let m=Array(a).fill(u).map(d);return await Qu(m),await this.createAndPoll(e,{file_ids:l})}};var On=class extends g{create(e,r,n){return this._client.post(p`/vector_stores/${e}/files`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(p`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/vector_stores/${e}/files`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await $e(i);break;case"failed":case"completed":return a}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(p`/vector_stores/${o}/files/${e}/content`,de,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ze=class extends g{constructor(){super(...arguments),this.files=new On(this._client),this.fileBatches=new Mn(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(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/vector_stores/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(p`/vector_stores/${e}/search`,de,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};Ze.Files=On;Ze.FileBatches=Mn;var nr=class extends g{create(e,r){return this._client.post("/videos",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(p`/videos/${e}/content`,{query:r,...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(p`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(p`/videos/${e}/remix`,ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Rn,Yu,vs,or=class extends g{constructor(){super(...arguments),Rn.add(this)}async unwrap(e,r,n=this._client.webhookSecret,o=300){return await this.verifySignature(e,r,n,o),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");_(this,Rn,"m",Yu).call(this,n);let s=T([r]).values,a=_(this,Rn,"m",vs).call(this,s,"webhook-signature"),i=_(this,Rn,"m",vs).call(this,s,"webhook-timestamp"),u=_(this,Rn,"m",vs).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Re("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>o)throw new Re("Webhook timestamp is too old");if(l>d+o)throw new Re("Webhook timestamp is too new");let m=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),I=u?`${u}.${i}.${e}`:`${i}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of m)try{let y=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,y,new TextEncoder().encode(I)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}};Rn=new WeakSet,Yu=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")},vs=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var ec=Symbol.for("openai.node.providerDefinitions.v1"),tc=globalThis,rc=tc[ec],nc=rc??new WeakMap;rc||Object.defineProperty(tc,ec,{value:nc});function oc(t){let e=nc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var ii,li,Ao,sc,Nh="workload-identity-auth",P=class{constructor(e={}){ii.add(this),Ao.set(this,void 0),this.completions=new Kt(this),this.chat=new mt(this),this.embeddings=new Wt(this),this.files=new Ht(this),this.images=new Yt(this),this.audio=new je(this),this.moderations=new er(this),this.models=new Xt(this),this.fineTuning=new Se(this),this.graders=new At(this),this.vectorStores=new Ze(this),this.webhooks=new or(this),this.beta=new Te(this),this.batches=new Dt(this),this.uploads=new It(this),this.admin=new ht(this),this.responses=new De(this),this.realtime=new He(this),this.conversations=new bt(this),this.evals=new xt(this),this.containers=new wt(this),this.skills=new Je(this),this.videos=new nr(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(b.length)throw new k(`The \`provider\` option cannot be used with ${b.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=r?null:Ie("OPENAI_BASE_URL"),apiKey:o=r?null:Ie("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Ie("OPENAI_ADMIN_KEY")??null,organization:a=r?null:Ie("OPENAI_ORG_ID")??null,project:i=r?null:Ie("OPENAI_PROJECT_ID")??null,webhookSecret:u=Ie("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,m=r?oc(r):void 0,f={apiKey:o,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...d,baseURL:m?.baseURL??(n||"https://api.openai.com/v1")};if(o&&l)throw new k("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!m&&!o&&!s&&!l)throw new k("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Xl())throw new k(`It looks like you're running in a browser-like environment.
|
|
51
|
+
${gs(t)}`);return{...V,id:K,type:B,function:{...Y,name:Z,arguments:ie}}})}}:{...I,message:{...h,content:w,role:x,refusal:l.refusal??null},finish_reason:d,index:m,logprobs:f}}),created:o,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Tu(u,e)}function gs(t){return JSON.stringify(t)}var yo=class t extends Nt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var We=class extends g{constructor(){super(...arguments),this.messages=new Rt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Cu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>co(n,e))}runTools(e,r){return e.stream?yo.runTools(this._client,e,r):go.runTools(this._client,e,r)}stream(e,r){return Nt.createChatCompletion(this._client,e,r)}};We.Messages=Rt;var mt=class extends g{constructor(){super(...arguments),this.completions=new We(this._client)}};mt.Completions=We;var zr=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(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",R,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var jr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Lr=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",de,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",de,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Dr=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 Fr=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(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=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(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",Q,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qr=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(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Br=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 Kr=class extends g{create(e,r,n){return this._client.post(p`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends g{create(e,r,n){return this._client.post(p`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/users`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ft=class extends g{constructor(){super(...arguments),this.users=new Gr(this._client),this.roles=new Kr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",Q,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};ft.Users=Gr;ft.Roles=Kr;var Wr=class extends g{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/api_keys`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends g{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/activate`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/deactivate`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends g{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends g{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{create(e,r,n){return this._client.post(p`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/projects/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{create(e,r,n){return this._client.post(p`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/service_accounts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var en=class extends g{create(e,r,n){return this._client.post(p`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/spend_alerts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var tn=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,group_id:s}=r;return this._client.get(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/groups/${e}/roles`,Q,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends g{constructor(){super(...arguments),this.roles=new tn(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(p`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/groups`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};zt.Roles=tn;var rn=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,user_id:s}=r;return this._client.get(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/users/${e}/roles`,Q,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var jt=class extends g{constructor(){super(...arguments),this.roles=new rn(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/users`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};jt.Roles=rn;var oe=class extends g{constructor(){super(...arguments),this.users=new jt(this._client),this.serviceAccounts=new Xr(this._client),this.apiKeys=new Wr(this._client),this.rateLimits=new Qr(this._client),this.modelPermissions=new Zr(this._client),this.hostedToolPermissions=new Jr(this._client),this.groups=new zt(this._client),this.roles=new Yr(this._client),this.dataRetention=new Hr(this._client),this.spendAlerts=new en(this._client),this.certificates=new Vr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};oe.Users=jt;oe.ServiceAccounts=Xr;oe.APIKeys=Wr;oe.RateLimits=Qr;oe.ModelPermissions=Zr;oe.HostedToolPermissions=Jr;oe.Groups=zt;oe.Roles=Yr;oe.DataRetention=Hr;oe.SpendAlerts=en;oe.Certificates=Vr;var nn=class extends g{create(e,r,n){return this._client.post(p`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/users/${e}/roles`,Q,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Lt=class extends g{constructor(){super(...arguments),this.roles=new nn(this._client)}retrieve(e,r){return this._client.get(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Lt.Roles=nn;var se=class extends g{constructor(){super(...arguments),this.auditLogs=new jr(this._client),this.adminAPIKeys=new zr(this._client),this.usage=new Br(this._client),this.invites=new Fr(this._client),this.users=new Lt(this._client),this.groups=new ft(this._client),this.roles=new Ur(this._client),this.dataRetention=new Dr(this._client),this.spendAlerts=new qr(this._client),this.certificates=new Lr(this._client),this.projects=new oe(this._client)}};se.AuditLogs=jr;se.AdminAPIKeys=zr;se.Usage=Br;se.Invites=Fr;se.Users=Lt;se.Groups=ft;se.Roles=Ur;se.DataRetention=Dr;se.SpendAlerts=qr;se.Certificates=Lr;se.Projects=oe;var ht=class extends g{constructor(){super(...arguments),this.organization=new se(this._client)}};ht.Organization=se;var Nu=Symbol("brand.privateNullableHeaders");function*Gf(t){if(!t)return;if(Nu in t){let{values:n,nulls:o}=t;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Sa(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Sa(n[1])?n[1]:[n[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,i])}}var T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,a]of Gf(n)){let i=s.toLowerCase();o.has(i)||(e.delete(s),o.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[Nu]:!0,values:e,nulls:r}};var on=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 sn=class extends g{create(e,r){return this._client.post("/audio/transcriptions",pe({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var an=class extends g{create(e,r){return this._client.post("/audio/translations",pe({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var je=class extends g{constructor(){super(...arguments),this.transcriptions=new sn(this._client),this.translations=new an(this._client),this.speech=new on(this._client)}};je.Transcriptions=sn;je.Translations=an;je.Speech=on;var Dt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var ln=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(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/assistants/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var un=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 cn=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 gt=class extends g{constructor(){super(...arguments),this.sessions=new un(this._client),this.transcriptionSessions=new cn(this._client)}};gt.Sessions=un;gt.TranscriptionSessions=cn;var dn=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(p`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var pn=class extends g{retrieve(e,r){return this._client.get(p`/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",j,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(p`/chatkit/threads/${e}/items`,j,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var yt=class extends g{constructor(){super(...arguments),this.sessions=new dn(this._client),this.threads=new pn(this._client)}};yt.Sessions=dn;yt.Threads=pn;var mn=class extends g{create(e,r,n){return this._client.post(p`/threads/${e}/messages`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/messages/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/messages`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var fn=class extends g{retrieve(e,r,n){let{thread_id:o,run_id:s,...a}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:a,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(p`/threads/${o}/runs/${e}/steps`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var zu=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var Ie=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 ae,Ut,si,Le,ys,ve,qt,hn,Ft,bs,ye,_s,ws,bo,_o,wo,ju,Lu,Du,Fu,Uu,qu,Bu,Ve=class extends dt{constructor(){super(...arguments),ae.add(this),si.set(this,[]),Le.set(this,{}),ys.set(this,{}),ve.set(this,void 0),qt.set(this,void 0),hn.set(this,void 0),Ft.set(this,void 0),bs.set(this,void 0),ye.set(this,void 0),_s.set(this,void 0),ws.set(this,void 0),bo.set(this,void 0)}[(si=new WeakMap,Le=new WeakMap,ys=new WeakMap,ve=new WeakMap,qt=new WeakMap,hn=new WeakMap,Ft=new WeakMap,bs=new WeakMap,ye=new WeakMap,_s=new WeakMap,ws=new WeakMap,bo=new WeakMap,ae=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,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 Ut;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=ze.fromReadableStream(e,this.controller);for await(let o of n)_(this,ae,"m",_o).call(this,o);if(n.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}toReadableStream(){return new ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Ut;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ae,"m",_o).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}static createThreadAssistantStream(e,r,n){let o=new Ut;return o._run(()=>o._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new Ut;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,_s,"f")}currentRun(){return _(this,ws,"f")}currentMessageSnapshot(){return _(this,ve,"f")}currentRunStepSnapshot(){return _(this,bo,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Le,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ys,"f"))}async finalRun(){if(await this.done(),!_(this,qt,"f"))throw Error("Final run was not received.");return _(this,qt,"f")}async _createThreadAssistantStream(e,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of s)_(this,ae,"m",_o).call(this,a);if(s.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}async _createAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.create(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)_(this,ae,"m",_o).call(this,i);if(a.controller.signal?.aborted)throw new W;return this._addRun(_(this,ae,"m",wo).call(this))}static accumulateDelta(e,r){for(let[n,o]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=o;continue}let s=e[n];if(s==null){e[n]=o;continue}if(n==="index"||n==="type"){e[n]=o;continue}if(typeof s=="string"&&typeof o=="string")s+=o;else if(typeof s=="number"&&typeof o=="number")s+=o;else if(to(s)&&to(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...o);continue}for(let a of o){if(!to(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: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};Ut=Ve,_o=function(e){if(!this.ended)switch(E(this,_s,e,"f"),_(this,ae,"m",Du).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,ae,"m",Bu).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,ae,"m",Lu).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,ae,"m",ju).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},wo=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!_(this,qt,"f"))throw Error("Final run has not been received");return _(this,qt,"f")},ju=function(e){let[r,n]=_(this,ae,"m",Uu).call(this,e,_(this,ve,"f"));E(this,ve,r,"f"),_(this,ys,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,a=r.content[o.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(o.index!=_(this,hn,"f")){if(_(this,Ft,"f"))switch(_(this,Ft,"f").type){case"text":this._emit("textDone",_(this,Ft,"f").text,_(this,ve,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Ft,"f").image_file,_(this,ve,"f"));break}E(this,hn,o.index,"f")}E(this,Ft,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,hn,"f")!==void 0){let o=e.data.content[_(this,hn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,ve,"f"));break;case"text":this._emit("textDone",o.text,_(this,ve,"f"));break}}_(this,ve,"f")&&this._emit("messageDone",e.data),E(this,ve,void 0,"f")}},Lu=function(e){let r=_(this,ae,"m",Fu).call(this,e);switch(E(this,bo,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==_(this,bs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,ye,"f")&&this._emit("toolCallDone",_(this,ye,"f")),E(this,bs,s.index,"f"),E(this,ye,r.step_details.tool_calls[s.index],"f"),_(this,ye,"f")&&this._emit("toolCallCreated",_(this,ye,"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":E(this,bo,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,ye,"f")&&(this._emit("toolCallDone",_(this,ye,"f")),E(this,ye,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Du=function(e){_(this,si,"f").push(e),this._emit("event",e)},Fu=function(e){switch(e.event){case"thread.run.step.created":return _(this,Le,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Le,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=Ut.accumulateDelta(r,n.delta);_(this,Le,"f")[e.data.id]=o}return _(this,Le,"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,Le,"f")[e.data.id]=e.data;break}if(_(this,Le,"f")[e.data.id])return _(this,Le,"f")[e.data.id];throw new Error("No snapshot available")},Uu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=_(this,ae,"m",qu).call(this,s,a)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},qu=function(e,r){return Ut.accumulateDelta(r,e)},Bu=function(e){switch(E(this,ws,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":E(this,qt,e.data,"f"),_(this,ye,"f")&&(this._emit("toolCallDone",_(this,ye,"f")),E(this,ye,void 0,"f"));break;case"thread.run.cancelling":break}};var Bt=class extends g{constructor(){super(...arguments),this.steps=new fn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/runs/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/runs`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(p`/threads/${o}/runs/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return Ve.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await $e(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Ve.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return Ve.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Bt.Steps=fn;var _t=class extends g{constructor(){super(...arguments),this.runs=new Bt(this._client),this.messages=new mn(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(p`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/threads/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/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 n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ve.createThreadAssistantStream(e,this._client.beta.threads,r)}};_t.Runs=Bt;_t.Messages=mn;var Te=class extends g{constructor(){super(...arguments),this.realtime=new gt(this._client),this.chatkit=new yt(this._client),this.assistants=new ln(this._client),this.threads=new _t(this._client)}};Te.Realtime=gt;Te.ChatKit=yt;Te.Assistants=ln;Te.Threads=_t;var Kt=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var gn=class extends g{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Gt=class extends g{constructor(){super(...arguments),this.content=new gn(this._client)}create(e,r,n){return this._client.post(p`/containers/${e}/files`,ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/containers/${e}/files`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(p`/containers/${o}/files/${e}`,{...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Gt.Content=gn;var wt=class extends g{constructor(){super(...arguments),this.files=new Gt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};wt.Files=Gt;var yn=class extends g{create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/conversations/${e}/items`,{query:{include:o},body:s,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{conversation_id:o,...s}=r;return this._client.get(p`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/conversations/${e}/items`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(p`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var bt=class extends g{constructor(){super(...arguments),this.items=new yn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};bt.Items=yn;var Wt=class extends g{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&J(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:o},...r,__security:{bearerAuth:!0}});return n?s:(J(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=zu(u)}),a)))}};var _n=class extends g{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(p`/evals/${o}/runs/${s}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r,n){let{eval_id:o,...s}=r;return this._client.getAPIList(p`/evals/${o}/runs/${e}/output_items`,R,{query:s,...n,__security:{bearerAuth:!0}})}};var Vt=class extends g{constructor(){super(...arguments),this.outputItems=new _n(this._client)}create(e,r,n){return this._client.post(p`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/evals/${e}/runs`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Vt.OutputItems=_n;var xt=class extends g{constructor(){super(...arguments),this.runs=new Vt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};xt.Runs=Vt;var Ht=class extends g{create(e,r){return this._client.post("/files",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(p`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!o.has(a.status);)if(await $e(r),a=await this.retrieve(e),Date.now()-s>n)throw new Oe({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var wn=class extends g{};var bn=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 Jt=class extends g{constructor(){super(...arguments),this.graders=new bn(this._client)}};Jt.Graders=bn;var xn=class extends g{create(e,r,n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(p`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends g{constructor(){super(...arguments),this.permissions=new xn(this._client)}};Zt.Permissions=xn;var An=class extends g{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var Qt=class extends g{constructor(){super(...arguments),this.checkpoints=new An(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/events`,R,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};Qt.Checkpoints=An;var Se=class extends g{constructor(){super(...arguments),this.methods=new wn(this._client),this.jobs=new Qt(this._client),this.checkpoints=new Zt(this._client),this.alpha=new Jt(this._client)}};Se.Methods=wn;Se.Jobs=Qt;Se.Checkpoints=Zt;Se.Alpha=Jt;var In=class extends g{};var At=class extends g{constructor(){super(...arguments),this.graderModels=new In(this._client)}};At.GraderModels=In;var Yt=class extends g{createVariation(e,r){return this._client.post("/images/variations",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",pe({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 Xt=class extends g{retrieve(e,r){return this._client.get(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",de,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var er=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var vn=class extends g{accept(e,r,n){return this._client.post(p`/realtime/calls/${e}/accept`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(p`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(p`/realtime/calls/${e}/refer`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(p`/realtime/calls/${e}/reject`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Tn=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var He=class extends g{constructor(){super(...arguments),this.clientSecrets=new Tn(this._client),this.calls=new vn(this._client)}};He.ClientSecrets=Tn;He.Calls=vn;function Ku(t,e){if(!e||!Ah(e)){let r={...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(o=>({...o,parsed:null}))}:n)};return Gu(t,r)&&_e(r),r}return ai(t,e)}function ai(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?Th(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?xh(e,i.text):null}:i);return{...s,content:a}}return s}),o=Object.assign({},t,{output:n});return Gu(t,o)&&_e(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let s of o.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),o}function xh(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Ah(t){return!!uo(t.text?.format)}function Ih(t){return t?.$brand==="auto-parseable-tool"}function vh(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Th(t,e){let r=vh(t.tools??[],e.name);return{...e,...e,parsed_arguments:Ih(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Gu(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function _e(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}function Vu(t,e){if(!e){if(t.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Wu(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&_e(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&_e(e);break}case"response.content_part.added":{let r=z(e,t.output_index),n=r.type,o=t.part;n==="message"&&o.type!=="reasoning_text"?(r.content.push(structuredClone(o)),o.type==="output_text"&&_e(e)):n==="reasoning"&&o.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(o)));break}case"response.content_part.done":{let r=z(e,t.output_index),n=t.part;if(r.type==="message"&&n.type!=="reasoning_text")we(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&_e(e);else if(r.type==="reasoning"&&n.type==="reasoning_text"){let o=r.content;if(!o)throw new k(`missing content at index ${t.content_index}`);we(o,t.content_index),o[t.content_index]=structuredClone(n)}break}case"response.output_text.delta":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.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 n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.text=t.text,_e(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}break}case"response.refusal.done":{let r=z(e,t.output_index);if(r.type==="message"){let n=we(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.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 k(`missing content at index ${t.content_index}`);let n=we(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.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 k(`missing content at index ${t.content_index}`);let n=we(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.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"&&(we(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 n=we(r.summary,t.summary_index);n.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=z(e,t.output_index);if(r.type==="reasoning"){let n=we(r.summary,t.summary_index);n.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=Wu(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:Sh(t)}return e}function Wu(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&_e(e),e}function z(t,e){let r=t.output[e];if(!r)throw new k(`missing output at index ${e}`);return r}function we(t,e){let r=t[e];if(!r)throw new k(`missing content at index ${e}`);return r}function Sh(t){throw new k(`Unhandled response stream event: ${JSON.stringify(t)}`)}var xo,xs,tr,As,Hu,Ju,Zu,Is=class t extends dt{constructor(e){super(),xo.add(this),xs.set(this,void 0),tr.set(this,void 0),As.set(this,void 0),E(this,xs,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){this._listenForAbort(n?.signal),_(this,xo,"m",Hu).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)_(this,xo,"m",Ju).call(this,a,s);if(o.controller.signal?.aborted)throw new W;return _(this,xo,"m",Zu).call(this)}[(xs=new WeakMap,tr=new WeakMap,As=new WeakMap,xo=new WeakSet,Hu=function(){this.ended||E(this,tr,void 0,"f")},Ju=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=Vu(r,_(this,tr,"f"));switch(E(this,tr,s,"f"),o("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new k(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new k(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new k(`expected content to be 'output_text', got ${i.type}`);o("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 k(`missing output at index ${r.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:o(r.type,r);break}},Zu=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,tr,"f");if(!r)throw new k("request ended without sending any events");E(this,tr,void 0,"f");let n=kh(r,_(this,xs,"f"));return E(this,As,n,"f"),n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,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,As,"f");if(!e)throw new k("stream ended without producing a ChatCompletion");return e}};function kh(t,e){return Ku(t,e)}var Sn=class extends g{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var kn=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var De=class extends g{constructor(){super(...arguments),this.inputItems=new Sn(this._client),this.inputTokens=new kn(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&_e(n),n))}retrieve(e,r={},n){return this._client.get(p`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&_e(o),o))}delete(e,r){return this._client.delete(p`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>ai(n,e))}stream(e,r){return Is.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(p`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};De.InputItems=Sn;De.InputTokens=kn;var Cn=class extends g{retrieve(e,r){return this._client.get(p`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var En=class extends g{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var rr=class extends g{constructor(){super(...arguments),this.content=new En(this._client)}create(e,r={},n){return this._client.post(p`/skills/${e}/versions`,ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/skills/${e}/versions`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};rr.Content=En;var Je=class extends g{constructor(){super(...arguments),this.content=new Cn(this._client),this.versions=new rr(this._client)}create(e={},r){return this._client.post("/skills",ct({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Je.Content=Cn;Je.Versions=rr;var Pn=class extends g{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,pe({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var It=class extends g{constructor(){super(...arguments),this.parts=new Pn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(p`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};It.Parts=Pn;var Qu=async t=>{let e=await Promise.allSettled(t),r=e.filter(o=>o.status==="rejected");if(r.length){for(let o of r)console.error(o.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let o of e)o.status==="fulfilled"&&n.push(o.value);return n};var Mn=class extends g{create(e,r,n){return this._client.post(p`/vector_stores/${e}/file_batches`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/file_batches/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(p`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(p`/vector_stores/${o}/file_batches/${e}/files`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await $e(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...n];async function d(f){for(let I of f){let w=await i.files.create({file:I,purpose:"assistants"},o);l.push(w.id)}}let m=Array(a).fill(u).map(d);return await Qu(m),await this.createAndPoll(e,{file_ids:l})}};var On=class extends g{create(e,r,n){return this._client.post(p`/vector_stores/${e}/files`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(p`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/vector_stores/${e}/files`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await $e(i);break;case"failed":case"completed":return a}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(p`/vector_stores/${o}/files/${e}/content`,de,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ze=class extends g{constructor(){super(...arguments),this.files=new On(this._client),this.fileBatches=new Mn(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(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/vector_stores/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(p`/vector_stores/${e}/search`,de,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};Ze.Files=On;Ze.FileBatches=Mn;var nr=class extends g{create(e,r){return this._client.post("/videos",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(p`/videos/${e}/content`,{query:r,...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(p`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(p`/videos/${e}/remix`,ct({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Rn,Yu,vs,or=class extends g{constructor(){super(...arguments),Rn.add(this)}async unwrap(e,r,n=this._client.webhookSecret,o=300){return await this.verifySignature(e,r,n,o),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");_(this,Rn,"m",Yu).call(this,n);let s=T([r]).values,a=_(this,Rn,"m",vs).call(this,s,"webhook-signature"),i=_(this,Rn,"m",vs).call(this,s,"webhook-timestamp"),u=_(this,Rn,"m",vs).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Re("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>o)throw new Re("Webhook timestamp is too old");if(l>d+o)throw new Re("Webhook timestamp is too new");let m=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),I=u?`${u}.${i}.${e}`:`${i}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of m)try{let y=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,y,new TextEncoder().encode(I)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}};Rn=new WeakSet,Yu=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")},vs=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var ec=Symbol.for("openai.node.providerDefinitions.v1"),tc=globalThis,rc=tc[ec],nc=rc??new WeakMap;rc||Object.defineProperty(tc,ec,{value:nc});function oc(t){let e=nc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var ii,li,Ao,sc,zh="workload-identity-auth",P=class{constructor(e={}){ii.add(this),Ao.set(this,void 0),this.completions=new Kt(this),this.chat=new mt(this),this.embeddings=new Wt(this),this.files=new Ht(this),this.images=new Yt(this),this.audio=new je(this),this.moderations=new er(this),this.models=new Xt(this),this.fineTuning=new Se(this),this.graders=new At(this),this.vectorStores=new Ze(this),this.webhooks=new or(this),this.beta=new Te(this),this.batches=new Dt(this),this.uploads=new It(this),this.admin=new ht(this),this.responses=new De(this),this.realtime=new He(this),this.conversations=new bt(this),this.evals=new xt(this),this.containers=new wt(this),this.skills=new Je(this),this.videos=new nr(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(y=>e[y]!=null);if(b.length)throw new k(`The \`provider\` option cannot be used with ${b.map(y=>`\`${y}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=r?null:Ie("OPENAI_BASE_URL"),apiKey:o=r?null:Ie("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Ie("OPENAI_ADMIN_KEY")??null,organization:a=r?null:Ie("OPENAI_ORG_ID")??null,project:i=r?null:Ie("OPENAI_PROJECT_ID")??null,webhookSecret:u=Ie("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,m=r?oc(r):void 0,f={apiKey:o,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...d,baseURL:m?.baseURL??(n||"https://api.openai.com/v1")};if(o&&l)throw new k("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!m&&!o&&!s&&!l)throw new k("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Xl())throw new k(`It looks like you're running in a browser-like environment.
|
|
52
52
|
|
|
53
53
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
54
54
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -58,26 +58,26 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
58
58
|
|
|
59
59
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
60
60
|
`);this.baseURL=f.baseURL,this.timeout=f.timeout??li.DEFAULT_TIMEOUT,this.logger=f.logger??console;let I="warn";this.logLevel=I,this.logLevel=La(f.logLevel,"ClientOptions.logLevel",this)??La(Ie("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??I,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??Qo(),E(this,Ao,ru,"f");let w=r?void 0:Ie("OPENAI_CUSTOM_HEADERS");if(w){let b={};for(let y of w.split(`
|
|
61
|
-
`)){let h=y.indexOf(":");h>=0&&(b[y.substring(0,h).trim()]=y.substring(h+1).trim())}f.defaultHeaders=T([b,f.defaultHeaders])}this._options=f,this._provider=m,l&&(this._workloadIdentityAuth=new os(l,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,n=e.provider??r,o={...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 n&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,n!==r&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return 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 du(e)}getUserAgent(){return`${this.constructor.name}/JS ${ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ta()}`}makeStatusError(e,r,n,o){return G.generate(e,r,n,o)}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(n){throw n instanceof k?n:new k(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,ii,"m",sc).call(this)&&n||this.baseURL,s=Wl(e)?new URL(e):new URL(o+(o.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:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Ot(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:a,url:i,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:o}),await this._provider?.prepareRequest?.(a,{url:i,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(J(this).debug(`[${l}] sending request`,Be({retryOfRequestLogID:n,method:o.method,url:i,options:o,headers:a.headers})),o.signal?.aborted)throw new W;let f=o.__security??{bearerAuth:!0},I=new AbortController,w=await this.fetchWithAuth(i,a,u,I,f).catch(Xn),b=Date.now();if(w instanceof globalThis.Error){let x=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new W;let S=Yn(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return J(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${x}`),J(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${x})`,Be({retryOfRequestLogID:n,url:i,durationMs:b-m,message:w.message})),this.retryRequest(o,r,n??l);throw J(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),J(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,Be({retryOfRequestLogID:n,url:i,durationMs:b-m,message:w.message})),w instanceof Pt||w instanceof eo?w:S?new Oe:new lt({message:zh(w),cause:w})}let y=[...w.headers.entries()].filter(([x])=>x==="x-request-id").map(([x,S])=>", "+x+": "+JSON.stringify(S)).join(""),h=`[${l}${d}${y}] ${a.method} ${i} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-m}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Pa(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let x=await this.shouldRetry(w);if(r&&x){let V=`retrying, ${r} attempts remaining`;return await Pa(w.body),J(this).info(`${h} - ${V}`),J(this).debug(`[${l}] response error (${V})`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),this.retryRequest(o,r,n??l,w.headers)}let S=x?"error; no more retries left":"error; not retryable";J(this).info(`${h} - ${S}`);let M=await w.text().catch(V=>Xn(V).message),F=Jl(M),B=F?void 0:M;throw J(this).debug(`[${l}] response error (${S})`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:B,durationMs:Date.now()-m})),this.makeStatusError(w.status,F,B,w.headers)}return J(this).info(h),J(this).debug(`[${l}] response start`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),{response:w,options:o,controller:I,requestLogID:l,retryOfRequestLogID:n,startTime:m}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new so(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${Nh}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(o);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,m={signal:o.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(m.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,a=o?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=o?.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 $e(s),this.makeRequest(e,r-1,n)}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 n={...e},{method:o,path:s,query:a,defaultBaseURL:i}=n,u=this.buildURL(s,a,i);"timeout"in n&&Hl("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:d,isStreamingBody:m}=this.buildBody({options:n});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...eu(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,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:n}=e;if(!r)return r===void 0&&"body"in e?{..._(this,Ao,"f").call(this,{body:r,headers:T([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=T([n]),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"&&o.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:Yo(r),isStreamingBody:!0}:typeof r=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,Ao,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};li=P,Ao=new WeakMap,ii=new WeakSet,sc=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=li;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=k;P.APIError=G;P.APIConnectionError=lt;P.APIConnectionTimeoutError=Oe;P.APIUserAbortError=W;P.NotFoundError=Ar;P.ConflictError=Ir;P.RateLimitError=Tr;P.BadRequestError=wr;P.AuthenticationError=br;P.InternalServerError=Sr;P.PermissionDeniedError=xr;P.UnprocessableEntityError=vr;P.InvalidWebhookSignatureError=Re;P.toFile=io;P.Completions=Kt;P.Chat=mt;P.Embeddings=Wt;P.Files=Ht;P.Images=Yt;P.Audio=je;P.Moderations=er;P.Models=Xt;P.FineTuning=Se;P.Graders=At;P.VectorStores=Ze;P.Webhooks=or;P.Beta=Te;P.Batches=Dt;P.Uploads=It;P.Admin=ht;P.Responses=De;P.Realtime=He;P.Conversations=bt;P.Evals=xt;P.Containers=wt;P.Skills=Je;P.Videos=nr;function zh(t){if(jh(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 jh(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}function Lh(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 be(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Oe.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===W.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Lh(t)?e=al.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Qn(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Qn(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Qn(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Qn(t,"MODEL_NOT_FOUND"):e=t,e}var ke=t=>t();function Qe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Dh(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 Ts(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Fh="LC_AUTOGENERATED";function sr(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'."),Fh)}function Ye(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(!Lo.isInstance(t))throw new Error("Invalid generic chat message");return Dh(t);default:throw new Error(`Unknown message type: ${e}`)}}function ac(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function Xe(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(n||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 ic(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(([,n])=>typeof n=="string").map(([n,o])=>[n,o]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function lc(){let t=sl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function et(t,e=!1,r="1.0.0"){let n=ic(t),o=lc(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function uc(t,e){let r;return yr(t)?r=fa(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Uh(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function cc(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(dc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
61
|
+
`)){let h=y.indexOf(":");h>=0&&(b[y.substring(0,h).trim()]=y.substring(h+1).trim())}f.defaultHeaders=T([b,f.defaultHeaders])}this._options=f,this._provider=m,l&&(this._workloadIdentityAuth=new os(l,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,n=e.provider??r,o={...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 n&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,n!==r&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return 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 du(e)}getUserAgent(){return`${this.constructor.name}/JS ${ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ta()}`}makeStatusError(e,r,n,o){return G.generate(e,r,n,o)}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(n){throw n instanceof k?n:new k(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,ii,"m",sc).call(this)&&n||this.baseURL,s=Wl(e)?new URL(e):new URL(o+(o.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:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Ot(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:a,url:i,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:o}),await this._provider?.prepareRequest?.(a,{url:i,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(J(this).debug(`[${l}] sending request`,Be({retryOfRequestLogID:n,method:o.method,url:i,options:o,headers:a.headers})),o.signal?.aborted)throw new W;let f=o.__security??{bearerAuth:!0},I=new AbortController,w=await this.fetchWithAuth(i,a,u,I,f).catch(Xn),b=Date.now();if(w instanceof globalThis.Error){let x=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new W;let S=Yn(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return J(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${x}`),J(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${x})`,Be({retryOfRequestLogID:n,url:i,durationMs:b-m,message:w.message})),this.retryRequest(o,r,n??l);throw J(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),J(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,Be({retryOfRequestLogID:n,url:i,durationMs:b-m,message:w.message})),w instanceof Pt||w instanceof eo?w:S?new Oe:new lt({message:jh(w),cause:w})}let y=[...w.headers.entries()].filter(([x])=>x==="x-request-id").map(([x,S])=>", "+x+": "+JSON.stringify(S)).join(""),h=`[${l}${d}${y}] ${a.method} ${i} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-m}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Pa(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let x=await this.shouldRetry(w);if(r&&x){let V=`retrying, ${r} attempts remaining`;return await Pa(w.body),J(this).info(`${h} - ${V}`),J(this).debug(`[${l}] response error (${V})`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),this.retryRequest(o,r,n??l,w.headers)}let S=x?"error; no more retries left":"error; not retryable";J(this).info(`${h} - ${S}`);let M=await w.text().catch(V=>Xn(V).message),F=Jl(M),B=F?void 0:M;throw J(this).debug(`[${l}] response error (${S})`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:B,durationMs:Date.now()-m})),this.makeStatusError(w.status,F,B,w.headers)}return J(this).info(h),J(this).debug(`[${l}] response start`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),{response:w,options:o,controller:I,requestLogID:l,retryOfRequestLogID:n,startTime:m}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new so(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${zh}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(o);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,m={signal:o.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(m.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,a=o?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=o?.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 $e(s),this.makeRequest(e,r-1,n)}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 n={...e},{method:o,path:s,query:a,defaultBaseURL:i}=n,u=this.buildURL(s,a,i);"timeout"in n&&Hl("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:d,isStreamingBody:m}=this.buildBody({options:n});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...eu(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,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:n}=e;if(!r)return r===void 0&&"body"in e?{..._(this,Ao,"f").call(this,{body:r,headers:T([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=T([n]),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"&&o.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:Yo(r),isStreamingBody:!0}:typeof r=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,Ao,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};li=P,Ao=new WeakMap,ii=new WeakSet,sc=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=li;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=k;P.APIError=G;P.APIConnectionError=lt;P.APIConnectionTimeoutError=Oe;P.APIUserAbortError=W;P.NotFoundError=Ar;P.ConflictError=Ir;P.RateLimitError=Tr;P.BadRequestError=wr;P.AuthenticationError=br;P.InternalServerError=Sr;P.PermissionDeniedError=xr;P.UnprocessableEntityError=vr;P.InvalidWebhookSignatureError=Re;P.toFile=io;P.Completions=Kt;P.Chat=mt;P.Embeddings=Wt;P.Files=Ht;P.Images=Yt;P.Audio=je;P.Moderations=er;P.Models=Xt;P.FineTuning=Se;P.Graders=At;P.VectorStores=Ze;P.Webhooks=or;P.Beta=Te;P.Batches=Dt;P.Uploads=It;P.Admin=ht;P.Responses=De;P.Realtime=He;P.Conversations=bt;P.Evals=xt;P.Containers=wt;P.Skills=Je;P.Videos=nr;function jh(t){if(Lh(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 Lh(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}function Dh(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 be(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Oe.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===W.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Dh(t)?e=al.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Qn(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Qn(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Qn(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Qn(t,"MODEL_NOT_FOUND"):e=t,e}var ke=t=>t();function Qe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Fh(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 Ts(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Uh="LC_AUTOGENERATED";function sr(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'."),Uh)}function Ye(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(!Lo.isInstance(t))throw new Error("Invalid generic chat message");return Fh(t);default:throw new Error(`Unknown message type: ${e}`)}}function ac(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function Xe(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(n||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 ic(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(([,n])=>typeof n=="string").map(([n,o])=>[n,o]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function lc(){let t=sl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function et(t,e=!1,r="1.0.0"){let n=ic(t),o=lc(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function uc(t,e){let r;return yr(t)?r=fa(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function qh(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function cc(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(dc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
62
62
|
`)}function dc(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${Ss(o,e)},`):r.push(`${n}?: ${Ss(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
|
|
63
|
-
`)}function Ss(t,e){if(
|
|
64
|
-
`);case"array":return t.items?`${Ss(t.items,e)}[]`:"any[]";default:return""}}function ks(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 $n(t){return"type"in t&&t.type!=="function"}function pc(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 mc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function ar(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Cs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function fc(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 hc(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 gc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function yc(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 _c(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 wc(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 xc=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"},Ac=t=>typeof t=="string"?{...bc,basePath:["#"],definitions:{},name:t}:{...bc,basePath:["#"],definitions:{},...t};var Io=t=>"_def"in t?t._def:t;function Ic(t){if(!t)return!0;for(let e in t)return!1;return!0}var vc=t=>{let e=Ac(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[Io(o),{def:Io(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function di(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function L(t,e,r,n,o){t[e]=r,di(t,e,n,o)}function Tc(){return{}}function Sc(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=O(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&L(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&L(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(L(r,"minItems",t.exactLength.value,t.exactLength.message,e),L(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function kc(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function Cc(){return{type:"boolean"}}function Ec(t,e,r){return O(t.type._def,e,r)}var Pc=(t,e,r)=>O(t.innerType._def,e,r);function pi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>pi(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return qh(t,e)}}var qh=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":L(r,"minimum",n.value,n.message,e);break;case"max":L(r,"maximum",n.value,n.message,e);break}return r};function Mc(t,e,r){return{...O(t.innerType._def,e,r),default:t.defaultValue()}}function Oc(t,e,r){return e.effectStrategy==="input"?O(t.schema._def,e,r):{}}function Rc(t){return{type:"string",enum:[...t.values]}}var Bh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function $c(t,e){let r=[O(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),O(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Bh(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function Nc(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,ir={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 Es(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Kh(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":L(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":L(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ce(r,"email",o.message,e);break;case"format:idn-email":Ce(r,"idn-email",o.message,e);break;case"pattern:zod":Ee(r,ir.email,o.message,e);break}break;case"url":Ce(r,"uri",o.message,e);break;case"uuid":Ce(r,"uuid",o.message,e);break;case"regex":Ee(r,o.regex,o.message,e);break;case"cuid":Ee(r,ir.cuid,o.message,e);break;case"cuid2":Ee(r,ir.cuid2,o.message,e);break;case"startsWith":Ee(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":Ee(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Ce(r,"date-time",o.message,e);break;case"date":Ce(r,"date",o.message,e);break;case"time":Ce(r,"time",o.message,e);break;case"duration":Ce(r,"duration",o.message,e);break;case"length":L(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),L(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{Ee(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ce(r,"ipv4",o.message,e),o.version!=="v4"&&Ce(r,"ipv6",o.message,e);break}case"emoji":Ee(r,ir.emoji,o.message,e);break;case"ulid":{Ee(r,ir.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ce(r,"binary",o.message,e);break}case"contentEncoding:base64":{L(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Ee(r,ir.base64,o.message,e);break}}break}case"nanoid":Ee(r,ir.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Kh=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ce=(t,e,r,n)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):L(t,"format",e,r,n)},Ee=(t,e,r,n)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:zc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):L(t,"pattern",zc(e,n),r,n)},zc=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<o.length;l++){if(a){s+=o[l],a=!1;continue}if(n.i){if(i){if(o[l].match(/[a-z]/)){u?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],u=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
|
|
63
|
+
`)}function Ss(t,e){if(qh(t))return t.anyOf.map(r=>Ss(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["{",dc(t,e+2),"}"].join(`
|
|
64
|
+
`);case"array":return t.items?`${Ss(t.items,e)}[]`:"any[]";default:return""}}function ks(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 $n(t){return"type"in t&&t.type!=="function"}function pc(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 mc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function ar(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Cs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function fc(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 hc(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 gc(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function yc(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 _c(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 wc(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 xc=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"},Ac=t=>typeof t=="string"?{...bc,basePath:["#"],definitions:{},name:t}:{...bc,basePath:["#"],definitions:{},...t};var Io=t=>"_def"in t?t._def:t;function Ic(t){if(!t)return!0;for(let e in t)return!1;return!0}var vc=t=>{let e=Ac(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[Io(o),{def:Io(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function di(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function L(t,e,r,n,o){t[e]=r,di(t,e,n,o)}function Tc(){return{}}function Sc(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=O(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&L(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&L(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(L(r,"minItems",t.exactLength.value,t.exactLength.message,e),L(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function kc(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function Cc(){return{type:"boolean"}}function Ec(t,e,r){return O(t.type._def,e,r)}var Pc=(t,e,r)=>O(t.innerType._def,e,r);function pi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>pi(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Bh(t,e)}}var Bh=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":L(r,"minimum",n.value,n.message,e);break;case"max":L(r,"maximum",n.value,n.message,e);break}return r};function Mc(t,e,r){return{...O(t.innerType._def,e,r),default:t.defaultValue()}}function Oc(t,e,r){return e.effectStrategy==="input"?O(t.schema._def,e,r):{}}function Rc(t){return{type:"string",enum:[...t.values]}}var Kh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function $c(t,e){let r=[O(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),O(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Kh(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function Nc(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,ir={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 Es(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Gh(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":L(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":L(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ce(r,"email",o.message,e);break;case"format:idn-email":Ce(r,"idn-email",o.message,e);break;case"pattern:zod":Ee(r,ir.email,o.message,e);break}break;case"url":Ce(r,"uri",o.message,e);break;case"uuid":Ce(r,"uuid",o.message,e);break;case"regex":Ee(r,o.regex,o.message,e);break;case"cuid":Ee(r,ir.cuid,o.message,e);break;case"cuid2":Ee(r,ir.cuid2,o.message,e);break;case"startsWith":Ee(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":Ee(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Ce(r,"date-time",o.message,e);break;case"date":Ce(r,"date",o.message,e);break;case"time":Ce(r,"time",o.message,e);break;case"duration":Ce(r,"duration",o.message,e);break;case"length":L(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),L(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{Ee(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ce(r,"ipv4",o.message,e),o.version!=="v4"&&Ce(r,"ipv6",o.message,e);break}case"emoji":Ee(r,ir.emoji,o.message,e);break;case"ulid":{Ee(r,ir.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ce(r,"binary",o.message,e);break}case"contentEncoding:base64":{L(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Ee(r,ir.base64,o.message,e);break}}break}case"nanoid":Ee(r,ir.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Gh=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ce=(t,e,r,n)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):L(t,"format",e,r,n)},Ee=(t,e,r,n)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:zc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):L(t,"pattern",zc(e,n),r,n)},zc=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",a=!1,i=!1,u=!1;for(let l=0;l<o.length;l++){if(a){s+=o[l],a=!1;continue}if(n.i){if(i){if(o[l].match(/[a-z]/)){u?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],u=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
|
|
65
65
|
]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
|
|
66
66
|
]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
|
|
67
67
|
`:`[${o[l]}\r
|
|
68
|
-
]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[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 Ps(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Es(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function jc(t,e){if(e.mapStrategy==="record")return Ps(t,e);let r=O(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Lc(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Dc(){return{not:{}}}function Fc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function qc(t,e){if(e.target==="openApi3")return Uc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in vo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=vo[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Uc(t,e)}var Uc=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>O(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Bc(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:vo[t.innerType._def.typeName],nullable:!0}:{type:[vo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=O(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Kc(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",di(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function Gh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Gc(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=O(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;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:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:Gh(t,e)};return r.required.length||delete r.required,r}var Wc=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return O(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Vc=(t,e,r)=>{if(e.pipeStrategy==="input")return O(t.in._def,e,r);if(e.pipeStrategy==="output")return O(t.out._def,e,r);let n=O(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=O(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Hc(t,e,r){return O(t.type._def,e,r)}function Jc(t,e){let n={type:"array",uniqueItems:!0,items:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&L(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&L(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Zc(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>O(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:O(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>O(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Qc(){return{not:{}}}function Yc(){return{}}var Xc=(t,e,r)=>O(t.innerType._def,e,r);function O(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==xc)return s}if(n&&!r){let s=Wh(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=Jh(t,t.typeName,e,r);return s&&Zh(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var Wh=(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((n,o)=>o===0?n:Vh(n)).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:Hh(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ed="_x_",Vh=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(ed))return t;let e=ed;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Hh=(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("/")},Jh=(t,e,r,n)=>{switch(e){case N.ZodString:return Es(t,r);case N.ZodNumber:return Kc(t,r);case N.ZodObject:return Gc(t,r);case N.ZodBigInt:return kc(t,r);case N.ZodBoolean:return Cc();case N.ZodDate:return pi(t,r);case N.ZodUndefined:return Qc();case N.ZodNull:return Fc(r);case N.ZodArray:return Sc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return qc(t,r);case N.ZodIntersection:return $c(t,r);case N.ZodTuple:return Zc(t,r);case N.ZodRecord:return Ps(t,r);case N.ZodLiteral:return Nc(t,r);case N.ZodEnum:return Rc(t);case N.ZodNativeEnum:return Lc(t);case N.ZodNullable:return Bc(t,r,n);case N.ZodOptional:return Wc(t,r,n);case N.ZodMap:return jc(t,r);case N.ZodSet:return Jc(t,r);case N.ZodLazy:return O(t.getter()._def,r,n);case N.ZodPromise:return Hc(t,r,n);case N.ZodNaN:case N.ZodNever:return Dc();case N.ZodEffects:return Oc(t,r,n);case N.ZodAny:return Tc();case N.ZodUnknown:return Yc();case N.ZodDefault:return Mc(t,r,n);case N.ZodBranded:return Ec(t,r,n);case N.ZodReadonly:return Xc(t,r,n);case N.ZodCatch:return Pc(t,r,n);case N.ZodPipeline:return Vc(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},Zh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fi=(t,e)=>{let r=vc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=O(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Ic(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,I]of m)u[f]=O(Io(I),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};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 td(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 tt(e,[],e)}function hi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(hi(e))return!0;for(let e of t.anyOf??[])if(hi(e))return!0;return!1}function tt(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!lr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(lr(n))for(let[f,I]of Object.entries(n))tt(I,[...e,"$defs",f],r);let o=t.definitions;if(lr(o))for(let[f,I]of Object.entries(o))tt(I,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(lr(i)){for(let[f,I]of Object.entries(i))if(!hi(I)&&!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,I])=>[f,tt(I,[...e,"properties",f],r)]))}let u=t.items;lr(u)&&(t.items=tt(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,I)=>tt(f,[...e,"anyOf",String(I)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=tt(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,I)=>tt(f,[...e,"allOf",String(I)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&Yh(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=Qh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!lr(f))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,tt(t,e,r)}return t}function Qh(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!lr(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function lr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function Xh(t,e){return fi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function eg(t){return td(ml(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&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 tg(t){return"_zod"in t}function rd(t,e,r){return vu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:tg(t)?eg(t):Xh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var nd=["jsonSchema","functionCalling","jsonMode"];function od(t,e){if(typeof e<"u"&&!nd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${nd.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 rg(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(fl(t))return rd(t,e,r);if(Uo(t))return rg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Ct(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>dl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function ad(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var id={"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}};function Nn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var ur=class extends Go{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??Ae("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Ae("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!Qe(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&&kt(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=Xe({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=et(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return ar(t)?wc(t.metadata.customTool):Bo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:uc(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if($n(n)||ar(n))return n;if(pc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return yr(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Ye(s))]),u=s.name!==void 0?n+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(m){console.error("Error parsing function arguments",m,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:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=cc(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw be(o)}})}get profile(){return id[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw: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=od(this.model,e?.method);if(i==="jsonMode"){n=pa(o);let u=Ct(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=Ct(o),l={name:s??"extract",description:ca(u),schema:kt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),kt(o)||Fo(o)){let d=pa(o);n=at.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d.invoke(m.content))}else n=new yl}else{let u=s??"extract",l=Ct(o),d;kt(o)||Fo(o)?d={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(d=o,u=o.name):(u=o.title??u,d={name:u,description:o.description??"",parameters:o}),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}:{}}),n=_l(o,u)}return wl(r,n,a)}};var Ms={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=ia({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=aa(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=aa(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=ia({dataUrl:t.url}),r=sr(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=sr(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`)}},gi=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(Ko(l,{returnId:!0}))}catch(d){a.push(hr(l,d.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new D({content:ad(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 Lo(t.content||"",t.role??"unknown")}},yi=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,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(o==="user")return new ua({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new st({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new Do({content:s,response_metadata:i}):o==="developer"?new Do({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new ll({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new la({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new il({content:s,role:o,response_metadata:i})},ld=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=ul(()=>{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=sr(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}}}},ud=({message:t,model:e})=>{let r=Ye(t);if(r==="system"&&Qe(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return D.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(da):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&q.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=ld(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},zn=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return ud({message:r});let n=Ye(r);n==="system"&&Qe(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>zo(a)?jo(a,Ms):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),D.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(da):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),q.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 Os=class extends ur{constructor(t,e){super(Nn(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 n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:ks(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),Qe(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=zn({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let I of a){I.message.response_metadata={...I.generationInfo,...I.message.response_metadata};let w=I.generationInfo?.completion??0;i[w]===void 0?i[w]=I:i[w]=i[w].concat(I)}let u=Object.entries(i).sort(([I],[w])=>parseInt(I,10)-parseInt(w,10)).map(([I,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:m}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(n.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let I of a?.choices??[]){let w={text:I.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(I.message??{role:"assistant"},a)};w.generationInfo={...I.finish_reason?{finish_reason:I.finish_reason}:{},...I.logprobs?{logprobs:I.logprobs}:{}},ot(w.message)&&(w.message.usage_metadata=n),w.message=new D(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=zn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),a=this.streamUsage??e.streamUsage;yield*Wo(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 n=zn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,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 m=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let I={...f};l.finish_reason!=null&&(I.finish_reason=l.finish_reason,I.system_fingerprint=u.system_fingerprint,I.model_name=u.model,I.service_tier=u.service_tier),this.logprobs&&(I.logprobs=l.logprobs);let w=new Jn({message:m,text:m.content,generationInfo:I});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 Jn({message:new st({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 r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw be(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return yi({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return gi({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Rs="__openai_function_call_ids__",$s="__openai_custom_tool_call_ids__";function gd(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 og(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 To=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}},Ns=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],n=[],o=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:o,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(gd),...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(Ko(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),n.push(hr(u,d))}a[Rs]??={},i.id&&(a[Rs][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=fc(i);u?(r.push(u),a[$s]??={},i.id&&i.call_id&&(a[$s][i.call_id]=i.id)):n.push(hr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=hc(i);u?r.push(u):n.push(hr(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 D({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:To(t.usage),additional_kwargs:a,response_metadata:s})},yd=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},_i=t=>{let e=[],r={},n,o=[],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:[gd(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")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Rs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.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[$s]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),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=Ns(t.response);if(n=To(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")o.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,m)=>({...d,index:m})):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 Jn({text:e.map(u=>u.text).join(""),message:new st({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},_d=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=ke(()=>{try{let h=Ye(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let d=(h,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},m=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{let x=ke(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:x,file_id:h.fileId};if(h.url)return{type:"input_image",detail:x,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},I=h=>{if(h.fileId){let x=Ts(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=Ts(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=sr(h),S=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,${S}`,filename:x}}},w=h=>{let x=ke(()=>{if(Array.isArray(h.summary)){let M=h.summary?.map(F=>F?.text).filter(F=>typeof F=="string")??[];if(M.length>0)return M}return h.reasoning?[h.reasoning]:[]}),S=x.length>0?x.map(M=>({type:"summary_text",text:M})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:S}},b=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:m(h.args)}),y=h=>{let x=m(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:x,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let x=ke(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});d([{type:"input_text",text:h.text}],x)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield w(h);else if(h.type==="tool_call"){yield*l();let x=h.id??"";x&&(s.add(x),i.delete(x)),yield b(h)}else if(h.type==="tool_call_chunk"){if(h.id){let x=i.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),i.set(h.id,x)}}else if(h.type==="server_tool_call"){yield*l();let x=h.id??"";x&&(a.add(x),u.delete(x)),yield b(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let x=u.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),u.set(h.id,x)}}else if(h.type==="server_tool_call_result")yield*l(),yield y(h);else if(h.type!=="audio")if(h.type==="file"){let x=I(h);x&&d([x])}else if(h.type==="image"){let x=f(h);x&&d([x])}else if(h.type==="video"){let x=I(h);x&&d([x])}else h.type==="text-plain"?h.text&&d([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,x]of i){if(!h||s.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}for(let[h,x]of u){if(!h||a.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}}return Array.from(r())},So=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return _d(n);let s=n.additional_kwargs,a=Ye(n);if(a==="system"&&Qe(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;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 m=i.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id: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&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(b=>"type"in b))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=yd(u);i.push(b)}let{content:d}=n;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",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:ke(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let h=y;return{type:"output_text",text:h.text,annotations:(h.annotations??[]).map(og)}}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 m=s?.[Rs],f=s?.[$s];D.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(b=>yc(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}:gc(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:m?.[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:m?.[b.id]}})));let I=o?.output?.length?o?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(I!=null){let b=I?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.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}),zo(l)){if(l.type==="file"){let d=Ts(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:sr(l)}}return jo(l,Ms)}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*wi(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,a=0,i=!1,u,l,d,m,f=new Set,I=(y,h)=>{let x=s.get(y);if(x!==void 0)return{index:x,isNew:!1};let S=a++;return s.set(y,S),o.set(S,{...h}),{index:S,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let h=o.get(y);h&&(f.add(y),yield{event:"content-block-finish",index:y,content:bl(h)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:h,isNew:x}=I(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let S=o.get(h);S.text=(S.text??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:h,isNew:x}=I(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let S=o.get(h);S.reasoning=(S.reasoning??"")+y.delta,yield{event:"content-block-delta",index:h,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 h=`tool:${y.output_index}`,x=y.item.type==="custom_tool_call",S=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:M,isNew:F}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index,...x?{isCustomTool:!0}:{}});if(F&&(yield{event:"content-block-start",index:M,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index}}),S){let B=o.get(M);yield{event:"content-block-delta",index:M,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...B.id!=null?{id:B.id}:{},...B.name!=null?{name:B.name}:{},args:B.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:h,isNew:x}=I(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:h,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let S=o.get(h);S.args=(S.args??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:S,isNew:M}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index});if(M)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index}};else{let F=o.get(S);F.args=x,F.id=y.item.call_id,F.name=y.item.name}yield*b(S);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=sg(y.response.status,y.type),m={model_provider:n,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=To(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of o)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function sg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var zs=class extends ur{constructor(t,e){super(Nn(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:mc(t?.tool_choice)?t?.tool_choice:(()=>{let o=ks(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)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 o=await this.completionWithRetry({input:So({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Ns(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:So({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*wi(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:So({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of n){if(e.signal?.aborted)return;let s=_i(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(o){throw be(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw be(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if($n(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(ar(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Bo(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Cs(n)&&r.push(_c(n));return r}};var js=class wd extends ur{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Nn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new zs(n),this.completions=n?.completions??new Os(n)}_useResponsesApi(e){let r=e?.tools?.some($n),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Cs)||e?.tools?.some(ar);return this.useResponsesApi||r||n||o||ac(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamChatModelEvents(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new wd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ls=class extends hl{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??Ae("OPENAI_API_KEY");this.organization=e?.configuration?.organization??Ae("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=ma(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)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let a=e[s],{data:i}=n[s];for(let u=0;u<a.length;u+=1)o.push(i[u].embedding)}return o}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Xe({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=et(n.defaultHeaders),this.client=new P(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw be(r)}})}};var ug=v.object({type:v.literal("screenshot")}),cg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),dg=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),pg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),mg=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),fg=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),hg=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),gg=v.object({type:v.literal("type"),text:v.string()}),yg=v.object({type:v.literal("wait"),duration:v.number().optional()}),_g=v.union([ug,cg,dg,pg,mg,fg,hg,gg,yg]),AK=v.object({action:_g});var wg=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()}),SK=v.union([wg]);var PK=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 bg=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),xg=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),Ag=v.object({type:v.literal("delete_file"),path:v.string()}),$K=v.union([bg,xg,Ag]);var xd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},xi={default:"text-embedding-ada-002"},bi=new Map,Ds=null,kg=()=>{let t=bd.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},Ad=async t=>{let e=kg();bi.size===0&&(Ds||(Ds=(async()=>{try{(await vg(`${e}/models`)).data.models.forEach(n=>bi.set(n.name,n))}catch(n){throw Ds=null,n}})()),await Ds);let r=bi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Cg=async(t="default")=>await Ad(xd[t]),Id=async(t="default")=>await Ad(xi[t]),cr=(t,e)=>e,vd=(t,e)=>({...t,...e}),Td=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
|
|
68
|
+
]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[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 Ps(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Es(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function jc(t,e){if(e.mapStrategy==="record")return Ps(t,e);let r=O(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Lc(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Dc(){return{not:{}}}function Fc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function qc(t,e){if(e.target==="openApi3")return Uc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in vo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=vo[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Uc(t,e)}var Uc=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>O(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Bc(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:vo[t.innerType._def.typeName],nullable:!0}:{type:[vo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=O(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Kc(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",di(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function Wh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Gc(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=O(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;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:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:Wh(t,e)};return r.required.length||delete r.required,r}var Wc=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return O(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Vc=(t,e,r)=>{if(e.pipeStrategy==="input")return O(t.in._def,e,r);if(e.pipeStrategy==="output")return O(t.out._def,e,r);let n=O(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=O(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Hc(t,e,r){return O(t.type._def,e,r)}function Jc(t,e){let n={type:"array",uniqueItems:!0,items:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&L(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&L(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Zc(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>O(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:O(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>O(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Qc(){return{not:{}}}function Yc(){return{}}var Xc=(t,e,r)=>O(t.innerType._def,e,r);function O(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==xc)return s}if(n&&!r){let s=Vh(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=Zh(t,t.typeName,e,r);return s&&Qh(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var Vh=(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((n,o)=>o===0?n:Hh(n)).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:Jh(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ed="_x_",Hh=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(ed))return t;let e=ed;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Jh=(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("/")},Zh=(t,e,r,n)=>{switch(e){case N.ZodString:return Es(t,r);case N.ZodNumber:return Kc(t,r);case N.ZodObject:return Gc(t,r);case N.ZodBigInt:return kc(t,r);case N.ZodBoolean:return Cc();case N.ZodDate:return pi(t,r);case N.ZodUndefined:return Qc();case N.ZodNull:return Fc(r);case N.ZodArray:return Sc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return qc(t,r);case N.ZodIntersection:return $c(t,r);case N.ZodTuple:return Zc(t,r);case N.ZodRecord:return Ps(t,r);case N.ZodLiteral:return Nc(t,r);case N.ZodEnum:return Rc(t);case N.ZodNativeEnum:return Lc(t);case N.ZodNullable:return Bc(t,r,n);case N.ZodOptional:return Wc(t,r,n);case N.ZodMap:return jc(t,r);case N.ZodSet:return Jc(t,r);case N.ZodLazy:return O(t.getter()._def,r,n);case N.ZodPromise:return Hc(t,r,n);case N.ZodNaN:case N.ZodNever:return Dc();case N.ZodEffects:return Oc(t,r,n);case N.ZodAny:return Tc();case N.ZodUnknown:return Yc();case N.ZodDefault:return Mc(t,r,n);case N.ZodBranded:return Ec(t,r,n);case N.ZodReadonly:return Xc(t,r,n);case N.ZodCatch:return Pc(t,r,n);case N.ZodPipeline:return Vc(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},Qh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fi=(t,e)=>{let r=vc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=O(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Ic(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,I]of m)u[f]=O(Io(I),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};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 td(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 tt(e,[],e)}function hi(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(hi(e))return!0;for(let e of t.anyOf??[])if(hi(e))return!0;return!1}function tt(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!lr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(lr(n))for(let[f,I]of Object.entries(n))tt(I,[...e,"$defs",f],r);let o=t.definitions;if(lr(o))for(let[f,I]of Object.entries(o))tt(I,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(lr(i)){for(let[f,I]of Object.entries(i))if(!hi(I)&&!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,I])=>[f,tt(I,[...e,"properties",f],r)]))}let u=t.items;lr(u)&&(t.items=tt(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,I)=>tt(f,[...e,"anyOf",String(I)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=tt(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,I)=>tt(f,[...e,"allOf",String(I)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&Xh(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=Yh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!lr(f))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,tt(t,e,r)}return t}function Yh(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!lr(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function lr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function eg(t,e){return fi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function tg(t){return td(ml(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&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 rg(t){return"_zod"in t}function rd(t,e,r){return vu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:rg(t)?tg(t):eg(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var nd=["jsonSchema","functionCalling","jsonMode"];function od(t,e){if(typeof e<"u"&&!nd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${nd.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 ng(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(fl(t))return rd(t,e,r);if(Uo(t))return ng({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Ct(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>dl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function ad(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var id={"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}};function Nn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var ur=class extends Go{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??Ae("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Ae("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!Qe(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&&kt(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=Xe({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=et(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return ar(t)?wc(t.metadata.customTool):Bo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:uc(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if($n(n)||ar(n))return n;if(pc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return yr(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Ye(s))]),u=s.name!==void 0?n+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(m){console.error("Error parsing function arguments",m,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:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=cc(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw be(o)}})}get profile(){return id[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw: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=od(this.model,e?.method);if(i==="jsonMode"){n=pa(o);let u=Ct(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=Ct(o),l={name:s??"extract",description:ca(u),schema:kt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),kt(o)||Fo(o)){let d=pa(o);n=at.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d.invoke(m.content))}else n=new yl}else{let u=s??"extract",l=Ct(o),d;kt(o)||Fo(o)?d={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(d=o,u=o.name):(u=o.title??u,d={name:u,description:o.description??"",parameters:o}),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}:{}}),n=_l(o,u)}return wl(r,n,a)}};var Ms={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=ia({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=aa(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=aa(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=ia({dataUrl:t.url}),r=sr(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=sr(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`)}},gi=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(Ko(l,{returnId:!0}))}catch(d){a.push(hr(l,d.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new D({content:ad(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 Lo(t.content||"",t.role??"unknown")}},yi=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,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(o==="user")return new ua({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new st({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new Do({content:s,response_metadata:i}):o==="developer"?new Do({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new ll({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new la({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new il({content:s,role:o,response_metadata:i})},ld=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=ul(()=>{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=sr(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}}}},ud=({message:t,model:e})=>{let r=Ye(t);if(r==="system"&&Qe(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return D.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(da):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&q.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=ld(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},zn=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return ud({message:r});let n=Ye(r);n==="system"&&Qe(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>zo(a)?jo(a,Ms):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),D.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(da):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),q.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 Os=class extends ur{constructor(t,e){super(Nn(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 n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:ks(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),Qe(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=zn({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let I of a){I.message.response_metadata={...I.generationInfo,...I.message.response_metadata};let w=I.generationInfo?.completion??0;i[w]===void 0?i[w]=I:i[w]=i[w].concat(I)}let u=Object.entries(i).sort(([I],[w])=>parseInt(I,10)-parseInt(w,10)).map(([I,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:m}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(n.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let I of a?.choices??[]){let w={text:I.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(I.message??{role:"assistant"},a)};w.generationInfo={...I.finish_reason?{finish_reason:I.finish_reason}:{},...I.logprobs?{logprobs:I.logprobs}:{}},ot(w.message)&&(w.message.usage_metadata=n),w.message=new D(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=zn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),a=this.streamUsage??e.streamUsage;yield*Wo(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 n=zn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,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 m=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let I={...f};l.finish_reason!=null&&(I.finish_reason=l.finish_reason,I.system_fingerprint=u.system_fingerprint,I.model_name=u.model,I.service_tier=u.service_tier),this.logprobs&&(I.logprobs=l.logprobs);let w=new Jn({message:m,text:m.content,generationInfo:I});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 Jn({message:new st({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 r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw be(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return yi({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return gi({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Rs="__openai_function_call_ids__",$s="__openai_custom_tool_call_ids__";function gd(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 sg(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 To=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}},Ns=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],n=[],o=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:o,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(gd),...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(Ko(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),n.push(hr(u,d))}a[Rs]??={},i.id&&(a[Rs][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=fc(i);u?(r.push(u),a[$s]??={},i.id&&i.call_id&&(a[$s][i.call_id]=i.id)):n.push(hr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=hc(i);u?r.push(u):n.push(hr(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 D({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:To(t.usage),additional_kwargs:a,response_metadata:s})},yd=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},_i=t=>{let e=[],r={},n,o=[],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:[gd(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")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Rs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.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[$s]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),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=Ns(t.response);if(n=To(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")o.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,m)=>({...d,index:m})):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 Jn({text:e.map(u=>u.text).join(""),message:new st({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},_d=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=ke(()=>{try{let h=Ye(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let d=(h,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},m=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{let x=ke(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:x,file_id:h.fileId};if(h.url)return{type:"input_image",detail:x,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},I=h=>{if(h.fileId){let x=Ts(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=Ts(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=sr(h),S=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,${S}`,filename:x}}},w=h=>{let x=ke(()=>{if(Array.isArray(h.summary)){let M=h.summary?.map(F=>F?.text).filter(F=>typeof F=="string")??[];if(M.length>0)return M}return h.reasoning?[h.reasoning]:[]}),S=x.length>0?x.map(M=>({type:"summary_text",text:M})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:S}},b=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:m(h.args)}),y=h=>{let x=m(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:x,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let x=ke(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});d([{type:"input_text",text:h.text}],x)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield w(h);else if(h.type==="tool_call"){yield*l();let x=h.id??"";x&&(s.add(x),i.delete(x)),yield b(h)}else if(h.type==="tool_call_chunk"){if(h.id){let x=i.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),i.set(h.id,x)}}else if(h.type==="server_tool_call"){yield*l();let x=h.id??"";x&&(a.add(x),u.delete(x)),yield b(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let x=u.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),u.set(h.id,x)}}else if(h.type==="server_tool_call_result")yield*l(),yield y(h);else if(h.type!=="audio")if(h.type==="file"){let x=I(h);x&&d([x])}else if(h.type==="image"){let x=f(h);x&&d([x])}else if(h.type==="video"){let x=I(h);x&&d([x])}else h.type==="text-plain"?h.text&&d([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,x]of i){if(!h||s.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}for(let[h,x]of u){if(!h||a.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}}return Array.from(r())},So=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return _d(n);let s=n.additional_kwargs,a=Ye(n);if(a==="system"&&Qe(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;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 m=i.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id: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&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(b=>"type"in b))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=yd(u);i.push(b)}let{content:d}=n;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",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:ke(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let h=y;return{type:"output_text",text:h.text,annotations:(h.annotations??[]).map(sg)}}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 m=s?.[Rs],f=s?.[$s];D.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(b=>yc(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}:gc(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:m?.[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:m?.[b.id]}})));let I=o?.output?.length?o?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(I!=null){let b=I?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.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}),zo(l)){if(l.type==="file"){let d=Ts(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:sr(l)}}return jo(l,Ms)}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*wi(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,a=0,i=!1,u,l,d,m,f=new Set,I=(y,h)=>{let x=s.get(y);if(x!==void 0)return{index:x,isNew:!1};let S=a++;return s.set(y,S),o.set(S,{...h}),{index:S,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let h=o.get(y);h&&(f.add(y),yield{event:"content-block-finish",index:y,content:bl(h)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:h,isNew:x}=I(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let S=o.get(h);S.text=(S.text??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:h,isNew:x}=I(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let S=o.get(h);S.reasoning=(S.reasoning??"")+y.delta,yield{event:"content-block-delta",index:h,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 h=`tool:${y.output_index}`,x=y.item.type==="custom_tool_call",S=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:M,isNew:F}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index,...x?{isCustomTool:!0}:{}});if(F&&(yield{event:"content-block-start",index:M,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index}}),S){let B=o.get(M);yield{event:"content-block-delta",index:M,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...B.id!=null?{id:B.id}:{},...B.name!=null?{name:B.name}:{},args:B.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:h,isNew:x}=I(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:h,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let S=o.get(h);S.args=(S.args??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:S,isNew:M}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index});if(M)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index}};else{let F=o.get(S);F.args=x,F.id=y.item.call_id,F.name=y.item.name}yield*b(S);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=ag(y.response.status,y.type),m={model_provider:n,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=To(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of o)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function ag(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var zs=class extends ur{constructor(t,e){super(Nn(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:mc(t?.tool_choice)?t?.tool_choice:(()=>{let o=ks(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)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 o=await this.completionWithRetry({input:So({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Ns(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:So({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*wi(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:So({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of n){if(e.signal?.aborted)return;let s=_i(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(o){throw be(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw be(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if($n(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(ar(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Bo(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Cs(n)&&r.push(_c(n));return r}};var js=class wd extends ur{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Nn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new zs(n),this.completions=n?.completions??new Os(n)}_useResponsesApi(e){let r=e?.tools?.some($n),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Cs)||e?.tools?.some(ar);return this.useResponsesApi||r||n||o||ac(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamChatModelEvents(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new wd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ls=class extends hl{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??Ae("OPENAI_API_KEY");this.organization=e?.configuration?.organization??Ae("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=ma(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)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let a=e[s],{data:i}=n[s];for(let u=0;u<a.length;u+=1)o.push(i[u].embedding)}return o}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Xe({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=et(n.defaultHeaders),this.client=new P(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw be(r)}})}};var cg=v.object({type:v.literal("screenshot")}),dg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),pg=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),mg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),fg=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),hg=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),gg=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),yg=v.object({type:v.literal("type"),text:v.string()}),_g=v.object({type:v.literal("wait"),duration:v.number().optional()}),wg=v.union([cg,dg,pg,mg,fg,hg,gg,yg,_g]),IK=v.object({action:wg});var bg=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()}),kK=v.union([bg]);var MK=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 xg=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),Ag=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),Ig=v.object({type:v.literal("delete_file"),path:v.string()}),NK=v.union([xg,Ag,Ig]);var Ad={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},xi={default:"text-embedding-ada-002"},bi=new Map,Ds=null,kg=()=>{let t=bd.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},Id=async t=>{let e=kg();bi.size===0&&(Ds||(Ds=(async()=>{try{(await xd(`${e}/models`)).data.models.forEach(n=>bi.set(n.name,n))}catch(n){throw Ds=null,n}})()),await Ds);let r=bi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Cg=async(t="default")=>await Id(Ad[t]),vd=async(t="default")=>await Id(xi[t]),cr=(t,e)=>e,Td=(t,e)=>({...t,...e}),Sd=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
|
|
69
69
|
|
|
70
70
|
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
71
71
|
|
|
72
|
-
${r}`},
|
|
72
|
+
${r}`},kd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),dr=()=>({agentExecutionContext:C({reducer:Td,default:kd}),outputMessage:C({reducer:Sd,default:()=>""}),summary:C({reducer:cr,default:()=>""}),status:C({reducer:cr})}),Fs=()=>({...dr(),sharedStatePatch:C({reducer:cr})}),Eg=C.Root({agentExecutionContext:C({default:kd,reducer:Td}),currentIntent:C({default:()=>"none",reducer:cr}),routing:C({default:()=>({mode:"auto"}),reducer:cr}),lastExecutedAgent:C({default:()=>"",reducer:cr}),requiresFollowUp:C({default:()=>!0,reducer:cr}),stepCount:C({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:C({default:()=>"",reducer:Sd})});var Pg=t=>typeof t=="string"&&t.length>0?t:void 0,Mg=()=>Yi(),Og=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Rg=t=>{let e=t?.configurable;return{conversationId:Pg(e?.thread_id),abortSignal:t?.signal,requestId:Mg(),requestSource:Og(Sg.applicationName)}},$g=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)}`)},Cd=async({config:t})=>{let e=bd.getDefault(),r=(await Tg.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Rg(t),l=new Headers(o?.headers);for(let m of[...l.keys()]){let f=m.toLowerCase();(f==="authorization"||f==="api-key"||f.startsWith("x-stainless-"))&&l.delete(m)}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&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return(await xd(n instanceof Request?n.url:n.toString(),{body:$g(o?.body),headers:Object.fromEntries(l),responseType:"native",signal:d})).data}},Ai=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=Ad[e],s=await Cg(e);return new js({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await Cd({config:n})}})},Ed=async(t={})=>{let{tier:e="default",config:r}=t,n=xi[e],o=await vd(e);return new Ls({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:await Cd({config:r})},batchSize:2048,maxConcurrency:10})},Ng=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(Ng);var Pd="0.1",jn=1536,Md="openai",Od=xi.default,Rd=`Name: {name}
|
|
73
73
|
Title: {title}
|
|
74
|
-
Description: {description}
|
|
74
|
+
Description: {description}`,$d=`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(Dg(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(jd(t))s=t;else if(Lg(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(ot(l)){i=l;break}}if(i==null||!ot(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(St))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)St(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ol(a))?o?o.goto.push(...s.goto):o=new qe({graph:qe.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var oW=C.Root({llmInputMessages:C({reducer:(t,e)=>Zn([],e),default:()=>[]})});var Co=(t,e)=>e??t,xy=C.Root({...Fs(),intent:C({reducer:Co}),vectorSearchLayerResults:C({reducer:Co,default:()=>[]}),vectorSearchFieldResults:C({reducer:Co}),navigationInternalState:C({reducer:Co,default:()=>({toolCallMessage:void 0})})});async function Ay(t,e){let r=pr.getDefault().helperServices,n=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Ii.assetsPath?.endsWith("/")?Ii.assetsPath:`${Ii.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await qg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new Bg({url:s,width:24,height:24}),u=new Ug({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Iy=["mapView"];function Fe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Iy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function vy({address:t},e){let{mapView:r}=Fe(e);return await Ay(t,r)}var Ty=c.object({address:c.string().describe("The full address or place name to locate.")}),Sy=$(vy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Ty});async function ky(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Cy({bookmarkName:t},e){let{mapView:r}=Fe(e);return await Promise.resolve(ky(t,r))}var Ey=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),Py=$(Cy,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Ey});async function My(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function Oy({layerId:t,where:e},r){let{mapView:n}=Fe(r);return await My(t,e,n)}var Ry=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.")}),$y=$(Oy,{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:Ry});async function Ny(t){let e=new Kg({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 zy(t,e){let{mapView:r}=Fe(e);return await Ny(r)}var jy=v.object({}),Ly=$(zy,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:jy});async function Dy(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 Fy(t,e){let{mapView:r}=Fe(e);return await Dy(r)}var Uy=c.object({}),qy=$(Fy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:Uy});async function By(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function Ky({layerId:t},e){let{mapView:r}=Fe(e);return await By(t,r)}var Gy=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),Wy=$(Ky,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Gy});async function Vy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Hy({scale:t},e){let{mapView:r}=Fe(e);return await Vy(t,r)}var Jy=c.object({scale:c.number().describe("The map scale of the view to go to.")}),Zy=$(Hy,{name:"goToScale",description:"Go to the specified view scale.",schema:Jy});async function Qy(t,e,r){let n={target:new Wd({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{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 Yy({center:t,zoom:e,scale:r},n){let{mapView:o}=Fe(n);return await Qy(t,o,{zoom:e,scale:r})}var Xy=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.")}),e_=$(Yy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Xy});async function t_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function r_({zoom:t},e){let{mapView:r}=Fe(e);return await t_(t,r)}var n_=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),o_=$(r_,{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:n_}),Bd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function nt(t){let e=Object.entries(Bd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
76
|
+
Description: {description}`,Nd=v.object({schemaVersion:v.literal(Pd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Md),model:v.literal(Od),dimensions:v.literal(jn),templates:v.object({layer:v.string().default(Rd),field:v.string().default($d)})}),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(jn,{message:`Layer vector must be exactly ${jn} 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(jn,{message:`Field vector must be exactly ${jn} dimensions`})}))})).default([])});var zg=(t,e)=>{let r=xl.fromTemplate(t);return gr.fromMessages([r,...e])};var ko=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=zg(e,o??[]),l=(await Ai({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var jg=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),s2=c.object({fields:c.array(jg)});var a2=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var zd=async t=>{try{return await(await Ed()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var Ld=t=>Array.isArray(t)&&t.every(Hn),Dg=t=>typeof t=="object"&&t!=null&&"messages"in t&&Ld(t.messages),Fg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,rt=class extends Al{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e,r){let n=this.tools.find(o=>o.name===t.name);try{if(n===void 0)throw new Error(`Tool "${t.name}" not found.`);let o={...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 n.invoke(o,s);return Hn(a)&&a.getType()==="tool"||St(a)?a:new q({status:"success",name:n.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||No(o))throw o;return new q({status:"error",content:`Error: ${o.message}
|
|
77
|
+
Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Fg(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(Ld(t))s=t;else if(Dg(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(ot(l)){i=l;break}}if(i==null||!ot(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(St))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)St(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>ol(a))?o?o.goto.push(...s.goto):o=new qe({graph:qe.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var sW=C.Root({llmInputMessages:C({reducer:(t,e)=>Zn([],e),default:()=>[]})});var Co=(t,e)=>e??t,Ay=C.Root({...Fs(),intent:C({reducer:Co}),vectorSearchLayerResults:C({reducer:Co,default:()=>[]}),vectorSearchFieldResults:C({reducer:Co}),navigationInternalState:C({reducer:Co,default:()=>({toolCallMessage:void 0})})});async function Iy(t,e){let r=pr.getDefault().helperServices,n=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Ii.assetsPath?.endsWith("/")?Ii.assetsPath:`${Ii.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await Bg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new Kg({url:s,width:24,height:24}),u=new qg({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var vy=["mapView"];function Fe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=vy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Ty({address:t},e){let{mapView:r}=Fe(e);return await Iy(t,r)}var Sy=c.object({address:c.string().describe("The full address or place name to locate.")}),ky=$(Ty,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Sy});async function Cy(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Ey({bookmarkName:t},e){let{mapView:r}=Fe(e);return await Promise.resolve(Cy(t,r))}var Py=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),My=$(Ey,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Py});async function Oy(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function Ry({layerId:t,where:e},r){let{mapView:n}=Fe(r);return await Oy(t,e,n)}var $y=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.")}),Ny=$(Ry,{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:$y});async function zy(t){let e=new Gg({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 jy(t,e){let{mapView:r}=Fe(e);return await zy(r)}var Ly=v.object({}),Dy=$(jy,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Ly});async function Fy(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 Uy(t,e){let{mapView:r}=Fe(e);return await Fy(r)}var qy=c.object({}),By=$(Uy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:qy});async function Ky(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function Gy({layerId:t},e){let{mapView:r}=Fe(e);return await Ky(t,r)}var Wy=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),Vy=$(Gy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Wy});async function Hy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Jy({scale:t},e){let{mapView:r}=Fe(e);return await Hy(t,r)}var Zy=c.object({scale:c.number().describe("The map scale of the view to go to.")}),Qy=$(Jy,{name:"goToScale",description:"Go to the specified view scale.",schema:Zy});async function Yy(t,e,r){let n={target:new Vd({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{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 Xy({center:t,zoom:e,scale:r},n){let{mapView:o}=Fe(n);return await Yy(t,o,{zoom:e,scale:r})}var e_=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.")}),t_=$(Xy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:e_});async function r_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function n_({zoom:t},e){let{mapView:r}=Fe(e);return await r_(t,r)}var o_=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),s_=$(n_,{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:o_}),Kd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function nt(t){let e=Object.entries(Kd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
78
78
|
Available prompts:
|
|
79
|
-
${Object.keys(
|
|
80
|
-
`)}`);return await e[1]()}var Fn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function
|
|
79
|
+
${Object.keys(Kd).join(`
|
|
80
|
+
`)}`);return await e[1]()}var Fn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function a_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=Vg({basemapTheme:await Ud(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=Hg({basemapTheme:await Ud(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function i_(t){return await Wg(t)}async function l_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o};try{let l=await a_(u),d=await i_(l);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var u_=["mapView"];function Pe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=u_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function c_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await l_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var d_=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)")}),p_=$(c_,{name:"chart",description:`Label: Charts
|
|
81
81
|
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
82
82
|
Keywords: pie, chart, all categories, breakdown, proportion
|
|
83
83
|
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
@@ -87,19 +87,19 @@ ${Object.keys(Bd).join(`
|
|
|
87
87
|
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.
|
|
88
88
|
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
89
89
|
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.
|
|
90
|
-
Fields: This style requires 2-8 number fields.`,schema:
|
|
90
|
+
Fields: This style requires 2-8 number fields.`,schema:d_});function m_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=Ri({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function f_(t){return await Jg(t)}async function h_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=m_(u),d=await f_(l);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function g_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await h_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var y_=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")}),__=$(g_,{name:"color-age",description:`Label: Age (color)
|
|
91
91
|
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.
|
|
92
92
|
Keywords: since, age, how old, how long
|
|
93
93
|
Example: Show the age of each feature based on its reported date.
|
|
94
|
-
Fields: This style requires at least one field with a date type.`,schema:
|
|
94
|
+
Fields: This style requires at least one field with a date type.`,schema:y_});function w_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=Ri({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function b_(t){return await Zg(t)}async function x_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=w_(u),d=await b_(l);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function A_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await x_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var I_=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")}),v_=$(A_,{name:"color",description:`Label: Counts and Amounts (color)
|
|
95
95
|
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
96
96
|
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
97
97
|
Example: Color each feature based on the population density.
|
|
98
|
-
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:
|
|
98
|
+
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:I_});function T_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=Ri({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function S_(t){return await Qg(t)}async function k_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=T_(u),d=await S_(l);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function C_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await k_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var E_=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")}),P_=$(C_,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
99
99
|
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
100
100
|
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
101
101
|
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.
|
|
102
|
-
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:
|
|
102
|
+
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:E_});function M_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=Xg({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,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 O_(t){return await Yg(t)}async function R_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){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:n,layer:a,view:s,colorSchemeTags:o};try{let u=M_(i),l=await O_(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function $_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Pe(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await R_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var N_=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")}),z_=$($_,{name:"dot-density",description:`Dot Density
|
|
103
103
|
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
104
104
|
**Use cases:**
|
|
105
105
|
- Population distribution visualization
|
|
@@ -110,11 +110,11 @@ ${Object.keys(Bd).join(`
|
|
|
110
110
|
- Visualize distribution of different crops across regions
|
|
111
111
|
- Display demographic patterns within census tracts
|
|
112
112
|
**Fields:** Requires 2-8 number fields.
|
|
113
|
-
**Keywords:** density, how much, how many, total, number, amount`,schema
|
|
113
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:N_});function j_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=ty({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function L_(t){return await ey(t)}async function D_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){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:n,layer:a,view:s,colorSchemeTags:o};try{let u=j_(i),l=await L_(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function F_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Pe(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await D_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var U_=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")}),q_=$(F_,{name:"heatmap",description:`Label: Heat Map
|
|
114
114
|
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
115
115
|
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
116
116
|
Example: Create a heatmap
|
|
117
|
-
Fields: This typically requires zero or one field of type number.`,schema:
|
|
117
|
+
Fields: This typically requires zero or one field of type number.`,schema:U_});function B_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=ny({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function K_(t){return await ry(t)}async function G_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o};try{let l=B_(u),d=await K_(l);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function W_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await G_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var V_=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)")}),H_=$(W_,{name:"predominance",description:`Label: Predominant category
|
|
118
118
|
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
119
119
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
120
120
|
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
@@ -124,15 +124,15 @@ Fields: This typically requires zero or one field of type number.`,schema:F_});f
|
|
|
124
124
|
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.
|
|
125
125
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
126
126
|
Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
|
|
127
|
-
Fields: This style relies on 2-10 number fields.`,schema:
|
|
127
|
+
Fields: This style relies on 2-10 number fields.`,schema:V_});function J_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=sy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function Z_(t){return await oy(t)}async function Q_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){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:n,layer:a,view:s,colorSchemeTags:o};try{let u=J_(i),l=await Z_(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function Y_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Pe(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await Q_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var X_=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")}),ew=$(Y_,{name:"relationship",description:`Label: Relationship
|
|
128
128
|
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
129
129
|
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
130
130
|
Example: Show the relationship between tree height and carbon storage
|
|
131
|
-
Fields: This style requires two number fields.`,schema:
|
|
131
|
+
Fields: This style requires two number fields.`,schema:X_});function tw(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function rw(t){return await ay(t)}async function nw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=tw(u),d=await rw(l);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function ow({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await nw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var sw=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")}),aw=$(ow,{name:"size-age",description:`Label: Age (size)
|
|
132
132
|
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.
|
|
133
133
|
Keywords: since, age, how old, how long
|
|
134
134
|
Example: Change the size of features so older features are larger than new features.
|
|
135
|
-
Fields: This style requires at least one field with a date type.`,schema:
|
|
135
|
+
Fields: This style requires at least one field with a date type.`,schema:sw});function iw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function lw(t){return await iy(t)}async function uw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=iw(u),d=await lw(l);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function cw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await uw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var dw=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")}),pw=$(cw,{name:"size",description:`Label: Counts and Amounts (size)
|
|
136
136
|
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
137
137
|
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
138
138
|
Example: Vary the size of each point based on the total population.
|
|
@@ -142,11 +142,11 @@ Fields: This typically requires zero or one field of type number.`,schema:F_});f
|
|
|
142
142
|
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
143
143
|
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
144
144
|
Example: Vary the size of each feature based on the date a ticket was completed.
|
|
145
|
-
Fields: This style requires a single field with a date type.`,schema:
|
|
145
|
+
Fields: This style requires a single field with a date type.`,schema:dw});function mw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=uy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function fw(t){return await ly(t)}async function hw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,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:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=mw(u),d=await fw(l);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function gw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Pe(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await hw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var yw=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")}),_w=$(gw,{name:"type",description:`Label: Types (unique symbols)
|
|
146
146
|
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
147
147
|
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
148
148
|
Example: Color each feature based on the region it belongs to
|
|
149
|
-
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:gw}),_w=C.Root({...dr(),vectorSearchLayerIds:C(),vectorSearchFieldResults:C(),layerFieldInfo:C(),selectedLayerId:C()}),ww=C.Root({...dr(),vectorSearchLayerIds:C(),vectorSearchFieldResults:C(),layerFieldInfo:C(),queryResponse:C(),dataExplorationMessages:C({reducer:Zn,default:()=>[]})}),bw=["mapView"];function vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=bw.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var xw=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},Aw=async(t,e)=>{let{mapView:r}=vt(e);return xw(r)},fV=$(Aw,{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({})}),Iw=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.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."},vw=async(t,e)=>{let{mapView:r}=vt(e);return await Iw(r)},hV=$(vw,{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({})}),Kd=750;function Ks(t){return"point"in t&&t.point!==void 0}function Eo(t){return"layerId"in t&&t.layerId!==void 0}var Vs=async(t,e)=>{if(Ks(t)){let{point:r}=t;return{geometry:new Wd({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Eo(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 n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Kd+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Kd)return{error:`Geometry filter for layer "${n}" 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]:Hd.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"}},Tw=async(t,e,r,n,o,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",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),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}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},Sw=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(m=>m.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let m=await Vs(o,e);if("error"in m)return m.error;i=m.geometry}if(a.featureEffect=null,a.featureEffect=new uy({filter:new Vd({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),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 Tw(e,t.layerId,u,i,o?.distance,o?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},kw=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Tt=c.enum(kw),Cw=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=vt(s);return await Sw(t,a,n,o,e,r)},Ew=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:Tt.optional().describe("The units for the distance buffer.")}),Pw=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:Tt.optional().describe("The units for the distance buffer.")}),Mw=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([Ew,Pw]).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.")}),gV=$(Cw,{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:Mw}),Ow=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Zd=t=>{if(!t)return!1;let e=t.toLowerCase();return Ow.has(e)},Ti=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},Rw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,$w=t=>{if(typeof t=="string"&&t)return t;let e=Ti(t);return e?e.toISOString().slice(0,10):null};var Nw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Zd(n))return t;if(n==="date-only"){let s=$w(t);return s?cy(s,Us("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return dy(t,Us("long-time"));let s=Ti(t);return s?Ud(s,{...Us("long-time"),timeZone:"UTC"}):t}let o=Ti(t);return o?Ud(o,{...Us("short-date-short-time"),timeZone:Rw(r)}):t},Qd=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},zw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,jw=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},Lw=(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}},Dw=(t,e,r)=>{let n=jw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=zw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Yd=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,Xd=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?Lw(r,s):s?.type==="date-time"?!n||Zd(n)?Dw(r,s,o):r:Nw(r,n,o)},Fw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Qd(e,r,t)??r;return Xd(t,e,s,o?.type,n)},Uw=(t,e)=>Yd(t,e),ep=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),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===n){u[l.name]=d;return}let m=Qd(l.name,d,t)??d,f=Yd(t,l.name);u[f]=Xd(t,l.name,m,l.type,r)}),u});return{objectIds:o,attributes:s}},qw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Bw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(d=>d.id===t),s=qw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=Fw(o,e,i,n.timeZone),l=Uw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function Kw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=vt(n),s=await Bw(t,e,r,o);return JSON.stringify(s,null,2)}var Gw=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.")})}),Ww=$(Kw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Gw}),$i=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function Gs(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Vw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(h=>h.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(a){let h=await Vs(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw Eo(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Eo(a)){let x=o.map?.allLayers.find(S=>S.id===a.layerId);m={geometryLayerName:x?.title??x?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else Ks(a)&&(m={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new Vd({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let I=$i(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Gs(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await py(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await my({layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Gs(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((M,F)=>F.count-M.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(M=>({...M,value:S?S.getName(M.value)??M.value:M.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:m}}};async function Hw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Fn(o,"layersAndFieldsRegistry"),{mapView:a}=vt(o),i=await Vw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var Jw=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:Tt.optional().describe("The units for the distance buffer.")}),Zw=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:Tt.optional().describe("The units for the distance buffer.")}),Qw=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([Jw,Zw]).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.")}),Yw=$(Hw,{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.
|
|
149
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:yw}),ww=C.Root({...dr(),vectorSearchLayerIds:C(),vectorSearchFieldResults:C(),layerFieldInfo:C(),selectedLayerId:C()}),bw=C.Root({...dr(),vectorSearchLayerIds:C(),vectorSearchFieldResults:C(),layerFieldInfo:C(),queryResponse:C(),dataExplorationMessages:C({reducer:Zn,default:()=>[]})}),xw=["mapView"];function vt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=xw.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var Aw=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},Iw=async(t,e)=>{let{mapView:r}=vt(e);return Aw(r)},hV=$(Iw,{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({})}),vw=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.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."},Tw=async(t,e)=>{let{mapView:r}=vt(e);return await vw(r)},gV=$(Tw,{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({})}),Gd=750;function Ks(t){return"point"in t&&t.point!==void 0}function Eo(t){return"layerId"in t&&t.layerId!==void 0}var Vs=async(t,e)=>{if(Ks(t)){let{point:r}=t;return{geometry:new Vd({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Eo(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 n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Gd+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Gd)return{error:`Geometry filter for layer "${n}" 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]:Jd.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"}},Sw=async(t,e,r,n,o,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",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),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}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},kw=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(m=>m.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let m=await Vs(o,e);if("error"in m)return m.error;i=m.geometry}if(a.featureEffect=null,a.featureEffect=new cy({filter:new Hd({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),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 Sw(e,t.layerId,u,i,o?.distance,o?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},Cw=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Tt=c.enum(Cw),Ew=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=vt(s);return await kw(t,a,n,o,e,r)},Pw=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:Tt.optional().describe("The units for the distance buffer.")}),Mw=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:Tt.optional().describe("The units for the distance buffer.")}),Ow=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([Pw,Mw]).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.")}),yV=$(Ew,{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:Ow}),Rw=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Qd=t=>{if(!t)return!1;let e=t.toLowerCase();return Rw.has(e)},Ti=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},$w=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Nw=t=>{if(typeof t=="string"&&t)return t;let e=Ti(t);return e?e.toISOString().slice(0,10):null};var zw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Qd(n))return t;if(n==="date-only"){let s=Nw(t);return s?dy(s,Us("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return py(t,Us("long-time"));let s=Ti(t);return s?qd(s,{...Us("long-time"),timeZone:"UTC"}):t}let o=Ti(t);return o?qd(o,{...Us("short-date-short-time"),timeZone:$w(r)}):t},Yd=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},jw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Lw=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},Dw=(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}},Fw=(t,e,r)=>{let n=Lw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=jw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Xd=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,ep=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?Dw(r,s):s?.type==="date-time"?!n||Qd(n)?Fw(r,s,o):r:zw(r,n,o)},Uw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Yd(e,r,t)??r;return ep(t,e,s,o?.type,n)},qw=(t,e)=>Xd(t,e),tp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),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===n){u[l.name]=d;return}let m=Yd(l.name,d,t)??d,f=Xd(t,l.name);u[f]=ep(t,l.name,m,l.type,r)}),u});return{objectIds:o,attributes:s}},Bw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Kw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(d=>d.id===t),s=Bw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=Uw(o,e,i,n.timeZone),l=qw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function Gw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=vt(n),s=await Kw(t,e,r,o);return JSON.stringify(s,null,2)}var Ww=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.")})}),Vw=$(Gw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Ww}),$i=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function Gs(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Hw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(h=>h.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(a){let h=await Vs(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw Eo(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Eo(a)){let x=o.map?.allLayers.find(S=>S.id===a.layerId);m={geometryLayerName:x?.title??x?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else Ks(a)&&(m={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new Hd({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let I=$i(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Gs(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await my(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await fy({layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Gs(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((M,F)=>F.count-M.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(M=>({...M,value:S?S.getName(M.value)??M.value:M.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:m}}};async function Jw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Fn(o,"layersAndFieldsRegistry"),{mapView:a}=vt(o),i=await Hw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var Zw=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:Tt.optional().describe("The units for the distance buffer.")}),Qw=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:Tt.optional().describe("The units for the distance buffer.")}),Yw=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([Zw,Qw]).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.")}),Xw=$(Jw,{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.
|
|
150
150
|
|
|
151
151
|
USE THIS TOOL FOR:
|
|
152
152
|
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
@@ -158,7 +158,7 @@ DO NOT USE FOR:
|
|
|
158
158
|
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
159
159
|
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
160
160
|
|
|
161
|
-
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:Qw}),Xw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),eb=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let f=await Vs(n,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 n?n.where:"unknown criteria"}`}};u=f.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new fy({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new hy({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=Gs(s.definitionExpression,t.where||"1=1"),b.outFields=m.length?m:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),n?.distance&&(b.distance=n.distance),n?.units&&(b.units=n.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...Xw(e.orderByFields)])],h=$i(a,y,o??!1);try{f=h?await a.queryFeatures(b):await s.queryFeatures(b)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(b)}}let I=f.features.map(b=>b.attributes[d]),{attributes:w}=ep(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:I,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)}}}},tb=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=vt(o),a=await eb(t,e,s,r,n);return JSON.stringify(a,null,2)},rb=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:Tt.optional().describe("The units for the distance buffer.")}),nb=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:Tt.optional().describe("The units for the distance buffer.")}),ob=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([rb,nb]).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).")}),sb=$(tb,{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:ob}),vi=25,ab=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),ib=async(t,e,r,n)=>{let o=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let y=await Vs(r,e);if("error"in y){let h={error:y.error};if(Eo(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else Ks(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!y.geometry){let h={};if(Eo(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else Ks(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=y.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...ab(t.orderByFields)])],l=$i(s,u,n??!1),d=o.objectIdField,m=o.createQuery();m.where=Gs(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],m.orderByFields=t.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,I;try{f=l?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=vi&&(I=l?await s.queryFeatures(m):await o.queryFeatures(m))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await o.queryFeatureCount(m),f>0&&f<=vi&&(I=await o.queryFeatures(m))}let{objectIds:w,attributes:b}=I?ep(o,I,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>vi&&{note:`${f} features found.`}}}};async function lb({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=vt(n),s=await ib(t,o,e,r);return JSON.stringify(s,null,2)}var ub=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:Tt.optional().describe("The units for the distance buffer.")}),cb=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:Tt.optional().describe("The units for the distance buffer.")}),db=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([ub,cb]).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).")}),pb=$(lb,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
161
|
+
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:Yw}),eb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),tb=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let f=await Vs(n,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 n?n.where:"unknown criteria"}`}};u=f.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new hy({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new gy({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=Gs(s.definitionExpression,t.where||"1=1"),b.outFields=m.length?m:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),n?.distance&&(b.distance=n.distance),n?.units&&(b.units=n.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...eb(e.orderByFields)])],h=$i(a,y,o??!1);try{f=h?await a.queryFeatures(b):await s.queryFeatures(b)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(b)}}let I=f.features.map(b=>b.attributes[d]),{attributes:w}=tp(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:I,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)}}}},rb=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=vt(o),a=await tb(t,e,s,r,n);return JSON.stringify(a,null,2)},nb=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:Tt.optional().describe("The units for the distance buffer.")}),ob=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:Tt.optional().describe("The units for the distance buffer.")}),sb=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([nb,ob]).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).")}),ab=$(rb,{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:sb}),vi=25,ib=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),lb=async(t,e,r,n)=>{let o=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let y=await Vs(r,e);if("error"in y){let h={error:y.error};if(Eo(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else Ks(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!y.geometry){let h={};if(Eo(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else Ks(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=y.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...ib(t.orderByFields)])],l=$i(s,u,n??!1),d=o.objectIdField,m=o.createQuery();m.where=Gs(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],m.orderByFields=t.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,I;try{f=l?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=vi&&(I=l?await s.queryFeatures(m):await o.queryFeatures(m))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await o.queryFeatureCount(m),f>0&&f<=vi&&(I=await o.queryFeatures(m))}let{objectIds:w,attributes:b}=I?tp(o,I,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>vi&&{note:`${f} features found.`}}}};async function ub({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=vt(n),s=await lb(t,o,e,r);return JSON.stringify(s,null,2)}var cb=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:Tt.optional().describe("The units for the distance buffer.")}),db=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:Tt.optional().describe("The units for the distance buffer.")}),pb=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([cb,db]).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).")}),mb=$(ub,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
162
162
|
|
|
163
163
|
USE THIS TOOL FOR:
|
|
164
164
|
- "Show / display / list features where..." \u2014 finding and listing features
|
|
@@ -167,26 +167,26 @@ USE THIS TOOL FOR:
|
|
|
167
167
|
- Spatial queries \u2014 finding features near/within/intersecting other features
|
|
168
168
|
- Any question where the user wants to SEE or COUNT matching features
|
|
169
169
|
|
|
170
|
-
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:
|
|
170
|
+
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:pb}),rp=[Vw,Xw,ab,mb];var _V=new rt(rp,{handleToolErrors:!1});var fb=C.Root({...dr(),helpInternalState:C({reducer:Co,default:()=>({toolCallMessage:void 0})})}),hb=(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 n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
|
|
171
171
|
`);return`**${r.layerItem.title}** has ${n.length} field(s):
|
|
172
172
|
|
|
173
|
-
${o}`},
|
|
174
|
-
Relationship Types: ${n}.`}},Po=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=
|
|
173
|
+
${o}`},gb=async({layerTitle:t},e)=>{let r=Fn(e,"layersAndFieldsRegistry");return hb(r,t)},yb=$(gb,{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.")})}),_b=C.Root({...dr(),intent:C({reducer:(t,e)=>e}),arcgisKnowledgeMessages:C({reducer:Zn,default:()=>[]}),arcgisKnowledgeToolResult:C({reducer:(t,e)=>e,default:()=>null})});function np(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 Un(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function Hs(t){!t||Un(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Mo(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)&&np(r),{view:r}}async function qn(t){let e=t?.configurable?.context;if(wb(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Bd(n)}}else{np(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Bd(n)}}}}function wb(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 Si=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Ws.fromDataModel(e)}},Ws=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 n of e.entityTypes)r.entityTypes.push(Po.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(ki.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:bb(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(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
|
|
174
|
+
Relationship Types: ${n}.`}},Po=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=xb(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Ab(n.role),geometryDef:n.fieldType==="esriFieldTypeGeometry"?{geometryType:n.geometryType??"esriGeometryAny",hasM:n.hasM?n.hasM:void 0,hasZ:n.hasZ?n.hasZ:void 0}:void 0};r.properties.push(o)}return r}},ki=class extends Po{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Po.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},bb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},xb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Ab(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 Js(t){return t?.signal}async function Ib(t,e){let r=await nt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
|
|
175
175
|
|
|
176
176
|
Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
|
|
177
177
|
|
|
178
178
|
Attempt Number: ${e.attemptCount}
|
|
179
179
|
Execution Error: ${e.executionError}
|
|
180
180
|
Failed Query:
|
|
181
|
-
${e.failedGraphQuery}`:`${t} ${r}`}async function
|
|
181
|
+
${e.failedGraphQuery}`:`${t} ${r}`}async function vb(t,e,r,n){let{graphQuery:o,explanation:s}=await Ni(t,e,r,n);return{graphQuery:o,explanation:s}}async function Ni(t,e,r,n,o){let s={message:await Ib(t,o),context:new Si(e)},a=Js(n);await H({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await Fd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:Dd.findCredential(pr.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,m="",f="",I=1;for(;!u;){await new Promise(b=>setTimeout(b,1e3)),await H({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,I)}`},n),I=I%3+1;let w=await Fd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:Dd.findCredential(pr.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});m=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:m,explanation:f}}function Tb(t,e){Ln(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Ln(t,e){if(!(!t||typeof t!="object")){if(kb(t))for(let r of t.path)Ln(r,e);else if(Sb(t))e(t);else if(Array.isArray(t))for(let r of t)Ln(r,e);else if(Cb(t))for(let r of Object.values(t.properties??{}))Ln(r,e)}}function Sb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function kb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Cb(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Eb(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function Pb(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};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=o.namedTypeDefinitions.get(l.name);if(!d){a=!1,n.push(l.name);continue}if(!d.useAllData){a=!1,n.push(l.name);for(let[m]of d.members||[])u.push(m)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var Dn=3;function op(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function Bn(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 Mb=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,d=o?.signal,m=()=>{l.abort(d?.reason)};d&&(d.aborted?l.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let f=await _y(t,e,o);i=f.resultHeader;let I=f.resultRowsStream.getReader(),w=0,b=Date.now(),y=!1;for(;;){let{done:h,value:x}=await I.read();if(h)break;if(!y&&a&&Date.now()-b>a)return l.abort(),{type:"timeout"};for(let S of x){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,S)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Bn(f),error:f}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function sp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let d;for(let m=1;m<=Dn;m++){let f;try{f=await Ni(t,r.dataModel,n,l,d)}catch(y){return{type:"generation-error",errorMessage:Bn(y),error:y}}await H({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let I=await Ob(f.graphQuery,e),w=await Mb({kg:r,queryParams:new Zd({openCypherQuery:f.graphQuery,bindParameters:I}),targetStructure:o,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(m>=Dn)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:m},await H({text:`Attempt ${m} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Dn} attempts.`)}var Ob=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await xy(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},Rb=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let d=u-a.length;if(d<=0)break;let m=(await wy(t,new by({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:I,value:w}=await m.read();if(I){f=!0;break}for(let b of w)for(let y of b)a.push(y)}}}catch(l){let d=Bn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},ap="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function ip({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(ap),!Un(e)&&e.map){let d=await nt("arcgis_knowledge_current_lc_context"),m=Eb(e.map,r);return o.push(d),{enhancedPrompt:o.join(`
|
|
182
182
|
|
|
183
|
-
`),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=
|
|
183
|
+
`),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=Pb(s,r);if(a)return{enhancedPrompt:o.join(`
|
|
184
184
|
|
|
185
185
|
`),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await nt("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return o.push(l),{enhancedPrompt:o.join(`
|
|
186
186
|
|
|
187
|
-
`),bindParameters:i,allNamedTypesFullyDynamic:a}}async function
|
|
187
|
+
`),bindParameters:i,allNamedTypesFullyDynamic:a}}async function $b(t,e,r,n,o,s){let{view:a}=o,i=await sp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,I)=>{for(let w of I)Tb(w,f);return f},requestOptions:{signal:Js(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,m=Array.from(d.values());return await H({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Un(a)&&a?.map?(await a.map.addRecords(m),await Hs(a),{generatedQuery:u,explanation:l,addedIdTypePairs:m}):(await a?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:u,explanation:l,addedIdTypePairs:m})}var qs="addRecords",Nb=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.")}),zb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await qn(e),n=Mo(e),{view:o}=n,s=pr.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await ip({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:qs,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:m}=await $b(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:qs,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
|
|
188
188
|
|
|
189
|
-
Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:m}}}catch(l){let d=Bn(l);return{toolName:qs,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},
|
|
189
|
+
Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:m}}}catch(l){let d=Bn(l);return{toolName:qs,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},jb=$(zb,{name:qs,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.
|
|
190
190
|
|
|
191
191
|
example prompts:
|
|
192
192
|
- "add all suppliers and the parts they produce to the link chart"
|
|
@@ -196,15 +196,15 @@ Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,ad
|
|
|
196
196
|
- "expand company x through all the buildings it owns"
|
|
197
197
|
- "connect company x and company y"
|
|
198
198
|
- "connect all buildings on the link chart"
|
|
199
|
-
`,schema
|
|
199
|
+
`,schema:Nb});async function Lb(t,e){return await e.map?.applyLayout(t),await Hs(e),{appliedLayout:t}}var Ci="applyLayout",Db=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")}),Fb=async({layout:t},e)=>{let{view:r}=Mo(e);if(Un(r))return{toolName:Ci,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await Lb(t,r);return{toolName:Ci,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},Ub=$(Fb,{name:Ci,description:"Apply a diagram layout to the link chart",schema:Db});async function qb(t,e){return e.map?.changeNonspatialDataDisplay(t),await Hs(e),{appliedNonspatialDataDisplayMode:t}}var Ei="changeNonspatialVisibility",Bb=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Kb=async({setting:t},e)=>{let{view:r}=Mo(e);if(Un(r))return{toolName:Ei,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await qb(t,r);return{toolName:Ei,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},Gb=$(Kb,{name:Ei,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Bb});async function Wb(t,e,r,n,o){let s,a="";for(let i=1;i<=Dn;i++){let{graphQuery:u,explanation:l}=await Ni(t,e.dataModel,r,o,s);try{await H({text:`Attempting to create link chart from derived query: ${u}`},o);let d=await yy.fromCypherQuery(e,new Zd({openCypherQuery:u}));await H({text:"Link chart created successfully, loading..."},o),await d.load();let m=n.map;return n.map=d,await n.when(),await Wd.whenOnce(()=>!n.updating),d.entityCount===0&&d.relationshipCount===0?(n.map===d&&(n.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
|
|
200
200
|
${u}
|
|
201
201
|
|
|
202
|
-
Explanation: ${l}`}):(await Hs(n),{type:"success",graphQuery:u,explanation:l})}catch(d){let m=Bn(d);if(i>=Dn){a=m;break}s={failedGraphQuery:u,executionError:m,attemptCount:i},await H({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Dn} attempts. Last error: ${a}`}}var Bs="createLinkChart",
|
|
202
|
+
Explanation: ${l}`}):(await Hs(n),{type:"success",graphQuery:u,explanation:l})}catch(d){let m=Bn(d);if(i>=Dn){a=m;break}s={failedGraphQuery:u,executionError:m,attemptCount:i},await H({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Dn} attempts. Last error: ${a}`}}var Bs="createLinkChart",Vb=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.")}),Hb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await qn(e),{view:n}=Mo(e);if(Un(n))return{toolName:Bs,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=pr.getDefault().helperServices,s=await Wb(`${t}
|
|
203
203
|
|
|
204
|
-
${
|
|
204
|
+
${ap}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:Bs,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:Bs,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
|
|
205
205
|
${a}
|
|
206
206
|
|
|
207
|
-
Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},
|
|
207
|
+
Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},Jb=$(Hb,{name:Bs,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:Vb}),Pi="queryGraphData",Zb=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.")}),Qb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await qn(e),n=pr.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Mo(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await ip({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await sp({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,y)=>(b.push(y),b),requestOptions:{signal:Js(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:Pi,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:m}=i,f=m.headerKeys;for(let b of d)for(let y of b)Ln(y,h=>op(h));let I=50,w=d.slice(0,I).map(b=>JSON.stringify(b));return{toolName:Pi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
208
208
|
|
|
209
209
|
\`\`\`cypher
|
|
210
210
|
${u}
|
|
@@ -221,16 +221,16 @@ ${w.length>I?`Showing top ${I} results:
|
|
|
221
221
|
|
|
222
222
|
`}${w.join(`
|
|
223
223
|
`)}
|
|
224
|
-
`,details:{generatedQuery:u,explanation:l,resultHeader:m,queryResults:d}}},
|
|
224
|
+
`,details:{generatedQuery:u,explanation:l,resultHeader:m,queryResults:d}}},Yb=$(Qb,{name:Pi,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:Zb}),Mi="generateCypher",Xb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),ex=async({prompt:t},e)=>{let{knowledgeGraph:r}=await qn(e),n=pr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await vb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Mi,status:"success",summary:`Generated Graph Query:
|
|
225
225
|
${o}
|
|
226
226
|
|
|
227
|
-
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Bn(o);return{toolName:Mi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},
|
|
227
|
+
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Bn(o);return{toolName:Mi,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},tx=$(ex,{name:Mi,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:Xb}),rx=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(m=>d.add(m)),r.set(u,d)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
|
|
228
228
|
${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
229
229
|
`)}`,a=`Relationship Types:
|
|
230
230
|
${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
|
|
231
231
|
`)}`;return`${s}
|
|
232
232
|
|
|
233
|
-
${a}`};async function
|
|
233
|
+
${a}`};async function nx(t,e,r){let n=await nt("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:rx(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 ko({promptText:n,inputVariables:o,schema:u,config:r})}var Oi="searchGraphData",ox=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.")}),sx=async({prompt:t},e)=>{let{knowledgeGraph:r}=await qn(e);await H({text:"Generating search query for the user inquiry"},e);let n=await nx(t,r,e);await H({text:"Executing graph search with generated search query"},e);let o=await Rb({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:Js(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Oi,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)Ln(i,u=>op(u));let s=10,a=o.results.slice(0,s);return{toolName:Oi,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
|
|
234
234
|
Query: ${n.query}
|
|
235
235
|
Type Category Filter: ${n.typeCategoryFilter}
|
|
236
236
|
Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
|
|
@@ -241,7 +241,7 @@ ${a}`};async function rx(t,e,r){let n=await nt("arcgis_knowledge_lucene_generati
|
|
|
241
241
|
${o.results.length>s?`Showing top ${s} results:
|
|
242
242
|
|
|
243
243
|
`:""}${a.map(i=>JSON.stringify(i)).join(`
|
|
244
|
-
`)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},
|
|
244
|
+
`)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},ax=$(sx,{name:Oi,description:`
|
|
245
245
|
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.
|
|
246
246
|
Example prompts:
|
|
247
247
|
- "Find 'Bradley'"
|
|
@@ -250,7 +250,7 @@ ${a}`};async function rx(t,e,r){let n=await nt("arcgis_knowledge_lucene_generati
|
|
|
250
250
|
- "Find all references to 'delayed parts shipment'"
|
|
251
251
|
- "Find all reports authored by someone with the title of 'Researcher'"
|
|
252
252
|
- "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".
|
|
253
|
-
- "Search for all john smiths and show their global ids`,schema:
|
|
253
|
+
- "Search for all john smiths and show their global ids`,schema:ox});var JV=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
254
254
|
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.
|
|
255
255
|
|
|
256
256
|
Supported actions:
|
|
@@ -269,11 +269,11 @@ ${a}`};async function rx(t,e,r){let n=await nt("arcgis_knowledge_lucene_generati
|
|
|
269
269
|
_Example: “Center the map on San Francisco at scale 50000”_
|
|
270
270
|
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
271
271
|
_Example: “Go to the Downtown bookmark”_
|
|
272
|
-
_Example: “Where is Mount Rainier?”_`;var
|
|
272
|
+
_Example: “Where is Mount Rainier?”_`;var pH=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.
|
|
273
273
|
_Example: “Color points by sales amount”_
|
|
274
274
|
_Example: “Show population density with a color gradient”_
|
|
275
275
|
_Example: “Create a relationship map between height and depth”_
|
|
276
|
-
_Example: “Vary circle sizes according to population”_`;var
|
|
276
|
+
_Example: “Vary circle sizes according to population”_`;var zH=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).
|
|
277
277
|
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.
|
|
278
278
|
_Example: “Only show stations where Brand is Shell”_
|
|
279
279
|
_Example: “Make Shell stations stand out on the map”_
|
|
@@ -283,7 +283,7 @@ ${a}`};async function rx(t,e,r){let n=await nt("arcgis_knowledge_lucene_generati
|
|
|
283
283
|
_Example: “What’s the average population?”_
|
|
284
284
|
_Example: “Which values are in the status field?”_
|
|
285
285
|
|
|
286
|
-
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
|
|
286
|
+
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 e4=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 @@ ${a}`};async function rx(t,e,r){let n=await nt("arcgis_knowledge_lucene_generati
|
|
|
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 _4=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 Me=ko;var te=H,
|
|
337
|
+
_example: "What is the average age of all people who work for Esri?"_`;var Me=ko;var te=H,up=zd;var Kn=()=>Fs(),Qs=async(t,e)=>await me(t,e),Ys=async({modelTier:t="default",temperature:e=0,config:r}={})=>await Ai({modelTier:t,temperature:e,config:r});var Pp=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function fr(t){if(!Pp(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var cx=`
|
|
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
|
+
`,dx=t=>t.map(e=>`"${e}"`).join(", "),px=c.object({successMessage:c.string().default("")}),dp="portal-group-creation",pp="approveAddMembers",mx=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 n=t.intentParams.memberInfo.memberIdentifiers.map(m=>m.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
|
|
353
353
|
|
|
354
354
|
${n.map(m=>`- **@${m}**`).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!==dp||s.id!==pp){let m={agentId:dp,id:pp,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new $o(m)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await te({text:`Adding members ${dx(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;fr(a);let{result:i,error:u}=await Tl(a.portal,r,n);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 m=(await Me({promptText:cx,schema:px,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(m)return{status:"success",outputMessage:m}}catch(m){console.error("Error generating add-members success message:",m)}return{}},fx=`
|
|
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
|
+
`,hx=`
|
|
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
|
+
`,mp="portal-group-creation",fp="approveCreateGroup",gx=c.object({successMessage:c.string().default("")}),yx=c.object({failureMessage:c.string().default("")}),_x=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 n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==mp||o.id!==fp){let l={agentId:mp,id:fp,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new $o(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await te({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;fr(s);let{result:a,error:i}=await vl(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let d=(await Me({promptText:hx,schema:yx,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 Me({promptText:fx,schema:gx,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{}},Ue=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},wx=`
|
|
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
|
+
`,bx=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),xx=async(t,e)=>{await te({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Ue(t.agentExecutionContext.messages).trim(),n=await Me({promptText:wx,schema:bx,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},Ax=["favorites","group","living-atlas","org"],Ix=["featured","my","organization"],vx=["licenses","members","overview","reports","settings","status"],Tx=c.object({destinationType:c.literal("portal-content"),hash:c.enum(Ax).optional(),t9nKey:c.string().min(1).optional()}),Sx=c.object({destinationType:c.literal("portal-groups"),hash:c.enum(Ix).optional(),t9nKey:c.string().min(1).optional()}),kx=c.object({destinationType:c.literal("portal-org"),hash:c.enum(vx).optional(),t9nKey:c.string().min(1).optional()}),Cx=c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1),t9nKey:c.string().min(1).optional()}),Ex=c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1),t9nKey:c.string().min(1).optional()}),Px=c.object({destinationType:c.union([c.literal("portal-gallery"),c.literal("portal-map-viewer"),c.literal("portal-notebooks"),c.literal("portal-scene-viewer")]),t9nKey:c.string().min(1).optional()}),Mx=c.union([Tx,Sx,kx,Cx,Ex,Px]),Mp="portal-navigation",na=async(t,e)=>{let r=e?.configurable?.context;!Pp(r)||!r.navigationTargetMap?.[t.destinationType]||await Qs({type:Mp,data:{...t}},e)},Ox=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await te({text:"Preparing navigation...",agentName:"group-creation"},e),await na({destinationType:"portal-group",groupId:r},e),{}):{}},hp=(t,e)=>e??t,Op=C.Root({...Kn(),intentParams:C({reducer:hp,default:()=>({intent:"clarify"})}),createdGroupId:C({reducer:hp,default:()=>""})}),Rx=()=>new ue(Op).addNode("detectGroupCreationIntent",xx).addNode("createPortalGroup",_x).addNode("addMembersToPortalGroup",mx).addNode("suggestCreatedGroupNavigation",Ox).addEdge(le,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return U}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",U),$x=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
|
-
`),
|
|
412
|
+
`,Nx={id:"portal-group-creation",name:"Portal Group Creation",description:$x,createGraph:Rx,workspace:Op},Rp="portalDocAssistantMemory",zx=()=>({conversationId:""}),jx=t=>{let e=t?.[Rp]?.value;if(!e||typeof e!="object")return zx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Lx=t=>({[Rp]:{value:t}}),Dx={pipeline:{follow_up:{allow:!1}}};function Fx(t){return{kind:"DocAIAssistantRequest",filters:{...Dx,persona:{persona:t}}}}async function Ux({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=Fx(r),i=await qx({portal:t,skillId:s,message:e,options:{context:a,previousConversationId:n,signal:o}});return{reply:Bx(i,s),conversationId:i[0]?.conversationId??""}}async function qx({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:lx.findCredential(t.url)?.token??""},a=await cp(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:d}=i,m=async(f,I)=>{if(!I)return;await tl(500);let w=await cp(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:d,ackSequenceNumber:f}),headers:s,signal:n.signal});if(w.httpStatus!==200)throw new Error(`Doc assistant poll failed (${w.httpStatus})`,{cause:w.data});let b=w.data;u.push(b),await m(b.sequenceNumber,b.hasMore)};return i.hasMore&&await m(i.sequenceNumber,i.hasMore),u}function Bx(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 n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return Vn(e)}}var Kx=async(t,e)=>{await te({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Ue(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;fr(n);let o=jx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Ux({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:Lx({conversationId:a||o.conversationId})}},$p=$(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;fr(n);try{return(await Il(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),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.")})}),Np=$(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;fr(n);let{result:o,error:s}=await Sl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.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 Ro(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let n=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return n?.[1]?n[1].trim():null}var zp={"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"]}},Gx=rl(zp),Wx=Object.entries(zp).map(([t,{description:e,hints:r}])=>` - ${t}: ${e} (hints: ${r.join(", ")})`).join(`
|
|
413
|
+
`),Vx=`
|
|
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
|
+
`,gp=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...Gx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),Hx=async(t,e)=>{await te({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Ue(t.agentExecutionContext.messages).trim(),o=await gr.fromTemplate(Vx).format({question:n,response:r}),s=(await Ys({modelTier:"fast"})).withStructuredOutput(gp),a=gp.parse(await s.invoke(o));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Ro(n,"#");u&&(a.itemId=await Np.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Ro(n,"$")??Ro(n,"#");u&&(a.groupId=await $p.invoke({groupTitle:u},e)??"")}let i=Jx(a);return i?(await na(i,e),{}):{}};function Jx({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"};case"portal-content-favorites":return{destinationType:"portal-content",hash:"favorites"};case"portal-content-group":return{destinationType:"portal-content",hash:"group"};case"portal-content-living-atlas":return{destinationType:"portal-content",hash:"living-atlas"};case"portal-content-organization":return{destinationType:"portal-content",hash:"org"};case"portal-groups-featured":return{destinationType:"portal-groups",hash:"featured"};case"portal-groups-my":return{destinationType:"portal-groups",hash:"my"};case"portal-groups-organization":return{destinationType:"portal-groups",hash:"organization"};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 Vn(t)}}var jp=C.Root({...Kn()}),Zx=()=>new ue(jp).addNode("answerDocQuestion",Kx).addNode("extractNavigationIntent",Hx).addEdge(le,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",U),Qx=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
|
+
`,Yx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:Qx,createGraph:Zx,workspace:jp},Xx=()=>({latestGroupId:null,memory:{}}),oa=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:Xx()},Lp=`
|
|
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
|
+
`,eA=`
|
|
453
453
|
You answer follow-up questions about ArcGIS group analytics.
|
|
454
454
|
|
|
455
|
-
${
|
|
455
|
+
${Lp}
|
|
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
|
+
`,tA=async(t,e)=>{await te({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=oa(t),n=t.groupSummaryGroupId??r.latestGroupId,o=n?r.memory[n]:void 0,s=t.groupSummaryQuestion||Ue(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Me({promptText:eA,schema:rA,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.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>."}},rA=c.object({answer:c.string(),isRelevant:c.boolean()}),nA=`
|
|
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
|
+
`,oA=async(t,e)=>{await te({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=Ue(t.agentExecutionContext.messages),n=!!oa(t).latestGroupId,o=await gr.fromTemplate(nA).format({userMessage:r,hasAnalyticsContext:String(n)}),s=(await Ys({modelTier:"fast"})).withStructuredOutput(yp),a=yp.parse(await s.invoke(o)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let I=Ro(r,"$");I&&(i=await $p.invoke({groupTitle:I},e)??"")}let{intent:u,question:l}=a,d=u==="summarize"&&!i,m=u==="followUp"&&!(l??"").trim(),f=u==="clarify"||d||m;return{groupSummaryIntent:f?"clarify":u,groupSummaryGroupId:i||null,groupSummaryQuestion:l||"",status:"success",outputMessage:f?"Please clarify with a group id or title":""}},yp=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),sA=async(t,e)=>{let r=oa(t),n=t.groupSummaryGroupId??r.latestGroupId;return await te({text:"Preparing navigation...",agentName:"group-analytics"},e),await na(n?{destinationType:"portal-group",groupId:n}:{destinationType:"portal-groups"},e),{status:"success"}};function Dp({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var aA=720*60*60*1e3;function iA(t){let e=Cl(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:El(t),membershipAccess:Pl(t),isOpenData:Ml(t),isDistributedCollaborationGroup:Ol(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function lA(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 uA(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 cA(t,e){return t.filter(r=>r.modified?Dp({timestamp:r.modified,now:e,windowMs:aA}):!1)}function dA(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,n)=>n[1]-r[1]||r[0].localeCompare(n[0])).slice(0,6).map(([r,n])=>({type:r,count:n}))}async function pA(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=uA(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:cA(r,n),topItemTypes:dA(r)}}async function mA(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 n=iA(r),o=await lA(r),s=await pA(r);return{result:{group:n,members:o,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var fA=`
|
|
507
507
|
You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
|
|
508
508
|
|
|
509
|
-
${
|
|
509
|
+
${Lp}
|
|
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
|
+
`,hA=2160*60*60*1e3,gA=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 te({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let n=e?.configurable?.context;fr(n);let{result:o,error:s}=await mA(n.portal,r);if(s||!o)return await te({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}=o,u=Date.now(),l=a.modified,d=l?Dp({timestamp:l,now:u,windowMs:hA}):!1,m=i.recentlyModifiedItems.length,f=m>0,I=d||f,w=await Me({promptText:fA,schema:yA,modelTier:"default",inputVariables:{context:JSON.stringify(o),deterministicSignals:JSON.stringify({isGroupActive:I,isGroupRecentlyModified:d,hasRecentlyAddedOrUpdatedContent:f,recentItemCount:m})}}),{followUpQuestions:b,summary:y}=w,h=oa(t),x={latestGroupId:r,memory:{...h.memory,[r]:{summary:y,followUpQuestions:b,fullContext:o}}};return b.length&&await Qs({type:"suggested-prompts",data:{prompts:b}},e),{status:"success",outputMessage:y,sharedStatePatch:{portalGroupSummaryMemory:{value:x}}}},yA=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Li=(t,e)=>e??t,Fp=C.Root({...Kn(),groupSummaryIntent:C({reducer:Li,default:()=>"clarify"}),groupSummaryGroupId:C({reducer:Li,default:()=>null}),groupSummaryQuestion:C({reducer:Li,default:()=>""})}),_A=()=>new ue(Fp).addNode("detectGroupSummaryIntent",oA).addNode("summarizePortalGroup",gA).addNode("answerGroupSummaryFollowUp",tA).addNode("suggestGroupSummaryNavigation",sA).addEdge(le,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":U).addEdge("summarizePortalGroup",U).addEdge("answerGroupSummaryFollowUp",U).addEdge("suggestGroupSummaryNavigation",U),wA=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
|
+
`,bA={id:"portal-group-analytics",name:"Portal Group Analytics",description:wA,createGraph:_A,workspace:Fp},xA=()=>({latestItemId:null,memory:{}}),Gi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:xA()},_p=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),AA=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),IA=c.object({answer:c.string(),isRelevant:c.boolean()}),vA=`
|
|
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
|
+
`,TA=async(t,e)=>{await te({text:"Answering follow-up...",agentName:"analytics"},e);let r=Gi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Ue(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Me({promptText:vA,schema:IA,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.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>."}},SA=`
|
|
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
|
+
`,kA=async(t,e)=>{await te({text:"Analyzing intent...",agentName:"analytics"},e);let r=Ue(t.agentExecutionContext.messages),n=!!Gi(t).latestItemId,o=await gr.fromTemplate(SA).format({userMessage:r,hasSummaryContext:String(n)}),s=(await Ys({modelTier:"fast"})).withStructuredOutput(_p),a=_p.parse(await s.invoke(o)),i=a.itemId;if(a.intent==="summarize"&&!i){let m=Ro(r,"#");m&&(i=await Np.invoke({itemTitle:m},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>".':""}},CA=`
|
|
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
|
+
`,EA=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 te({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;fr(n);let{portal:o,user:s}=n,{result:a,error:i}=await kl(s,o,r);if(i||!a)return await te({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 Me({promptText:CA,schema:AA,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:m}=l,f=Gi(t),I={latestItemId:r,memory:{...f.memory,[r]:{summary:m,followUpQuestions:d,fullContext:u}}};return d.length&&await Qs({type:"suggested-prompts",data:{prompts:d}},e),{status:"success",outputMessage:m,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:I}}}},Di=(t,e)=>e??t,Up=C.Root({...Kn(),analyticsIntent:C({reducer:Di,default:()=>"clarify"}),analyticsItemId:C({reducer:Di,default:()=>null}),analyticsQuestion:C({reducer:Di,default:()=>""})}),PA=()=>new ue(Up).addNode("detectAnalyticsIntent",kA).addNode("summarizePortalItem",EA).addNode("answerAnalyticsFollowUp",TA).addEdge(le,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":U).addEdge("summarizePortalItem",U).addEdge("answerAnalyticsFollowUp",U),MA=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
|
+
`,OA={id:"portal-item-analytics",name:"Portal Item Analytics",description:MA,createGraph:PA,workspace:Up},RA={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"}}}]},$A={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"}}}]},NA={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"}}}]},zA={"contentRouteRegistry.ts":RA,"groupsRouteRegistry.ts":$A,"orgSettingsRouteRegistry.ts":NA};function wp(t){let e=[],r=new Set;for(let[n,o]of Object.entries(t))for(let s of o.capabilities){if(r.has(s.id))throw new Error(`${n}: duplicate capability id "${s.id}" across registries`);r.add(s.id),e.push(s)}return e}var Xs;function mr(t){return t?Xs=wp({customCapabilities:t}):Xs||(Xs=wp(zA)),Xs}var jA=/^(?:take me to|navigate to|go to|show me|open)\s+(?:the\s+)?/u;function ra(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu," ").trim().replace(jA,"").trim()}var LA=c.object({capabilityIds:c.array(c.string()).default([]),confidence:c.number().min(0).max(1).default(0),reason:c.string().default("")}),bp=.8,DA=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}`,FA=async(t,e)=>{if(t.outputMessage||t.targets.length===0)return{};let r=Ue(t.agentExecutionContext.messages).trim(),n=UA(r,t);if(n.length===1)return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"exact-match",request:r,selectedCapabilityIds:n}),{chosenCapabilityIds:n};await te({text:"Choosing a navigation destination...",agentName:"navigation"},e);let o=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 Me({promptText:DA,schema:LA,modelTier:"fast",inputVariables:{candidates:o,userRequest:r}}),a=new Set(t.targets.map(({capability:u})=>u.id)),i=s.capabilityIds.filter(u=>a.has(u));return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{confidence:s.confidence,method:"structured-model",reason:s.reason,request:r,selectedCapabilityIds:i}),s.confidence<bp?{chosenCapabilityIds:[],status:"failed",summary:`Navigation selection confidence ${s.confidence} is below the required ${bp}; defer to the Portal Doc Assistant.`}:{chosenCapabilityIds:i}}catch{return console.info("[arcgis-portal-ai-assistant] navigation capability selection:",{method:"structured-model-unavailable",request:r,selectedCapabilityIds:[]}),{chosenCapabilityIds:[]}}};function UA(t,e){let r=ra(t);return e.targets.filter(({capability:n})=>[n.title,...n.hints].some(o=>ra(o)===r)).map(({capability:n})=>n.id)}var qp=new Set(["1d","7d","14d","30d","3m","6m"]),qA=c.object({period:c.string(),startTime:c.string(),endTime:c.string()}),BA=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,10 +651,10 @@ Now UTC:
|
|
|
651
651
|
- Epoch ms: {nowEpochMs}
|
|
652
652
|
|
|
653
653
|
User request:
|
|
654
|
-
{userRequest}`;async function BA(t,e=new Date){let r=t.trim();if(!r)return{};try{let n=await Me({promptText:qA,schema:UA,modelTier:"fast",inputVariables:{nowEpochMs:String(e.getTime()),nowIso:e.toISOString(),userRequest:r}});return KA(n,e)}catch(n){return console.error(n),{}}}function KA(t,e=new Date){let r=bp(t.startTime),n=bp(t.endTime),o=GA(t.period);if(o){if(r!==void 0&&n!==void 0&&r<n)return{period:o,startTime:String(r),endTime:String(n)};let s=Up.has(o);if(!s||n!==void 0&&!VA(n,e.getTime())){let a=n??e.getTime(),i=WA(o,new Date(a));if(i!==void 0)return{period:o,startTime:String(i),endTime:String(a)}}return s?{period:o,...r!==void 0?{startTime:String(r)}:{},...n!==void 0?{endTime:String(n)}:{}}:{period:o}}return r!==void 0&&n!==void 0&&r<n?{startTime:String(r),endTime:String(n)}:r!==void 0?{startTime:String(r),endTime:String(e.getTime())}:{}}function GA(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 n=e[2].toLowerCase();if(n==="w"){let o=r*7;if(Up.has(`${o}d`))return`${o}d`}return`${r}${n}`}function WA(t,e){let r=t.match(/^(\d+)([dwm])$/u);if(!r)return;let n=Number.parseInt(r[1],10);if(!Number.isFinite(n)||n<=0)return;let o=r[2];if(o==="d")return e.getTime()-n*24*60*60*1e3;if(o==="w")return e.getTime()-n*7*24*60*60*1e3;let s=new Date(e.getTime());return s.setUTCMonth(s.getUTCMonth()-n),s.getTime()}function bp(t){if(!t)return;let e=Number.parseInt(t,10);if(!(!Number.isFinite(e)||e<=0))return e}function VA(t,e){let r=new Date(t),n=new Date(e);return r.getUTCFullYear()===n.getUTCFullYear()&&r.getUTCMonth()===n.getUTCMonth()&&r.getUTCDate()===n.getUTCDate()}async function HA(t,e,r){let n=mr().find(s=>s.id===t);if(!n)return;let o=await ZA(JA(n),r);return o&&YA(o,e)?{capability:n,target:o}:void 0}function JA(t){let{hash:e,queryParams:r,routeKey:n}=t.resolutions.navigate;switch(n){case"content":switch(t.id){case"my-content":return{destinationType:"portal-content",t9nKey:"myContent"};case"create-feature-layer":return{destinationType:"portal-content",t9nKey:"createFeatureLayer"};case"create-folder":return{destinationType:"portal-content",t9nKey:"createFolder"};default:return{destinationType:"portal-content"}}case"groups":if(e==="featured")return{destinationType:"portal-groups",hash:"featured",t9nKey:"featuredGroups"};if(e==="organization")return{destinationType:"portal-groups",hash:"organization",t9nKey:"organizationGroups"};switch(t.id){case"my groups":return{destinationType:"portal-groups",hash:"my",t9nKey:"myGroups"};case"create-group":return{destinationType:"portal-groups",t9nKey:"createGroup"};default:return{destinationType:"portal-groups"}}case"organization":return{destinationType:"portal-org",hash:e,queryParams:r,buttonLabel:t.buttonLabel};default:return}}async function ZA(t,e){if(!t||!e||!QA(t))return t;let r=await BA(e);if(!r.period&&!r.startTime&&!r.endTime)return t;let n={...t.queryParams,...r.period?{period:r.period}:{},...r.startTime?{startTime:r.startTime}:{},...r.endTime?{endTime:r.endTime}:{}};return{...t,queryParams:n}}function QA(t){return t.destinationType==="portal-org"&&t.hash==="status"}function YA(t,e){return!e||!!e[t.destinationType]}var XA=async(t,e)=>{if(t.outputMessage||t.status==="failed")return{};let r=t.targets.find(({capability:s})=>t.chosenCapabilityIds.includes(s.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:xp(t)}},status:"success",summary:"Navigation could not find a matching capability; route another agent if appropriate."};let n=xp(t),o=await HA(r.capability.id,void 0,n);return o?(await te({text:"Preparing navigation...",agentName:"navigation"},e),await na(o.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:n}}}):(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:n}}})};function xp(t){return Ue(t.agentExecutionContext.messages)||t.agentExecutionContext.userRequest}async function qp(t){return t.length===0?[]:(await lx.getDefault().load(),await lp(t))}var eI=Object.freeze(Object.defineProperty({__proto__:null,generateEmbeddings:qp},Symbol.toStringTag,{value:"Module"}));function tI(t){let e=[],r=`${t.title}. ${t.description}`;r.trim().length>0&&e.push({field:"summary",text:r});let n=t.hints;if(Array.isArray(n))for(let o of n)typeof o=="string"&&o.trim().length>0&&e.push({field:"hint",text:o});return e}var ea,Wi,ta=0;async function rI(t={}){let e=ta;return ea??=oI(t.embed??sI).then(r=>(e===ta&&(Wi=r),r)).catch(r=>{throw e===ta&&(ea=void 0),r}),await ea}function nI(){return Wi}function Ap(){ta+=1,Wi=void 0,ea=void 0}async function oI(t){let e=aI(),r=await t(e.map(n=>n.text));if(r.length!==e.length)throw new Error(`Expected ${e.length} vectors, got ${r.length}`);return e.map((n,o)=>({...n,vector:r[o]}))}async function sI(t){let{generateEmbeddings:e}=await Promise.resolve().then(()=>eI);return await e(t)}function aI(){return mr().flatMap(t=>tI(t).map(({field:e,text:r})=>({capabilityId:t.id,field:e,text:r})))}var Ip=1.2,vp=.75,iI=60,lI=.65,Fi={description:1,hint:2,title:3},Bi;function uI(){Bi=void 0}async function cI(t,e={}){let r=fI(Bp(t)),n=[],o=!1,s;if(t.trim()){let a=e.loadEmbeddings,i=nI();if(!a&&!i)o=!0,s="Capability embeddings are still loading.";else try{if(a){let[u,l]=await Promise.all([(e.embedQuery??Sp)(t),a()]);n=Tp(u,l)}else if(i){let u=await(e.embedQuery??Sp)(t);n=Tp(u,i)}}catch{o=!0,s="Semantic search is unavailable."}}return{degraded:o,...s?{degradedReason:s}:{},matches:gI(r,n,e.topN??5)}}function dI(){return Bi??=pI(mr()),Bi}function pI(t){let e=new Map,r=t.map(n=>{let o=new Map;Ui(o,n.title,Fi.title),Ui(o,n.description,Fi.description);for(let s of n.hints)Ui(o,s,Fi.hint);for(let s of o.keys())e.set(s,(e.get(s)??0)+1);return{capability:n,length:mI(o),termFrequencies:o}});return{averageDocumentLength:r.length?r.reduce((n,o)=>n+o.length,0)/r.length:0,documentFrequency:e,documents:r}}function Ui(t,e,r){for(let n of Bp(e))t.set(n,(t.get(n)??0)+r)}function mI(t){return[...t.values()].reduce((e,r)=>e+r,0)}function Bp(t){return t.toLowerCase().split(/[^a-z0-9]+/u).filter(Boolean)}function fI(t){let e=dI(),r=new Set(t),n=e.documents.length;return e.documents.map(({capability:o,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 m=Math.log(1+(n-d+.5)/(d+.5)),f=Ip*(1-vp+vp*(s/e.averageDocumentLength));i+=m*(l*(Ip+1)/(l+f))}return{capability:o,score:i}}).filter(({score:o})=>o>0).sort(Kp)}function Tp(t,e){let r=new Map;for(let o of e){let s=hI(t,o.vector);if(s===void 0)continue;let a=r.get(o.capabilityId);(a===void 0||s>a)&&r.set(o.capabilityId,s)}let n=new Map(mr().map(o=>[o.id,o]));return[...r.entries()].flatMap(([o,s])=>{let a=n.get(o);return a&&s>=lI?[{capability:a,score:s}]:[]}).sort(Kp)}function hI(t,e){if(t.length===0||t.length!==e.length)return;let r=0,n=0,o=0;for(let a=0;a<t.length;a+=1)r+=t[a]*e[a],n+=t[a]**2,o+=e[a]**2;let s=Math.sqrt(n)*Math.sqrt(o);return s===0?void 0:r/s}async function Sp(t){let[e]=await qp([t]);if(!e)throw new Error("Expected one query embedding.");return e}function gI(t,e,r){let n=new Map;return kp(n,t,"keyword"),kp(n,e,"semantic"),[...n.values()].sort((o,s)=>s.score!==o.score?s.score-o.score:(s.semanticScore??0)!==(o.semanticScore??0)?(s.semanticScore??0)-(o.semanticScore??0):(s.keywordScore??0)!==(o.keywordScore??0)?(s.keywordScore??0)-(o.keywordScore??0):o.capability.id.localeCompare(s.capability.id)).slice(0,Math.max(0,r))}function kp(t,e,r){for(let[n,{capability:o,score:s}]of e.entries()){let a=n+1,i=t.get(o.id)??{capability:o,score:0};i.score+=1/(iI+a),r==="keyword"?(i.keywordRank=a,i.keywordScore=s):(i.semanticRank=a,i.semanticScore=s),t.set(o.id,i)}}function Kp(t,e){return e.score-t.score||t.capability.id.localeCompare(e.capability.id)}var yI=async(t,e)=>{await te({text:"Finding a place to navigate...",agentName:"navigation"},e);let r=Ue(t.agentExecutionContext.messages).trim();try{let n=await cI(r,{topN:5});return console.table(n.matches.map(({capability:o,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u,score:l})=>({capability:o.title,fusedScore:l,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u}))),n.degradedReason&&console.info("[arcgis-portal-ai-assistant] navigation semantic search:",n.degradedReason),{chosenCapabilityIds:[],retrievalDegraded:n.degradedReason??"",targets:_I(r,n.matches)}}catch{return{chosenCapabilityIds:[],outputMessage:"I couldn't look up a Portal page right now. Please try again.",status:"failed",targets:[]}}};function _I(t,e){let r=ra(t),n=e.filter(({capability:s})=>[s.title,...s.hints].some(a=>ra(a)===r));if(n.length!==1)return e;let[o]=n;return[o,...e.filter(s=>s!==o)]}var qi=(t,e)=>e??t,Gp=C.Root({...Kn(),chosenCapabilityIds:C({reducer:qi,default:()=>[]}),retrievalDegraded:C({reducer:qi,default:()=>""}),targets:C({reducer:qi,default:()=>[]})}),wI=()=>new ue(Gp).addNode("retrieveNavigationTargets",yI).addNode("chooseNavigationTargets",DA).addNode("respondWithNavigation",XA).addEdge(le,"retrieveNavigationTargets").addEdge("retrieveNavigationTargets","chooseNavigationTargets").addEdge("chooseNavigationTargets","respondWithNavigation").addEdge("respondWithNavigation",U);function bI(){let t=mr().map(({hints:e,title:r})=>e[0]??r).join(", ");return String.raw`- **portal-navigation** - Portal page navigation assistant:
|
|
654
|
+
{userRequest}`;async function KA(t,e=new Date){let r=t.trim();if(!r)return{};try{let n=await Me({promptText:BA,schema:qA,modelTier:"fast",inputVariables:{nowEpochMs:String(e.getTime()),nowIso:e.toISOString(),userRequest:r}});return GA(n,e)}catch(n){return console.error(n),{}}}function GA(t,e=new Date){let r=xp(t.startTime),n=xp(t.endTime),o=WA(t.period);if(o){if(r!==void 0&&n!==void 0&&r<n)return{period:o,startTime:String(r),endTime:String(n)};let s=qp.has(o);if(!s||n!==void 0&&!HA(n,e.getTime())){let a=n??e.getTime(),i=VA(o,new Date(a));if(i!==void 0)return{period:o,startTime:String(i),endTime:String(a)}}return s?{period:o,...r!==void 0?{startTime:String(r)}:{},...n!==void 0?{endTime:String(n)}:{}}:{period:o}}return r!==void 0&&n!==void 0&&r<n?{startTime:String(r),endTime:String(n)}:r!==void 0?{startTime:String(r),endTime:String(e.getTime())}:{}}function WA(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 n=e[2].toLowerCase();if(n==="w"){let o=r*7;if(qp.has(`${o}d`))return`${o}d`}return`${r}${n}`}function VA(t,e){let r=t.match(/^(\d+)([dwm])$/u);if(!r)return;let n=Number.parseInt(r[1],10);if(!Number.isFinite(n)||n<=0)return;let o=r[2];if(o==="d")return e.getTime()-n*24*60*60*1e3;if(o==="w")return e.getTime()-n*7*24*60*60*1e3;let s=new Date(e.getTime());return s.setUTCMonth(s.getUTCMonth()-n),s.getTime()}function xp(t){if(!t)return;let e=Number.parseInt(t,10);if(!(!Number.isFinite(e)||e<=0))return e}function HA(t,e){let r=new Date(t),n=new Date(e);return r.getUTCFullYear()===n.getUTCFullYear()&&r.getUTCMonth()===n.getUTCMonth()&&r.getUTCDate()===n.getUTCDate()}async function JA(t,e,r){let n=mr().find(s=>s.id===t);if(!n)return;let o=await QA(ZA(n),r);return o&&XA(o,e)?{capability:n,target:o}:void 0}function ZA(t){let{hash:e,queryParams:r,routeKey:n}=t.resolutions.navigate;switch(n){case"content":switch(t.id){case"my-content":return{destinationType:"portal-content",t9nKey:"myContent"};case"create-feature-layer":return{destinationType:"portal-content",t9nKey:"createFeatureLayer"};case"create-folder":return{destinationType:"portal-content",t9nKey:"createFolder"};default:return{destinationType:"portal-content"}}case"groups":if(e==="featured")return{destinationType:"portal-groups",hash:"featured",t9nKey:"featuredGroups"};if(e==="organization")return{destinationType:"portal-groups",hash:"organization",t9nKey:"organizationGroups"};switch(t.id){case"my groups":return{destinationType:"portal-groups",hash:"my",t9nKey:"myGroups"};case"create-group":return{destinationType:"portal-groups",t9nKey:"createGroup"};default:return{destinationType:"portal-groups"}}case"organization":return{destinationType:"portal-org",hash:e,queryParams:r,buttonLabel:t.buttonLabel};default:return}}async function QA(t,e){if(!t||!e||!YA(t))return t;let r=await KA(e);if(!r.period&&!r.startTime&&!r.endTime)return t;let n={...t.queryParams,...r.period?{period:r.period}:{},...r.startTime?{startTime:r.startTime}:{},...r.endTime?{endTime:r.endTime}:{}};return{...t,queryParams:n}}function YA(t){return t.destinationType==="portal-org"&&t.hash==="status"}function XA(t,e){return!e||!!e[t.destinationType]}var eI=async(t,e)=>{if(t.outputMessage||t.status==="failed")return{};let r=t.targets.find(({capability:s})=>t.chosenCapabilityIds.includes(s.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:Ap(t)}},status:"success",summary:"Navigation could not find a matching capability; route another agent if appropriate."};let n=Ap(t),o=await JA(r.capability.id,void 0,n);return o?(await te({text:"Preparing navigation...",agentName:"navigation"},e),await na(o.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:n}}}):(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:n}}})};function Ap(t){return Ue(t.agentExecutionContext.messages)||t.agentExecutionContext.userRequest}async function Bp(t){return t.length===0?[]:(await ux.getDefault().load(),await up(t))}var tI=Object.freeze(Object.defineProperty({__proto__:null,generateEmbeddings:Bp},Symbol.toStringTag,{value:"Module"}));function rI(t){let e=[],r=`${t.title}. ${t.description}`;r.trim().length>0&&e.push({field:"summary",text:r});let n=t.hints;if(Array.isArray(n))for(let o of n)typeof o=="string"&&o.trim().length>0&&e.push({field:"hint",text:o});return e}var ea,Wi,ta=0;async function nI(t={}){let e=ta;return ea??=sI(t.embed??aI).then(r=>(e===ta&&(Wi=r),r)).catch(r=>{throw e===ta&&(ea=void 0),r}),await ea}function oI(){return Wi}function Ip(){ta+=1,Wi=void 0,ea=void 0}async function sI(t){let e=iI(),r=await t(e.map(n=>n.text));if(r.length!==e.length)throw new Error(`Expected ${e.length} vectors, got ${r.length}`);return e.map((n,o)=>({...n,vector:r[o]}))}async function aI(t){let{generateEmbeddings:e}=await Promise.resolve().then(()=>tI);return await e(t)}function iI(){return mr().flatMap(t=>rI(t).map(({field:e,text:r})=>({capabilityId:t.id,field:e,text:r})))}var vp=1.2,Tp=.75,lI=60,uI=.65,Fi={description:1,hint:2,title:3},Bi;function cI(){Bi=void 0}async function dI(t,e={}){let r=hI(Kp(t)),n=[],o=!1,s;if(t.trim()){let a=e.loadEmbeddings,i=oI();if(!a&&!i)o=!0,s="Capability embeddings are still loading.";else try{if(a){let[u,l]=await Promise.all([(e.embedQuery??kp)(t),a()]);n=Sp(u,l)}else if(i){let u=await(e.embedQuery??kp)(t);n=Sp(u,i)}}catch{o=!0,s="Semantic search is unavailable."}}return{degraded:o,...s?{degradedReason:s}:{},matches:yI(r,n,e.topN??5)}}function pI(){return Bi??=mI(mr()),Bi}function mI(t){let e=new Map,r=t.map(n=>{let o=new Map;Ui(o,n.title,Fi.title),Ui(o,n.description,Fi.description);for(let s of n.hints)Ui(o,s,Fi.hint);for(let s of o.keys())e.set(s,(e.get(s)??0)+1);return{capability:n,length:fI(o),termFrequencies:o}});return{averageDocumentLength:r.length?r.reduce((n,o)=>n+o.length,0)/r.length:0,documentFrequency:e,documents:r}}function Ui(t,e,r){for(let n of Kp(e))t.set(n,(t.get(n)??0)+r)}function fI(t){return[...t.values()].reduce((e,r)=>e+r,0)}function Kp(t){return t.toLowerCase().split(/[^a-z0-9]+/u).filter(Boolean)}function hI(t){let e=pI(),r=new Set(t),n=e.documents.length;return e.documents.map(({capability:o,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 m=Math.log(1+(n-d+.5)/(d+.5)),f=vp*(1-Tp+Tp*(s/e.averageDocumentLength));i+=m*(l*(vp+1)/(l+f))}return{capability:o,score:i}}).filter(({score:o})=>o>0).sort(Gp)}function Sp(t,e){let r=new Map;for(let o of e){let s=gI(t,o.vector);if(s===void 0)continue;let a=r.get(o.capabilityId);(a===void 0||s>a)&&r.set(o.capabilityId,s)}let n=new Map(mr().map(o=>[o.id,o]));return[...r.entries()].flatMap(([o,s])=>{let a=n.get(o);return a&&s>=uI?[{capability:a,score:s}]:[]}).sort(Gp)}function gI(t,e){if(t.length===0||t.length!==e.length)return;let r=0,n=0,o=0;for(let a=0;a<t.length;a+=1)r+=t[a]*e[a],n+=t[a]**2,o+=e[a]**2;let s=Math.sqrt(n)*Math.sqrt(o);return s===0?void 0:r/s}async function kp(t){let[e]=await Bp([t]);if(!e)throw new Error("Expected one query embedding.");return e}function yI(t,e,r){let n=new Map;return Cp(n,t,"keyword"),Cp(n,e,"semantic"),[...n.values()].sort((o,s)=>s.score!==o.score?s.score-o.score:(s.semanticScore??0)!==(o.semanticScore??0)?(s.semanticScore??0)-(o.semanticScore??0):(s.keywordScore??0)!==(o.keywordScore??0)?(s.keywordScore??0)-(o.keywordScore??0):o.capability.id.localeCompare(s.capability.id)).slice(0,Math.max(0,r))}function Cp(t,e,r){for(let[n,{capability:o,score:s}]of e.entries()){let a=n+1,i=t.get(o.id)??{capability:o,score:0};i.score+=1/(lI+a),r==="keyword"?(i.keywordRank=a,i.keywordScore=s):(i.semanticRank=a,i.semanticScore=s),t.set(o.id,i)}}function Gp(t,e){return e.score-t.score||t.capability.id.localeCompare(e.capability.id)}var _I=async(t,e)=>{await te({text:"Finding a place to navigate...",agentName:"navigation"},e);let r=Ue(t.agentExecutionContext.messages).trim();try{let n=await dI(r,{topN:5});return console.table(n.matches.map(({capability:o,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u,score:l})=>({capability:o.title,fusedScore:l,keywordRank:s,keywordScore:a,semanticRank:i,semanticScore:u}))),n.degradedReason&&console.info("[arcgis-portal-ai-assistant] navigation semantic search:",n.degradedReason),{chosenCapabilityIds:[],retrievalDegraded:n.degradedReason??"",targets:wI(r,n.matches)}}catch{return{chosenCapabilityIds:[],outputMessage:"I couldn't look up a Portal page right now. Please try again.",status:"failed",targets:[]}}};function wI(t,e){let r=ra(t),n=e.filter(({capability:s})=>[s.title,...s.hints].some(a=>ra(a)===r));if(n.length!==1)return e;let[o]=n;return[o,...e.filter(s=>s!==o)]}var qi=(t,e)=>e??t,Wp=C.Root({...Kn(),chosenCapabilityIds:C({reducer:qi,default:()=>[]}),retrievalDegraded:C({reducer:qi,default:()=>""}),targets:C({reducer:qi,default:()=>[]})}),bI=()=>new ue(Wp).addNode("retrieveNavigationTargets",_I).addNode("chooseNavigationTargets",FA).addNode("respondWithNavigation",eI).addEdge(le,"retrieveNavigationTargets").addEdge("retrieveNavigationTargets","chooseNavigationTargets").addEdge("chooseNavigationTargets","respondWithNavigation").addEdge("respondWithNavigation",U);function xI(){let t=mr().map(({hints:e,title:r})=>e[0]??r).join(", ");return String.raw`- **portal-navigation** - Portal page navigation assistant:
|
|
655
655
|
- routes requests to open, show, or navigate to a Portal page, including creation-flow pages
|
|
656
656
|
- falls back to the closest Portal page where a workflow starts when another agent cannot perform the action
|
|
657
657
|
- handles short navigation follow-ups after asking the user to open a page
|
|
658
658
|
- capability examples: ${t}
|
|
659
659
|
- do not use for general "how do I" questions unless the user explicitly asks to reach a page
|
|
660
|
-
`}var xI={id:"navigation",name:"Portal Navigation",get description(){return bI()},createGraph:wI,workspace:Gp},AI=Ji`: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 II(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":return e[r]?.(t.hash);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);default:return Vn(r)}}function vI(t){let e=Px.safeParse(t);return e.success?e.data:void 0}var TI={myContent:"My content",createFeatureLayer:"Create feature layer",createFolder:"Create folder",myGroups:"My groups",createGroup:"Create group",featuredGroups:"Featured groups",organizationGroups:"Organization groups",configureMultifactorAuthentication:"Configure multifactor authentication"},Wp={navigationTargets:TI};function SI(t,e){let r=Cp(t.t9nKey,e.navigationTargets)??Cp(t.t9nKey,Wp.navigationTargets);if(r)return r;let n=e.navigation;switch(t.destinationType){case"portal-content":switch(t.hash){case"favorites":return n.openContentFavorites;case"group":return n.openContentGroup;case"living-atlas":return n.openContentLivingAtlas;case"org":return n.openContentOrganization;default:return n.openContent}case"portal-gallery":return n.openGallery;case"portal-groups":switch(t.hash){case"featured":return n.openGroupsFeatured;case"my":return n.openGroupsMy;case"organization":return n.openGroupsOrganization;default:return n.openGroups}case"portal-map-viewer":return n.openMapViewer;case"portal-notebooks":return n.openNotebooks;case"portal-scene-viewer":return n.openSceneViewer;case"portal-org":return n.openOrgSettings;case"portal-item":return n.openItem;case"portal-group":return n.openGroup;default:return Vn(t)}}function Cp(t,e){if(!(!t||!e||!kI(t)))return e[t]}function kI(t){return t in Wp.navigationTargets}var Ki=class extends Xi{constructor(){super(),this.t9n=nl({blocking:!0}),this.assistantEl=Gn(),this.formEl=Gn(),this.voiceInputEl=Gn(),this.inputEl=Gn(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=Qi(),mr()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,disabledAgents:0,defaultClosed:5,navigationCapabilities:0}}static{this.styles=AI}async load(){await this.refreshCapabilityEmbeddings()}willUpdate(e){!this.hasUpdated||!e.has("navigationCapabilities")||this.refreshCapabilityEmbeddings()}async clearEmbeddingsCache(){Ap()}isAgentEnabled(e){return!this.disabledAgents?.[e]}async refreshCapabilityEmbeddings(){try{mr(this.navigationCapabilities),uI(),Ap(),await rI()}catch(e){console.warn("[arcgis-portal-ai-assistant] embeddings warm-up failed:",e)}}getNavigationAction(e){if(e?.type!==Pp)return;let r=e.data,n=vI(r);if(!n)return;let o=II(r,this.navigationTargetMap);if(o)return{href:o,targetDetail:r,label:r?.buttonLabel||SI(n,this.t9n)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=`navigation:${e}`,s=this.navigationSlotElements.get(o);s||(s=document.createElement("div"),s.slot=e,this.navigationSlotElements.set(o,s),n.append(s)),Zi(xe`<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?xe`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,s)}render(){let{t9n:e,inputText:r,portal:n,user:o,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return xe`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:l})=>{this.interrupt=l}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:l})=>{this.inputText=l.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${Wn(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=${l=>{l.preventDefault();let d=r.trim();d&&(this.assistantEl.value?.submitMessage(d),this.inputText="")}} ${Wn(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:l})=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:l})=>{this.inputText=l??""}} ${Wn(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=${l=>{l.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${l=>{this.inputText=l.detail.text}} ${Wn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&xe`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let l=this.voiceInputEl.value;i?await l?.stopListening():await l?.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")&&xe`<arcgis-assistant-agent .agent=${MA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupCreation")&&xe`<arcgis-assistant-agent .agent=${$x} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("docAssistant")&&xe`<arcgis-assistant-agent .agent=${Qx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupAnalytics")&&xe`<arcgis-assistant-agent .agent=${wA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("navigation")&&xe`<arcgis-assistant-agent .agent=${xI} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.interrupt&&xe`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:l})=>{this.assistantEl.value?.submitInterrupt(l)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};el("arcgis-portal-ai-assistant",Ki);return Ki},"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","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","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","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","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","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)
|
|
660
|
+
`}var AI={id:"navigation",name:"Portal Navigation",get description(){return xI()},createGraph:bI,workspace:Wp},II=Ji`: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 vI(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":return e[r]?.(t.hash);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);default:return Vn(r)}}function TI(t){let e=Mx.safeParse(t);return e.success?e.data:void 0}var SI={myContent:"My content",createFeatureLayer:"Create feature layer",createFolder:"Create folder",myGroups:"My groups",createGroup:"Create group",featuredGroups:"Featured groups",organizationGroups:"Organization groups",configureMultifactorAuthentication:"Configure multifactor authentication"},Vp={navigationTargets:SI};function kI(t,e){let r=Ep(t.t9nKey,e.navigationTargets)??Ep(t.t9nKey,Vp.navigationTargets);if(r)return r;let n=e.navigation;switch(t.destinationType){case"portal-content":switch(t.hash){case"favorites":return n.openContentFavorites;case"group":return n.openContentGroup;case"living-atlas":return n.openContentLivingAtlas;case"org":return n.openContentOrganization;default:return n.openContent}case"portal-gallery":return n.openGallery;case"portal-groups":switch(t.hash){case"featured":return n.openGroupsFeatured;case"my":return n.openGroupsMy;case"organization":return n.openGroupsOrganization;default:return n.openGroups}case"portal-map-viewer":return n.openMapViewer;case"portal-notebooks":return n.openNotebooks;case"portal-scene-viewer":return n.openSceneViewer;case"portal-org":return n.openOrgSettings;case"portal-item":return n.openItem;case"portal-group":return n.openGroup;default:return Vn(t)}}function Ep(t,e){if(!(!t||!e||!CI(t)))return e[t]}function CI(t){return t in Vp.navigationTargets}var Ki=class extends Xi{constructor(){super(),this.t9n=nl({blocking:!0}),this.assistantEl=Gn(),this.formEl=Gn(),this.voiceInputEl=Gn(),this.inputEl=Gn(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=Qi(),mr()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,disabledAgents:0,defaultClosed:5,navigationCapabilities:0}}static{this.styles=II}async load(){await this.refreshCapabilityEmbeddings()}willUpdate(e){!this.hasUpdated||!e.has("navigationCapabilities")||this.refreshCapabilityEmbeddings()}async clearEmbeddingsCache(){Ip()}isAgentEnabled(e){return!this.disabledAgents?.[e]}async refreshCapabilityEmbeddings(){try{mr(this.navigationCapabilities),cI(),Ip(),await nI()}catch(e){console.warn("[arcgis-portal-ai-assistant] embeddings warm-up failed:",e)}}getNavigationAction(e){if(e?.type!==Mp)return;let r=e.data,n=TI(r);if(!n)return;let o=vI(r,this.navigationTargetMap);if(o)return{href:o,targetDetail:r,label:r?.buttonLabel||kI(n,this.t9n)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=`navigation:${e}`,s=this.navigationSlotElements.get(o);s||(s=document.createElement("div"),s.slot=e,this.navigationSlotElements.set(o,s),n.append(s)),Zi(xe`<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?xe`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,s)}render(){let{t9n:e,inputText:r,portal:n,user:o,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return xe`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:l})=>{this.interrupt=l}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:l})=>{this.inputText=l.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${Wn(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=${l=>{l.preventDefault();let d=r.trim();d&&(this.assistantEl.value?.submitMessage(d),this.inputText="")}} ${Wn(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:l})=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:l})=>{this.inputText=l??""}} ${Wn(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=${l=>{l.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${l=>{this.inputText=l.detail.text}} ${Wn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&xe`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let l=this.voiceInputEl.value;i?await l?.stopListening():await l?.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")&&xe`<arcgis-assistant-agent .agent=${OA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupCreation")&&xe`<arcgis-assistant-agent .agent=${Nx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("docAssistant")&&xe`<arcgis-assistant-agent .agent=${Yx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupAnalytics")&&xe`<arcgis-assistant-agent .agent=${bA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("navigation")&&xe`<arcgis-assistant-agent .agent=${AI} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.interrupt&&xe`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:l})=>{this.assistantEl.value?.submitInterrupt(l)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};el("arcgis-portal-ai-assistant",Ki);return Ki},"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","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","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","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","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","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)
|