@arcgis/portal-components 5.2.0-next.71 → 5.2.0-next.72
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.
- package/LICENSE.md +4 -2
- package/dist/cdn/{2IIE3YY2.js → 4HZG3T4B.js} +86 -86
- package/dist/cdn/{UUGX7XW6.js → KPDZDJTT.js} +1 -1
- package/dist/cdn/{YPRKDQA4.js → SSLWBHRC.js} +1 -1
- package/dist/cdn/W2AW2BW3.js +2 -0
- package/dist/cdn/{3IA7YX3J.js → YY4236HO.js} +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/portal-item-badge.js +107 -104
- package/dist/components/arcgis-portal-ai-assistant/agents/portalRouteKeys.d.ts +26 -0
- package/dist/components/arcgis-portal-ai-assistant/agents/types.d.ts +19 -4
- package/dist/components/arcgis-portal-ai-assistant/customElement.js +920 -780
- package/dist/components/arcgis-portal-navigation/customElement.js +1 -1
- package/dist/components/arcgis-portal-navigation/index.js +4 -4
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/package.json +4 -4
- package/dist/cdn/G4HKVJ53.js +0 -2
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import c from"./55FL7WQV.js";import b from"./A4AA5T6M.js";import{a as
|
|
2
|
+
import c from"./55FL7WQV.js";import b from"./A4AA5T6M.js";import{a as Pl,c as Ml,e as Ol,f as Rl,g as $l}from"./UZCHLKLO.js";import a from"./F3ODJVJC.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import{a as Vn,b as ol,d as Ro}from"./2GBRZSEC.js";import{a as sl}from"./W3UBNVKL.js";import"./QZD2UBOW.js";import"./JVGCIDQW.js";import{K as Kn,L as Gn,M as rl,S as nl,h as Yi,j as Ae,n as Xi,w as el,z as tl}from"./6BUBZ7WC.js";import{$ as dl,Aa as Al,Ba as Go,Ca as Vo,Da as Il,Db as Wo,Ea as hr,Eb as Ho,Fa as gr,Fb as ce,Ga as v,Ha as $,Ia as ma,J as il,Ja as fa,K as Ie,L as ll,M as zo,N as aa,O as ia,P as Lo,Q as Wn,R as q,S as la,T as D,Ta as C,U as ot,V as st,W as jo,X as ul,Y as cl,Z as ua,_ as Do,a as ue,aa as pl,b as U,ba as Hn,ca as Fo,da as ml,ea as fl,fa as hl,g as al,ga as Uo,ha as gl,ia as kt,j as qe,ja as ca,k as St,ka as qo,la as N,ma as A,mb as vl,na as Ct,oa as at,pa as yl,qa as Bo,ra as _l,s as $o,sa as wl,ta as Ko,ua as da,va as fr,wa as pa,xa as bl,y as No,ya as xl,zb as Jn}from"./PGCNY5GO.js";import"./UZLQALHY.js";export default $arcgis.t(([wV,xV,Ad,Id,Ag,Ig,Ng,kV,EV,U4,rx,jd,dr,Dd,Si,Gd,,Dg,{addressToLocations:Fg},Ug,qg,Vd,{createRenderer:Bg},{getSchemesByTag:Kg,getSchemes:Gg},{getBackgroundColorTheme:Fd},{createAgeRenderer:Vg,createContinuousRenderer:Wg},{getSchemesByTag:zi},{createContinuousRenderer:Hg},{createRenderer:Jg},{getSchemesByTag:Zg},{createRenderer:Qg},{getSchemesByTag:Yg},{createRenderer:Xg},{getSchemesByTag:ey},{createRenderer:ty},{getSchemesByTag:ry},{createAgeRenderer:ny,createContinuousRenderer:oy},{createRenderer:sy},{getSchemesByTag:ay},iy,Wd,Hd,{formatDateOnly:ly,convertDateFormatToIntlOptions:Us,formatTimeOnly:uy,formatDate:Ud},cy,dy,py,my,fy,Jd,,{fetchKnowledgeGraph:qd,executeQueryStreaming:hy,executeSearchStreaming:gy},yy,{getBindParametersFromCypherQuery:_y},,,,,,,,,,,,,,,,,,,,,,,,,UH,BH,,,,,,,,,,,,,nx,up,ox,,{a:Cl,b:El},{a:Tl,b:Sl,c:kl}])=>{var it=(t,e)=>e,ha=(t,e)=>({...t,...e}),ga=(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(`
|
|
3
|
+
|
|
4
|
+
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
5
|
+
|
|
6
|
+
${r}`},ya=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Et=()=>({agentExecutionContext:C({reducer:ha,default:ya}),outputMessage:C({reducer:ga,default:()=>""}),summary:C({reducer:it,default:()=>""}),status:C({reducer:it})}),Jo=()=>({...Et(),sharedStatePatch:C({reducer:it})});var c=v;async function _a(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
7
|
|
|
4
8
|
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
5
9
|
|
|
6
10
|
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
7
11
|
|`,`
|
|
8
12
|
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
9
|
-
`].join(" "));let n=await
|
|
13
|
+
`].join(" "));let n=await pl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var H=async(t,e)=>{await _a("trace_message",t,e)},fe=async(t,e)=>{await _a("graph_ux_suggestion",t,e)};var Wp={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"}},QI=Object.keys(Wp);var xa=Symbol.for("langgraph-zod");xa in globalThis||(globalThis[xa]=new WeakSet);function Ll(t){let e=globalThis[xa];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{Ll(A.ZodType.prototype),Ll(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 jl=class extends fl{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)}},Qp=new jl(Wo);var mm=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),fm=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),hm=["approve","edit","reject"],gm=A.enum(hm),ym=A.object({allowedDecisions:A.array(gm),description:A.union([A.string(),fm]).optional(),argsSchema:A.record(A.any()).optional(),when:mm.optional()}),ak=A.object({interruptOn:A.record(A.union([A.boolean(),ym])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var bm=`<role>
|
|
10
14
|
Context Extraction Assistant
|
|
11
15
|
</role>
|
|
12
16
|
|
|
@@ -32,23 +36,23 @@ Respond ONLY with the extracted context. Do not include any additional informati
|
|
|
32
36
|
<messages>
|
|
33
37
|
Messages to summarize:
|
|
34
38
|
{messages}
|
|
35
|
-
</messages>`;var
|
|
39
|
+
</messages>`;var xm=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),ka=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"}),Wl=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"}),vk=A.object({model:A.custom(),trigger:A.union([ka,A.array(ka)]).optional(),keep:Wl.optional(),tokenCounter:xm.optional(),summaryPrompt:A.string().default(bm),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var Nk=A.object({model:A.string().or(A.instanceof(_l)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var qk=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var Wk=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Am=["continue","error","end"],Im="continue";var vm=A.enum(Am).default(Im);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:vm});var oC=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Tm=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Sm=A.object({content:A.string().describe("Content of the todo item"),status:Tm}),pC=A.object({todos:A.array(Sm).default([])});var yC=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),_C=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var Zo=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 OC=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(Zo);var FC=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(Zo);var tE=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var sE=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function Zn(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
36
40
|
|
|
37
41
|
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 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
|
-
`):[]}};
|
|
40
|
-
`,"\r"]);
|
|
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]=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:
|
|
42
|
+
`,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 Ca=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Ca=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 Qn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Yn=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 ut({message:n,cause:Yn(r)});let s=r?.error;return e===400?new _r(e,s,n,o):e===401?new wr(e,s,n,o):e===403?new br(e,s,n,o):e===404?new xr(e,s,n,o):e===409?new Ar(e,s,n,o):e===422?new Ir(e,s,n,o):e===429?new vr(e,s,n,o):e>=500?new Tr(e,s,n,o):new t(e,s,n,o)}},V=class extends G{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ut=class extends G{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Re=class extends ut{constructor({message:e}={}){super({message:e??"Request timed out."})}},_r=class extends G{},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 k{constructor(){super("Could not parse response content as the length limit was reached")}},kr=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},$e=class extends Error{constructor(e){super(e)}},Mt=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}},Xn=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var zm=/^[a-z][a-z0-9+.-]*:/i,Hl=t=>zm.test(t),de=t=>(de=Array.isArray,de(t)),Ea=de;function Qo(t){return typeof t!="object"?{}:t??{}}function Pa(t){if(!t)return!0;for(let e in t)return!1;return!0}function Jl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function eo(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Zl=(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 Ql=t=>{try{return JSON.parse(t)}catch{return}};var Ne=t=>new Promise(e=>setTimeout(e,t));var ct="6.45.0";var tu=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Lm(){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 jm=()=>{let t=Lm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":Xl(Deno.build.os),"X-Stainless-Arch":Yl(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":ct,"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":ct,"X-Stainless-OS":Xl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Dm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"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":ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Dm(){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 Yl=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Xl=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"),eu,ru=()=>eu??(eu=jm());function Yo(){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 Ma(...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 Xo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ma({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Oa(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 Ra(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 ou=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var $a="RFC3986",Na=t=>String(t),za={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Na},su="RFC1738";var es=(t,e)=>(es=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),es(t,e)),ze=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var La=1024,au=(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+=La){let u=s.length>=La?s.slice(i,i+La):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===su&&(m===40||m===41)){l[l.length]=u.charAt(d);continue}if(m<128){l[l.length]=ze[m];continue}if(m<2048){l[l.length]=ze[192|m>>6]+ze[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=ze[224|m>>12]+ze[128|m>>6&63]+ze[128|m&63];continue}d+=1,m=65536+((m&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=ze[240|m>>18]+ze[128|m>>12&63]+ze[128|m>>6&63]+ze[128|m&63]}a+=l.join("")}return a};function iu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ja(t,e){if(de(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var uu={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},cu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},lu,X={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:au,encodeValuesOnly:!1,format:$a,formatter:Na,indices:!1,serializeDate(t){return(lu??(lu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Um(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Da={};function du(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(Da))!==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(Da)>"u"&&(M=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&de(x)&&(x=ja(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(Um(x)||iu(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"&&de(x))b&&u&&(x=ja(x,u)),K=[{value:x.length>0?x.join(",")||null:void 0}];else if(de(l))K=l;else{let Z=Object.keys(x);K=d?Z.sort(d):Z}let W=i?String(e).replace(/\./g,"%2E"):String(e),le=n&&de(x)&&x.length===1?W+"[]":W;if(o&&de(x)&&x.length===0)return le+"[]";for(let Z=0;Z<K.length;++Z){let Y=K[Z],Zi=typeof Y=="object"&&typeof Y.value<"u"?Y.value:x[Y];if(a&&Zi===null)continue;let sa=m&&i?Y.replace(/\./g,"%2E"):Y,Gp=de(x)?typeof r=="function"?r(le,sa):le:le+(m?"."+sa:"["+sa+"]");h.set(t,M);let Qi=new WeakMap;Qi.set(Da,h),cu(B,du(Zi,Gp,r,n,o,s,a,i,r==="comma"&&b&&de(x)?null:u,l,d,m,f,I,w,b,y,Qi))}return B}function qm(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=$a;if(typeof t.format<"u"){if(!es(za,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=za[r],o=X.filter;(typeof t.filter=="function"||de(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in uu?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 pu(t,e={}){let r=t,n=qm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):de(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=uu[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||cu(a,du(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 mu(t){return pu(t,{arrayFormat:"brackets"})}function gu(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 fu;function Cr(t){let e;return(fu??(e=new globalThis.TextEncoder,fu=e.encode.bind(e)))(t)}var hu;function Fa(t){let e;return(hu??(e=new globalThis.TextDecoder,hu=e.decode.bind(e)))(t)}var ge,ye,Ot=class{constructor(){ge.set(this,void 0),ye.set(this,void 0),E(this,ge,new Uint8Array,"f"),E(this,ye,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Cr(e):e;E(this,ge,gu([_(this,ge,"f"),r]),"f");let n=[],o;for(;(o=Km(_(this,ge,"f"),_(this,ye,"f")))!=null;){if(o.carriage&&_(this,ye,"f")==null){E(this,ye,o.index,"f");continue}if(_(this,ye,"f")!=null&&(o.index!==_(this,ye,"f")+1||o.carriage)){n.push(Fa(_(this,ge,"f").subarray(0,_(this,ye,"f")-1))),E(this,ge,_(this,ge,"f").subarray(_(this,ye,"f")),"f"),E(this,ye,null,"f");continue}let s=_(this,ye,"f")!==null?o.preceding-1:o.preceding,a=Fa(_(this,ge,"f").subarray(0,s));n.push(a),E(this,ge,_(this,ge,"f").subarray(o.index),"f"),E(this,ye,null,"f")}return n}flush(){return _(this,ge,"f").length?this.decode(`
|
|
43
|
+
`):[]}};ge=new WeakMap,ye=new WeakMap;Ot.NEWLINE_CHARS=new Set([`
|
|
44
|
+
`,"\r"]);Ot.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Km(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 yu(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 rs={off:0,error:200,warn:300,info:400,debug:500},Ua=(t,e,r)=>{if(t){if(Jl(rs,t))return t;J(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(rs))}`)}};function to(){}function ts(t,e,r){return!e||rs[t]>rs[r]?to:e[t].bind(e)}var Gm={error:to,warn:to,info:to,debug:to},_u=new WeakMap;function J(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Gm;let n=_u.get(e);if(n&&n[0]===r)return n[1];let o={error:ts("error",e,r),warn:ts("warn",e,r),info:ts("info",e,r),debug:ts("debug",e,r)};return _u.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 ro,Le=class t{constructor(e,r,n){this.iterator=e,ro.set(this,void 0),this.controller=r,E(this,ro,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 Vm(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(Qn(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 Ot,u=Oa(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(Qn(u))return;throw u}finally{i||r.abort()}}return new t(a,r,n)}[(ro=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,ro,"f")),new t(()=>o(r),this.controller,_(this,ro,"f"))]}toReadableStream(){let e=this,r;return Ma({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=Cr(JSON.stringify(o)+`
|
|
45
|
+
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Vm(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 qa,n=new Ot,o=Oa(t.body);for await(let s of Wm(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*Wm(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"?Cr(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=yu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var qa=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
46
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Hm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Hm(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ns(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):Le.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 Ba(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 Ba(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 no,Rt=class t extends Promise{constructor(e,r,n=ns){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,no.set(this,void 0),E(this,no,e,"f")}_thenUnwrap(e){return new t(_(this,no,"f"),this.responsePromise,async(r,n)=>Ba(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,no,"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)}};no=new WeakMap;var os,Er=class{constructor(e,r,n,o){os.set(this,void 0),E(this,os,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,os,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(os=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},oo=class extends Rt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await ns(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends Er{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 Er{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:{...Qo(this.options.query),after:r}}:null}},L=class extends Er{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:{...Qo(this.options.query),after:e}}:null}},Q=class extends Er{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:{...Qo(this.options.query),after:e}}:null}};var Zm={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Qm="urn:ietf:params:oauth:grant-type:token-exchange",ss=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Yo()}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:Qm,subject_token:e,subject_token_type:Zm[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 Mt(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 Va=()=>{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 Pr(t,e,r){return Va(),new File(t,e??"unknown_file",r)}function so(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 as=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",dt=async(t,e)=>Ka(t.body)?{...t,body:await bu(t.body,e)}:t,me=async(t,e)=>({...t,body:await bu(t.body,e)}),wu=new WeakMap;function Ym(t){let e=typeof t=="function"?t:t.fetch,r=wu.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 wu.set(e,n),n}var bu=async(t,e)=>{if(!await Ym(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])=>Ga(r,n,o))),r},xu=t=>t instanceof Blob&&"name"in t,Xm=t=>typeof t=="object"&&t!==null&&(t instanceof Response||as(t)||xu(t)),Ka=t=>{if(Xm(t))return!0;if(Array.isArray(t))return t.some(Ka);if(t&&typeof t=="object"){for(let e in t)if(Ka(t[e]))return!0}return!1},Ga=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,Pr([await r.blob()],so(r)));else if(as(r))t.append(e,Pr([await new Response(Xo(r)).blob()],so(r)));else if(xu(r))t.append(e,r,so(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Ga(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Ga(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 Au=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",ef=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Au(t),tf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function ao(t,e,r){if(Va(),t=await t,ef(t))return t instanceof File?t:Pr([await t.arrayBuffer()],t.name);if(tf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Pr(await Wa(o),e,r)}let n=await Wa(t);if(e||(e=so(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Pr(n,e,r)}async function Wa(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Au(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(as(t))for await(let r of t)e.push(...await Wa(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${rf(t)}`)}return e}function rf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function vu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Iu=Object.freeze(Object.create(null)),of=(t=vu)=>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??Iu)??Iu)?.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
47
|
${s.map(f=>f.error).join(`
|
|
44
48
|
`)}
|
|
45
49
|
${a}
|
|
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()},
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${
|
|
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.
|
|
50
|
+
${m}`)}return a},p=of(vu);var $t=class extends g{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function io(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Su(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function lo(t){return t?.$brand==="auto-parseable-response-format"}function Nt(t){return t?.$brand==="auto-parseable-tool"}function ku(t,e){return!e||!Ha(e)?{...t,choices:t.choices.map(r=>(Eu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:uo(t,e)}function uo(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Sr;if(n.finish_reason==="content_filter")throw new kr;return Eu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>lf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?af(e,n.message.content):null}}});return{...t,choices:r}}function af(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 lf(t,e){let r=t.tools?.find(n=>io(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Nt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Cu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>io(n)&&n.function?.name===e.function.name);return io(r)&&(Nt(r)||r?.function.strict||!1)}function Ha(t){return lo(t.response_format)?!0:t.tools?.some(e=>Nt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Eu(t){for(let e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Pu(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 Mr=t=>t?.role==="assistant",Ja=t=>t?.role==="tool";var is,ls,us,co,po,cs,mo,Ke,ds,fo,ps,ms,Or,Mu,Ou,pt=class{constructor(){is.add(this),this.controller=new AbortController,ls.set(this,void 0),us.set(this,()=>{}),co.set(this,()=>{}),po.set(this,void 0),cs.set(this,()=>{}),mo.set(this,()=>{}),Ke.set(this,{}),ds.set(this,[]),fo.set(this,!1),ps.set(this,!1),ms.set(this,!1),Or.set(this,!1),E(this,ls,new Promise((e,r)=>{E(this,us,e,"f"),E(this,co,r,"f")}),"f"),E(this,po,new Promise((e,r)=>{E(this,cs,e,"f"),E(this,mo,r,"f")}),"f"),_(this,ls,"f").catch(()=>{}),_(this,po,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,is,"m",Ou).bind(this))},0)}_connected(){this.ended||(_(this,us,"f").call(this),this._emit("connect"))}get ended(){return _(this,fo,"f")}get errored(){return _(this,ps,"f")}get aborted(){return _(this,ms,"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,ds,"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,Or,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){E(this,Or,!0,"f"),await _(this,po,"f")}_emit(e,...r){if(_(this,fo,"f"))return;e==="end"&&(_(this,is,"m",Mu).call(this),E(this,fo,!0,"f"),_(this,cs,"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,Or,"f")&&!n?.length&&Promise.reject(o),_(this,co,"f").call(this,o),_(this,mo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Or,"f")&&!n?.length&&Promise.reject(o),_(this,co,"f").call(this,o),_(this,mo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};ls=new WeakMap,us=new WeakMap,co=new WeakMap,po=new WeakMap,cs=new WeakMap,mo=new WeakMap,Ke=new WeakMap,ds=new WeakMap,fo=new WeakMap,ps=new WeakMap,ms=new WeakMap,Or=new WeakMap,is=new WeakSet,Mu=function(){for(let{signal:e,listener:r}of _(this,ds,"f").splice(0))e.removeEventListener("abort",r)},Ou=function(e){if(E(this,ps,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new V),e instanceof V)return E(this,ms,!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 Ru(t){return typeof t.parse=="function"}var he,Za,fs,Qa,Ya,Xa,$u,Nu,uf=10,Rr=class extends pt{constructor(){super(...arguments),he.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),Ja(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Mr(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,he,"m",Za).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",fs).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",Qa).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",Ya).call(this)}async totalUsage(){return await this.done(),_(this,he,"m",Xa).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,he,"m",fs).call(this);r&&this._emit("finalMessage",r);let n=_(this,he,"m",Za).call(this);n&&this._emit("finalContent",n);let o=_(this,he,"m",Qa).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,he,"m",Ya).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",_(this,he,"m",Xa).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),_(this,he,"m",$u).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(uo(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=uf,afterCompletion:m}=o||{},f=r.tools.map(y=>{if(Nt(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(W=>JSON.stringify(W)).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(Ru(M)){let K;try{K=await M.parse(S)}catch(W){let le=W instanceof Error?W.message:String(W);return{message:{role:s,tool_call_id:h,content:le},functionCalled:!1}}F=await M.function(K,n)}else F=await M.function(S,n);let B=_(this,he,"m",Nu).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)}}};he=new WeakSet,Za=function(){return _(this,he,"m",fs).call(this).content??null},fs=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Mr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},Qa=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Mr(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}}},Ya=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Ja(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}},Xa=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},$u=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.")},Nu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ho=class t extends Rr{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),Mr(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},ei=class extends Error{},ti=class extends Error{};function cf(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 df(t.trim(),e)}var df=(t,e)=>{let r=t.length,n=0,o=f=>{throw new ei(`${f} at position ${n}`)},s=f=>{throw new ti(`${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&&`
|
|
51
|
+
\r `.includes(t[n]);)n++};return a()},ri=t=>cf(t,ne.ALL^ne.NUM);var ee,Ge,$r,mt,ni,hs,oi,si,ai,gs,ii,zu,zt=class t extends Rr{constructor(e){super(),ee.add(this),Ge.set(this,void 0),$r.set(this,void 0),mt.set(this,void 0),E(this,Ge,e,"f"),E(this,$r,[],"f")}get currentChatCompletionSnapshot(){return _(this,mt,"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",ni).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",oi).call(this,s);if(o.controller.signal?.aborted)throw new V;return this._addChatCompletion(_(this,ee,"m",gs).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,ee,"m",ni).call(this),this._connected();let n=Le.fromReadableStream(e,this.controller),o;for await(let s of n)o&&o!==s.id&&this._addChatCompletion(_(this,ee,"m",gs).call(this)),_(this,ee,"m",oi).call(this,s),o=s.id;if(n.controller.signal?.aborted)throw new V;return this._addChatCompletion(_(this,ee,"m",gs).call(this))}[(Ge=new WeakMap,$r=new WeakMap,mt=new WeakMap,ee=new WeakSet,ni=function(){this.ended||E(this,mt,void 0,"f")},hs=function(r){let n=_(this,$r,"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,$r,"f")[r.index]=n,n)},oi=function(r){if(this.ended)return;let n=_(this,ee,"m",zu).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",hs).call(this,s);s.finish_reason&&(_(this,ee,"m",ai).call(this,s),a.current_tool_call_index!=null&&_(this,ee,"m",si).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",ai).call(this,s),a.current_tool_call_index!=null&&_(this,ee,"m",si).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))}}},si=function(r,n){if(_(this,ee,"m",hs).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=>io(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:Nt(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},ai=function(r){let n=_(this,ee,"m",hs).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,ee,"m",ii).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}))},gs=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,mt,"f");if(!r)throw new k("request ended without sending any chunks");return E(this,mt,void 0,"f"),E(this,$r,[],"f"),pf(r,_(this,Ge,"f"))},ii=function(){let r=_(this,Ge,"f")?.response_format;return lo(r)?r:null},zu=function(r){var n,o,s,a;let i=_(this,mt,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=E(this,mt,{...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,...W}=I;Object.assign(b.logprobs,W),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")&&Ha(_(this,Ge,"f")))){if(m==="length")throw new Sr;if(m==="content_filter")throw new kr}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",ii).call(this)&&(b.message.parsed=b.message.content.trim()?ri(b.message.content):null)),M){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:B,id:K,type:W,function:le,...Z}of M){let Y=(a=b.message.tool_calls)[B]??(a[B]={});Object.assign(Y,Z),K&&(Y.id=K),W&&(Y.type=W),le&&(Y.function??(Y.function={name:le.name??"",arguments:""})),le?.name&&(Y.function.name=le.name),le?.arguments&&(Y.function.arguments+=le.arguments,Cu(_(this,Ge,"f"),Y)&&(Y.function.parsed_arguments=ri(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 Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function pf(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,...W}=S,{arguments:le,name:Z,...Y}=F||{};if(K==null)throw new k(`missing choices[${m}].tool_calls[${M}].id
|
|
52
|
+
${ys(t)}`);if(B==null)throw new k(`missing choices[${m}].tool_calls[${M}].type
|
|
53
|
+
${ys(t)}`);if(Z==null)throw new k(`missing choices[${m}].tool_calls[${M}].function.name
|
|
54
|
+
${ys(t)}`);if(le==null)throw new k(`missing choices[${m}].tool_calls[${M}].function.arguments
|
|
55
|
+
${ys(t)}`);return{...W,id:K,type:B,function:{...Y,name:Z,arguments:le}}})}}:{...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 ku(u,e)}function ys(t){return JSON.stringify(t)}var go=class t extends zt{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 Ve=class extends g{constructor(){super(...arguments),this.messages=new $t(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 Pu(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>uo(n,e))}runTools(e,r){return e.stream?go.runTools(this._client,e,r):ho.runTools(this._client,e,r)}stream(e,r){return zt.createChatCompletion(this._client,e,r)}};Ve.Messages=$t;var ft=class extends g{constructor(){super(...arguments),this.completions=new Ve(this._client)}};ft.Completions=Ve;var Nr=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 zr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",L,{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",L,{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",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var jr=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 Dr=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",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Fr=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 Ur=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",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qr=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 Br=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 Kr=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 ht=class extends g{constructor(){super(...arguments),this.users=new Kr(this._client),this.roles=new Br(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}})}};ht.Users=Kr;ht.Roles=Br;var Gr=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`,L,{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`,L,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Wr=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 Hr=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 Jr=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 Zr=class extends g{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,L,{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 Qr=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 Yr=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`,L,{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 Xr=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`,L,{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 en=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 Lt=class extends g{constructor(){super(...arguments),this.roles=new en(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}})}};Lt.Roles=en;var tn=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 tn(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`,L,{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=tn;var se=class extends g{constructor(){super(...arguments),this.users=new jt(this._client),this.serviceAccounts=new Yr(this._client),this.apiKeys=new Gr(this._client),this.rateLimits=new Zr(this._client),this.modelPermissions=new Jr(this._client),this.hostedToolPermissions=new Hr(this._client),this.groups=new Lt(this._client),this.roles=new Qr(this._client),this.dataRetention=new Wr(this._client),this.spendAlerts=new Xr(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",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};se.Users=jt;se.ServiceAccounts=Yr;se.APIKeys=Gr;se.RateLimits=Zr;se.ModelPermissions=Jr;se.HostedToolPermissions=Hr;se.Groups=Lt;se.Roles=Qr;se.DataRetention=Wr;se.SpendAlerts=Xr;se.Certificates=Vr;var rn=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 Dt=class extends g{constructor(){super(...arguments),this.roles=new rn(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",L,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Dt.Roles=rn;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new zr(this._client),this.adminAPIKeys=new Nr(this._client),this.usage=new qr(this._client),this.invites=new Dr(this._client),this.users=new Dt(this._client),this.groups=new ht(this._client),this.roles=new Fr(this._client),this.dataRetention=new jr(this._client),this.spendAlerts=new Ur(this._client),this.certificates=new Lr(this._client),this.projects=new se(this._client)}};ae.AuditLogs=zr;ae.AdminAPIKeys=Nr;ae.Usage=qr;ae.Invites=Dr;ae.Users=Dt;ae.Groups=ht;ae.Roles=Fr;ae.DataRetention=jr;ae.SpendAlerts=Ur;ae.Certificates=Lr;ae.Projects=se;var gt=class extends g{constructor(){super(...arguments),this.organization=new ae(this._client)}};gt.Organization=ae;var Lu=Symbol("brand.privateNullableHeaders");function*qf(t){if(!t)return;if(Lu 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():Ea(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=Ea(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 qf(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{[Lu]:!0,values:e,nulls:r}};var nn=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 on=class extends g{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var sn=class extends g{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var je=class extends g{constructor(){super(...arguments),this.transcriptions=new on(this._client),this.translations=new sn(this._client),this.speech=new nn(this._client)}};je.Transcriptions=on;je.Translations=sn;je.Speech=nn;var Ft=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 an=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 ln=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 un=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 yt=class extends g{constructor(){super(...arguments),this.sessions=new ln(this._client),this.transcriptionSessions=new un(this._client)}};yt.Sessions=ln;yt.TranscriptionSessions=un;var cn=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 dn=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",L,{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`,L,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var _t=class extends g{constructor(){super(...arguments),this.sessions=new cn(this._client),this.threads=new dn(this._client)}};_t.Sessions=cn;_t.Threads=dn;var pn=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 mn=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 ju=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 ve=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var ie,qt,li,De,_s,Te,Bt,fn,Ut,xs,_e,ws,bs,wo,yo,_o,Du,Fu,Uu,qu,Bu,Ku,Gu,We=class extends pt{constructor(){super(...arguments),ie.add(this),li.set(this,[]),De.set(this,{}),_s.set(this,{}),Te.set(this,void 0),Bt.set(this,void 0),fn.set(this,void 0),Ut.set(this,void 0),xs.set(this,void 0),_e.set(this,void 0),ws.set(this,void 0),bs.set(this,void 0),wo.set(this,void 0)}[(li=new WeakMap,De=new WeakMap,_s=new WeakMap,Te=new WeakMap,Bt=new WeakMap,fn=new WeakMap,Ut=new WeakMap,xs=new WeakMap,_e=new WeakMap,ws=new WeakMap,bs=new WeakMap,wo=new WeakMap,ie=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 qt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=Le.fromReadableStream(e,this.controller);for await(let o of n)_(this,ie,"m",yo).call(this,o);if(n.controller.signal?.aborted)throw new V;return this._addRun(_(this,ie,"m",_o).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new qt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){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,ie,"m",yo).call(this,i);if(a.controller.signal?.aborted)throw new V;return this._addRun(_(this,ie,"m",_o).call(this))}static createThreadAssistantStream(e,r,n){let o=new qt;return o._run(()=>o._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new qt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,ws,"f")}currentRun(){return _(this,bs,"f")}currentMessageSnapshot(){return _(this,Te,"f")}currentRunStepSnapshot(){return _(this,wo,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,De,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,_s,"f"))}async finalRun(){if(await this.done(),!_(this,Bt,"f"))throw Error("Final run was not received.");return _(this,Bt,"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,ie,"m",yo).call(this,a);if(s.controller.signal?.aborted)throw new V;return this._addRun(_(this,ie,"m",_o).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,ie,"m",yo).call(this,i);if(a.controller.signal?.aborted)throw new V;return this._addRun(_(this,ie,"m",_o).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(eo(s)&&eo(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(!eo(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)}};qt=We,yo=function(e){if(!this.ended)switch(E(this,ws,e,"f"),_(this,ie,"m",Uu).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":_(this,ie,"m",Gu).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":_(this,ie,"m",Fu).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":_(this,ie,"m",Du).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},_o=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!_(this,Bt,"f"))throw Error("Final run has not been received");return _(this,Bt,"f")},Du=function(e){let[r,n]=_(this,ie,"m",Bu).call(this,e,_(this,Te,"f"));E(this,Te,r,"f"),_(this,_s,"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,fn,"f")){if(_(this,Ut,"f"))switch(_(this,Ut,"f").type){case"text":this._emit("textDone",_(this,Ut,"f").text,_(this,Te,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Ut,"f").image_file,_(this,Te,"f"));break}E(this,fn,o.index,"f")}E(this,Ut,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,fn,"f")!==void 0){let o=e.data.content[_(this,fn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,Te,"f"));break;case"text":this._emit("textDone",o.text,_(this,Te,"f"));break}}_(this,Te,"f")&&this._emit("messageDone",e.data),E(this,Te,void 0,"f")}},Fu=function(e){let r=_(this,ie,"m",qu).call(this,e);switch(E(this,wo,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,xs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,_e,"f")&&this._emit("toolCallDone",_(this,_e,"f")),E(this,xs,s.index,"f"),E(this,_e,r.step_details.tool_calls[s.index],"f"),_(this,_e,"f")&&this._emit("toolCallCreated",_(this,_e,"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,wo,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,_e,"f")&&(this._emit("toolCallDone",_(this,_e,"f")),E(this,_e,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Uu=function(e){_(this,li,"f").push(e),this._emit("event",e)},qu=function(e){switch(e.event){case"thread.run.step.created":return _(this,De,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,De,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=qt.accumulateDelta(r,n.delta);_(this,De,"f")[e.data.id]=o}return _(this,De,"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,De,"f")[e.data.id]=e.data;break}if(_(this,De,"f")[e.data.id])return _(this,De,"f")[e.data.id];throw new Error("No snapshot available")},Bu=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,ie,"m",Ku).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")},Ku=function(e,r){return qt.accumulateDelta(r,e)},Gu=function(e){switch(E(this,bs,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,Bt,e.data,"f"),_(this,_e,"f")&&(this._emit("toolCallDone",_(this,_e,"f")),E(this,_e,void 0,"f"));break;case"thread.run.cancelling":break}};var Kt=class extends g{constructor(){super(...arguments),this.steps=new mn(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 We.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 Ne(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return We.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 We.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Kt.Steps=mn;var wt=class extends g{constructor(){super(...arguments),this.runs=new Kt(this._client),this.messages=new pn(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 We.createThreadAssistantStream(e,this._client.beta.threads,r)}};wt.Runs=Kt;wt.Messages=pn;var Se=class extends g{constructor(){super(...arguments),this.realtime=new yt(this._client),this.chatkit=new _t(this._client),this.assistants=new an(this._client),this.threads=new wt(this._client)}};Se.Realtime=yt;Se.ChatKit=_t;Se.Assistants=an;Se.Threads=wt;var Gt=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var hn=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 Vt=class extends g{constructor(){super(...arguments),this.content=new hn(this._client)}create(e,r,n){return this._client.post(p`/containers/${e}/files`,dt({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}})}};Vt.Content=hn;var bt=class extends g{constructor(){super(...arguments),this.files=new Vt(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}})}};bt.Files=Vt;var gn=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`,L,{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 xt=class extends g{constructor(){super(...arguments),this.items=new gn(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}})}};xt.Items=gn;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=ju(u)}),a)))}};var yn=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 Ht=class extends g{constructor(){super(...arguments),this.outputItems=new yn(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}})}};Ht.OutputItems=yn;var At=class extends g{constructor(){super(...arguments),this.runs=new Ht(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}})}};At.Runs=Ht;var Jt=class extends g{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(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 Ne(r),a=await this.retrieve(e),Date.now()-s>n)throw new Re({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var _n=class extends g{};var wn=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 Zt=class extends g{constructor(){super(...arguments),this.graders=new wn(this._client)}};Zt.Graders=wn;var bn=class extends g{create(e,r,n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,pe,{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`,L,{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 Qt=class extends g{constructor(){super(...arguments),this.permissions=new bn(this._client)}};Qt.Permissions=bn;var xn=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 Yt=class extends g{constructor(){super(...arguments),this.checkpoints=new xn(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}})}};Yt.Checkpoints=xn;var ke=class extends g{constructor(){super(...arguments),this.methods=new _n(this._client),this.jobs=new Yt(this._client),this.checkpoints=new Qt(this._client),this.alpha=new Zt(this._client)}};ke.Methods=_n;ke.Jobs=Yt;ke.Checkpoints=Qt;ke.Alpha=Zt;var An=class extends g{};var It=class extends g{constructor(){super(...arguments),this.graderModels=new An(this._client)}};It.GraderModels=An;var Xt=class extends g{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var er=class extends g{retrieve(e,r){return this._client.get(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var tr=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var In=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 vn=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 vn(this._client),this.calls=new In(this._client)}};He.ClientSecrets=vn;He.Calls=In;function Vu(t,e){if(!e||!wh(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 Wu(t,r)&&we(r),r}return ui(t,e)}function ui(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?Ah(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?_h(e,i.text):null}:i);return{...s,content:a}}return s}),o=Object.assign({},t,{output:n});return Wu(t,o)&&we(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 _h(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function wh(t){return!!lo(t.text?.format)}function bh(t){return t?.$brand==="auto-parseable-tool"}function xh(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Ah(t,e){let r=xh(t.tools??[],e.name);return{...e,...e,parsed_arguments:bh(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Wu(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function we(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 Ju(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 Hu(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&we(e);break}case"response.output_item.done":{z(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&we(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"&&we(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")be(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&we(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}`);be(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=be(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=be(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,we(e)}break}case"response.output_text.annotation.added":{let r=z(e,t.output_index);if(r.type==="message"){let n=be(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=be(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=be(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=be(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=be(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"&&(be(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=be(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=be(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=Hu(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:Ih(t)}return e}function Hu(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&we(e),e}function z(t,e){let r=t.output[e];if(!r)throw new k(`missing output at index ${e}`);return r}function be(t,e){let r=t[e];if(!r)throw new k(`missing content at index ${e}`);return r}function Ih(t){throw new k(`Unhandled response stream event: ${JSON.stringify(t)}`)}var bo,As,rr,Is,Zu,Qu,Yu,vs=class t extends pt{constructor(e){super(),bo.add(this),As.set(this,void 0),rr.set(this,void 0),Is.set(this,void 0),E(this,As,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,bo,"m",Zu).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,bo,"m",Qu).call(this,a,s);if(o.controller.signal?.aborted)throw new V;return _(this,bo,"m",Yu).call(this)}[(As=new WeakMap,rr=new WeakMap,Is=new WeakMap,bo=new WeakSet,Zu=function(){this.ended||E(this,rr,void 0,"f")},Qu=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=Ju(r,_(this,rr,"f"));switch(E(this,rr,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}},Yu=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=_(this,rr,"f");if(!r)throw new k("request ended without sending any events");E(this,rr,void 0,"f");let n=vh(r,_(this,As,"f"));return E(this,Is,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,Is,"f");if(!e)throw new k("stream ended without producing a ChatCompletion");return e}};function vh(t,e){return Vu(t,e)}var Tn=class extends g{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var Sn=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Fe=class extends g{constructor(){super(...arguments),this.inputItems=new Tn(this._client),this.inputTokens=new Sn(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"&&we(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"&&we(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=>ui(n,e))}stream(e,r){return vs.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}})}};Fe.InputItems=Tn;Fe.InputTokens=Sn;var kn=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 Cn=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 nr=class extends g{constructor(){super(...arguments),this.content=new Cn(this._client)}create(e,r={},n){return this._client.post(p`/skills/${e}/versions`,dt({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}})}};nr.Content=Cn;var Je=class extends g{constructor(){super(...arguments),this.content=new kn(this._client),this.versions=new nr(this._client)}create(e={},r){return this._client.post("/skills",dt({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=kn;Je.Versions=nr;var En=class extends g{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,me({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var vt=class extends g{constructor(){super(...arguments),this.parts=new En(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}})}};vt.Parts=En;var Xu=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 Pn=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 Ne(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 Xu(m),await this.createAndPoll(e,{file_ids:l})}};var Mn=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 Ne(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`,pe,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ze=class extends g{constructor(){super(...arguments),this.files=new Mn(this._client),this.fileBatches=new Pn(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`,pe,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};Ze.Files=Mn;Ze.FileBatches=Pn;var or=class extends g{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",L,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},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",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(p`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(p`/videos/${e}/remix`,dt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var On,ec,Ts,sr=class extends g{constructor(){super(...arguments),On.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,On,"m",ec).call(this,n);let s=T([r]).values,a=_(this,On,"m",Ts).call(this,s,"webhook-signature"),i=_(this,On,"m",Ts).call(this,s,"webhook-timestamp"),u=_(this,On,"m",Ts).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new $e("Invalid webhook timestamp format");let d=Math.floor(Date.now()/1e3);if(d-l>o)throw new $e("Webhook timestamp is too old");if(l>d+o)throw new $e("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 $e("The given webhook signature does not match the expected signature")}};On=new WeakSet,ec=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")},Ts=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 rc=Symbol.for("openai.node.providerDefinitions.v1"),nc=globalThis,oc=nc[rc],sc=oc??new WeakMap;oc||Object.defineProperty(nc,rc,{value:sc});function ac(t){let e=sc.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var ci,di,xo,ic,Rh="workload-identity-auth",P=class{constructor(e={}){ci.add(this),xo.set(this,void 0),this.completions=new Gt(this),this.chat=new ft(this),this.embeddings=new Wt(this),this.files=new Jt(this),this.images=new Xt(this),this.audio=new je(this),this.moderations=new tr(this),this.models=new er(this),this.fineTuning=new ke(this),this.graders=new It(this),this.vectorStores=new Ze(this),this.webhooks=new sr(this),this.beta=new Se(this),this.batches=new Ft(this),this.uploads=new vt(this),this.admin=new gt(this),this.responses=new Fe(this),this.realtime=new He(this),this.conversations=new xt(this),this.evals=new At(this),this.containers=new bt(this),this.skills=new Je(this),this.videos=new or(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:ve("OPENAI_BASE_URL"),apiKey:o=r?null:ve("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:ve("OPENAI_ADMIN_KEY")??null,organization:a=r?null:ve("OPENAI_ORG_ID")??null,project:i=r?null:ve("OPENAI_PROJECT_ID")??null,webhookSecret:u=ve("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...d}=e,m=r?ac(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&&tu())throw new k(`It looks like you're running in a browser-like environment.
|
|
52
56
|
|
|
53
57
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
54
58
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -57,27 +61,23 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
57
61
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
58
62
|
|
|
59
63
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
60
|
-
`);this.baseURL=f.baseURL,this.timeout=f.timeout??
|
|
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
|
-
`)}function
|
|
63
|
-
`)}function
|
|
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
|
|
64
|
+
`);this.baseURL=f.baseURL,this.timeout=f.timeout??di.DEFAULT_TIMEOUT,this.logger=f.logger??console;let I="warn";this.logLevel=I,this.logLevel=Ua(f.logLevel,"ClientOptions.logLevel",this)??Ua(ve("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??I,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??Yo(),E(this,xo,ou,"f");let w=r?void 0:ve("OPENAI_CUSTOM_HEADERS");if(w){let b={};for(let y of w.split(`
|
|
65
|
+
`)){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 ss(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 mu(e)}getUserAgent(){return`${this.constructor.name}/JS ${ct}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ca()}`}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,ci,"m",ic).call(this)&&n||this.baseURL,s=Hl(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!Pa(a)||!Pa(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 Rt(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 V;let f=o.__security??{bearerAuth:!0},I=new AbortController,w=await this.fetchWithAuth(i,a,u,I,f).catch(Yn),b=Date.now();if(w instanceof globalThis.Error){let x=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new V;let S=Qn(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 Mt||w instanceof Xn?w:S?new Re:new ut({message:$h(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 Ra(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 W=`retrying, ${r} attempts remaining`;return await Ra(w.body),J(this).info(`${h} - ${W}`),J(this).debug(`[${l}] response error (${W})`,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(W=>Yn(W).message),F=Ql(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 oo(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 ${Rh}`){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 Ne(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&&Zl("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))}:{},...ru(),"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,xo,"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:Xo(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,xo,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};di=P,xo=new WeakMap,ci=new WeakSet,ic=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=di;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=k;P.APIError=G;P.APIConnectionError=ut;P.APIConnectionTimeoutError=Re;P.APIUserAbortError=V;P.NotFoundError=xr;P.ConflictError=Ar;P.RateLimitError=vr;P.BadRequestError=_r;P.AuthenticationError=wr;P.InternalServerError=Tr;P.PermissionDeniedError=br;P.UnprocessableEntityError=Ir;P.InvalidWebhookSignatureError=$e;P.toFile=ao;P.Completions=Gt;P.Chat=ft;P.Embeddings=Wt;P.Files=Jt;P.Images=Xt;P.Audio=je;P.Moderations=tr;P.Models=er;P.FineTuning=ke;P.Graders=It;P.VectorStores=Ze;P.Webhooks=sr;P.Beta=Se;P.Batches=Ft;P.Uploads=vt;P.Admin=gt;P.Responses=Fe;P.Realtime=He;P.Conversations=xt;P.Evals=At;P.Containers=bt;P.Skills=Je;P.Videos=or;function $h(t){if(Nh(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 Nh(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 zh(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function xe(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Re.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===V.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):zh(t)?e=ll.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Zn(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Zn(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Zn(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Zn(t,"MODEL_NOT_FOUND"):e=t,e}var Ce=t=>t();function Qe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Lh(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 Ss(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var jh="LC_AUTOGENERATED";function ar(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'."),jh)}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(!jo.isInstance(t))throw new Error("Invalid generic chat message");return Lh(t);default:throw new Error(`Unknown message type: ${e}`)}}function lc(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 mi(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function uc(t){let e=Ce(()=>{if(mi(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&mi(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 cc(){let t=il();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=uc(t),o=cc(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function dc(t,e){let r;return gr(t)?r=fa(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Dh(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function pc(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(mc(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
66
|
+
`)}function mc(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}: ${ks(o,e)},`):r.push(`${n}?: ${ks(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
|
|
67
|
+
`)}function ks(t,e){if(Dh(t))return t.anyOf.map(r=>ks(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["{",mc(t,e+2),"}"].join(`
|
|
68
|
+
`);case"array":return t.items?`${ks(t.items,e)}[]`:"any[]";default:return""}}function Cs(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 Rn(t){return"type"in t&&t.type!=="function"}function fc(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 hc(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function ir(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 Es(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function gc(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 yc(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 _c(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function wc(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 bc(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 xc(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 Ic=Symbol("Let zodToJsonSchema decide on which parser to use"),Ac={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"},vc=t=>typeof t=="string"?{...Ac,basePath:["#"],definitions:{},name:t}:{...Ac,basePath:["#"],definitions:{},...t};var Ao=t=>"_def"in t?t._def:t;function Tc(t){if(!t)return!0;for(let e in t)return!1;return!0}var Sc=t=>{let e=vc(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])=>[Ao(o),{def:Ao(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function fi(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function j(t,e,r,n,o){t[e]=r,fi(t,e,n,o)}function kc(){return{}}function Cc(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&&j(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&j(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(j(r,"minItems",t.exactLength.value,t.exactLength.message,e),j(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Ec(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?j(r,"minimum",n.value,n.message,e):j(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?j(r,"maximum",n.value,n.message,e):j(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",n.value,n.message,e));break;case"multipleOf":j(r,"multipleOf",n.value,n.message,e);break}return r}function Pc(){return{type:"boolean"}}function Mc(t,e,r){return O(t.type._def,e,r)}var Oc=(t,e,r)=>O(t.innerType._def,e,r);function hi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>hi(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 Fh(t,e)}}var Fh=(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":j(r,"minimum",n.value,n.message,e);break;case"max":j(r,"maximum",n.value,n.message,e);break}return r};function Rc(t,e,r){return{...O(t.innerType._def,e,r),default:t.defaultValue()}}function $c(t,e,r){return e.effectStrategy==="input"?O(t.schema._def,e,r):{}}function Nc(t){return{type:"string",enum:[...t.values]}}var Uh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function zc(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(Uh(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 Lc(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var gi,lr={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:()=>(gi===void 0&&(gi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gi),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 Ps(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?qh(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":j(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":Ee(r,"email",o.message,e);break;case"format:idn-email":Ee(r,"idn-email",o.message,e);break;case"pattern:zod":Pe(r,lr.email,o.message,e);break}break;case"url":Ee(r,"uri",o.message,e);break;case"uuid":Ee(r,"uuid",o.message,e);break;case"regex":Pe(r,o.regex,o.message,e);break;case"cuid":Pe(r,lr.cuid,o.message,e);break;case"cuid2":Pe(r,lr.cuid2,o.message,e);break;case"startsWith":Pe(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":Pe(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Ee(r,"date-time",o.message,e);break;case"date":Ee(r,"date",o.message,e);break;case"time":Ee(r,"time",o.message,e);break;case"duration":Ee(r,"duration",o.message,e);break;case"length":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{Pe(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ee(r,"ipv4",o.message,e),o.version!=="v4"&&Ee(r,"ipv6",o.message,e);break}case"emoji":Pe(r,lr.emoji,o.message,e);break;case"ulid":{Pe(r,lr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ee(r,"binary",o.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Pe(r,lr.base64,o.message,e);break}}break}case"nanoid":Pe(r,lr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var qh=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ee=(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}}})):j(t,"format",e,r,n)},Pe=(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:jc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):j(t,"pattern",jc(e,n),r,n)},jc=(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
69
|
]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
|
|
66
70
|
]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
|
|
67
71
|
`:`[${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 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
|
-
|
|
70
|
-
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
71
|
-
|
|
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}
|
|
72
|
+
]`;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 Ms(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(Ps(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 Dc(t,e){if(e.mapStrategy==="record")return Ms(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 Fc(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 Uc(){return{not:{}}}function qc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Io={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Kc(t,e){if(e.target==="openApi3")return Bc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Io&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Io[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 Bc(t,e)}var Bc=(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 Gc(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:Io[t.innerType._def.typeName],nullable:!0}:{type:[Io[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 Vc(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",fi(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?j(r,"minimum",n.value,n.message,e):j(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?j(r,"maximum",n.value,n.message,e):j(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",n.value,n.message,e));break;case"multipleOf":j(r,"multipleOf",n.value,n.message,e);break}return r}function Bh(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 Wc(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:Bh(t,e)};return r.required.length||delete r.required,r}var Hc=(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 Jc=(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 Zc(t,e,r){return O(t.type._def,e,r)}function Qc(t,e){let n={type:"array",uniqueItems:!0,items:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&j(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&j(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Yc(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 Xc(){return{not:{}}}function ed(){return{}}var td=(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!==Ic)return s}if(n&&!r){let s=Kh(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=Wh(t,t.typeName,e,r);return s&&Hh(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var Kh=(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:Gh(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:Vh(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}},rd="_x_",Gh=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(rd))return t;let e=rd;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Vh=(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("/")},Wh=(t,e,r,n)=>{switch(e){case N.ZodString:return Ps(t,r);case N.ZodNumber:return Vc(t,r);case N.ZodObject:return Wc(t,r);case N.ZodBigInt:return Ec(t,r);case N.ZodBoolean:return Pc();case N.ZodDate:return hi(t,r);case N.ZodUndefined:return Xc();case N.ZodNull:return qc(r);case N.ZodArray:return Cc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return Kc(t,r);case N.ZodIntersection:return zc(t,r);case N.ZodTuple:return Yc(t,r);case N.ZodRecord:return Ms(t,r);case N.ZodLiteral:return Lc(t,r);case N.ZodEnum:return Nc(t);case N.ZodNativeEnum:return Fc(t);case N.ZodNullable:return Gc(t,r,n);case N.ZodOptional:return Hc(t,r,n);case N.ZodMap:return Dc(t,r);case N.ZodSet:return Qc(t,r);case N.ZodLazy:return O(t.getter()._def,r,n);case N.ZodPromise:return Zc(t,r,n);case N.ZodNaN:case N.ZodNever:return Uc();case N.ZodEffects:return $c(t,r,n);case N.ZodAny:return kc();case N.ZodUnknown:return ed();case N.ZodDefault:return Rc(t,r,n);case N.ZodBranded:return Mc(t,r,n);case N.ZodReadonly:return td(t,r,n);case N.ZodCatch:return Oc(t,r,n);case N.ZodPipeline:return Jc(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},Hh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var yi=(t,e)=>{let r=Sc(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(Tc(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(Ao(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 nd(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 _i(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(_i(e))return!0;for(let e of t.anyOf??[])if(_i(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(!ur(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(ur(n))for(let[f,I]of Object.entries(n))tt(I,[...e,"$defs",f],r);let o=t.definitions;if(ur(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(ur(i)){for(let[f,I]of Object.entries(i))if(!_i(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;ur(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&&Zh(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=Jh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!ur(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 Jh(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(!ur(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 ur(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Zh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function Qh(t,e){return yi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Yh(t){return nd(hl(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 Xh(t){return"_zod"in t}function od(t,e,r){return Su({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Xh(t)?Yh(t):Qh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var sd=["jsonSchema","functionCalling","jsonMode"];function ad(t,e){if(typeof e<"u"&&!sd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${sd.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function eg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function id(t,e,r){if(gl(t))return od(t,e,r);if(Uo(t))return eg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Ct(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>ml(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function ld(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 ud={"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 $n(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var cr=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??Ie("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Ie("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)?id(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 ir(t)?xc(t.metadata.customTool):Bo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:dc(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(Rn(n)||ir(n))return n;if(fc(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return gr(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=pc(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 xe(o)}})}get profile(){return ud[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=ad(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 wl}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=bl(o,u)}return xl(r,n,a)}};var Os={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=ar(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=ar(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`)}},wi=({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(fr(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:ld(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 jo(t.content||"",t.role??"unknown")}},bi=({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 cl({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 ul({content:s,role:o,response_metadata:i})},cd=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=dl(()=>{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=ar(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}}}},dd=({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=cd(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Nn=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return dd({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)?Lo(a,Os):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 Rs=class extends cr{constructor(t,e){super($n(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:Cs(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=Nn({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=Nn({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*Vo(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=Nn({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 Hn({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 Hn({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 xe(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return bi({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return wi({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var $s="__openai_function_call_ids__",Ns="__openai_custom_tool_call_ids__";function _d(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function rg(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 vo=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}},zs=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(_d),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(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(fr(u,d))}a[$s]??={},i.id&&(a[$s][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=gc(i);u?(r.push(u),a[Ns]??={},i.id&&i.call_id&&(a[Ns][i.call_id]=i.id)):n.push(fr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=yc(i);u?r.push(u):n.push(fr(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:vo(t.usage),additional_kwargs:a,response_metadata:s})},wd=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}},xi=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:[_d(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,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.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[Ns]={[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=zs(t.response);if(n=vo(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 Hn({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})},bd=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ce(()=>{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=Ce(()=>{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=Ss(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=Ss(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=ar(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=Ce(()=>{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=Ce(()=>{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())},To=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return bd(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=wd(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:Ce(()=>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(rg)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Ce(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let m=s?.[$s],f=s?.[Ns];D.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(b=>wc(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}:_c(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=Ss(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:ar(l)}}return Lo(l,Os)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ce(()=>{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:Ce(()=>{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*Ai(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:Al(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=ng(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=vo(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 ng(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Ls=class extends cr{constructor(t,e){super($n(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:hc(t?.tool_choice)?t?.tool_choice:(()=>{let o=Cs(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:To({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:zs(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:To({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Ai(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:To({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=xi(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 xe(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 xe(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Rn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(ir(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 Es(n)&&r.push(bc(n));return r}};var js=class xd extends cr{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=$n(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Ls(n),this.completions=n?.completions??new Rs(n)}_useResponsesApi(e){let r=e?.tools?.some(Rn),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(Es)||e?.tools?.some(ir);return this.useResponsesApi||r||n||o||lc(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 xd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ds=class extends yl{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??Ie("OPENAI_API_KEY");this.organization=e?.configuration?.organization??Ie("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 xe(r)}})}};var ig=v.object({type:v.literal("screenshot")}),lg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),ug=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),cg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),dg=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),pg=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),mg=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),fg=v.object({type:v.literal("type"),text:v.string()}),hg=v.object({type:v.literal("wait"),duration:v.number().optional()}),gg=v.union([ig,lg,ug,cg,dg,pg,mg,fg,hg]),EK=v.object({action:gg});var yg=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()}),RK=v.union([yg]);var LK=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 _g=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),wg=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),bg=v.object({type:v.literal("delete_file"),path:v.string()}),UK=v.union([_g,wg,bg]);var vd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},vi={default:"text-embedding-ada-002"},Ii=new Map,Fs=null,vg=()=>{let t=Ad.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},Td=async t=>{let e=vg();Ii.size===0&&(Fs||(Fs=(async()=>{try{(await Id(`${e}/models`)).data.models.forEach(n=>Ii.set(n.name,n))}catch(n){throw Fs=null,n}})()),await Fs);let r=Ii.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Tg=async(t="default")=>await Td(vd[t]),Sd=async(t="default")=>await Td(vi[t]),Sg=C.Root({agentExecutionContext:C({default:ya,reducer:ha}),currentIntent:C({default:()=>"none",reducer:it}),routing:C({default:()=>({mode:"auto"}),reducer:it}),lastExecutedAgent:C({default:()=>"",reducer:it}),requiresFollowUp:C({default:()=>!0,reducer:it}),stepCount:C({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:C({default:()=>"",reducer:ga})});var kg=t=>typeof t=="string"&&t.length>0?t:void 0,Cg=()=>tl(),Eg=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Pg=t=>{let e=t?.configurable;return{conversationId:kg(e?.thread_id),abortSignal:t?.signal,requestId:Cg(),requestSource:Eg(Ig.applicationName)}},Mg=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},kd=async({config:t})=>{let e=Ad.getDefault(),r=(await Ag.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Pg(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 Id(n instanceof Request?n.url:n.toString(),{body:Mg(o?.body),headers:Object.fromEntries(l),responseType:"native",signal:d})).data}},Ti=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=vd[e],s=await Tg(e);return new js({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await kd({config:n})}})},Cd=async(t={})=>{let{tier:e="default",config:r}=t,n=vi[e],o=await Sd(e);return new Ds({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:await kd({config:r})},batchSize:2048,maxConcurrency:10})},Og=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(Og);var Ed="0.1",zn=1536,Pd="openai",Md=vi.default,Od=`Name: {name}
|
|
73
73
|
Title: {title}
|
|
74
|
-
Description: {description}
|
|
74
|
+
Description: {description}`,Rd=`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(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}
|
|
76
|
+
Description: {description}`,$d=v.object({schemaVersion:v.literal(Ed),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Pd),model:v.literal(Md),dimensions:v.literal(zn),templates:v.object({layer:v.string().default(Od),field:v.string().default(Rd)})}),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(zn,{message:`Layer vector must be exactly ${zn} 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(zn,{message:`Field vector must be exactly ${zn} dimensions`})}))})).default([])});var Rg=(t,e)=>{let r=Il.fromTemplate(t);return hr.fromMessages([r,...e])};var So=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=Rg(e,o??[]),l=(await Ti({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var $g=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),pV=c.object({fields:c.array($g)});var mV=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var Nd=async t=>{try{return await(await Cd()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var Ld=t=>Array.isArray(t)&&t.every(Wn),zg=t=>typeof t=="object"&&t!=null&&"messages"in t&&Ld(t.messages),Lg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,rt=class extends vl{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 Wn(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(Lg(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(zg(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=>al(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 p2=C.Root({llmInputMessages:C({reducer:(t,e)=>Jn([],e),default:()=>[]})});var ko=(t,e)=>e??t,wy=C.Root({...Jo(),intent:C({reducer:ko}),vectorSearchLayerResults:C({reducer:ko,default:()=>[]}),vectorSearchFieldResults:C({reducer:ko}),navigationInternalState:C({reducer:ko,default:()=>({toolCallMessage:void 0})})});async function by(t,e){let r=dr.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=`${Si.assetsPath?.endsWith("/")?Si.assetsPath:`${Si.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await Fg(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 Ug({url:s,width:24,height:24}),u=new Dg({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}}}}function oe(t,e){let r=t?.configurable?.context;if(!r||typeof r!="object")throw new Error("Agent context missing");let n=e.filter(o=>!(o in r));if(n.length)throw new Error(`Agent context missing: ${n.join(", ")}`);return r}async function xy({address:t},e){let{mapView:r}=oe(e,["mapView"]);return await by(t,r)}var Ay=c.object({address:c.string().describe("The full address or place name to locate.")}),Iy=$(xy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Ay});async function vy(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 Ty({bookmarkName:t},e){let{mapView:r}=oe(e,["mapView"]);return await Promise.resolve(vy(t,r))}var Sy=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),ky=$(Ty,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Sy});async function Cy(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 Ey({layerId:t,where:e},r){let{mapView:n}=oe(r,["mapView"]);return await Cy(t,e,n)}var Py=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.")}),My=$(Ey,{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:Py});async function Oy(t){let e=new qg({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 Ry(t,e){let{mapView:r}=oe(e,["mapView"]);return await Oy(r)}var $y=v.object({}),Ny=$(Ry,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:$y});async function zy(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 Ly(t,e){let{mapView:r}=oe(e,["mapView"]);return await zy(r)}var jy=c.object({}),Dy=$(Ly,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:jy});async function Fy(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 Uy({layerId:t},e){let{mapView:r}=oe(e,["mapView"]);return await Fy(t,r)}var qy=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),By=$(Uy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:qy});async function Ky(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Gy({scale:t},e){let{mapView:r}=oe(e,["mapView"]);return await Ky(t,r)}var Vy=c.object({scale:c.number().describe("The map scale of the view to go to.")}),Wy=$(Gy,{name:"goToScale",description:"Go to the specified view scale.",schema:Vy});async function Hy(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 Jy({center:t,zoom:e,scale:r},n){let{mapView:o}=oe(n,["mapView"]);return await Hy(t,o,{zoom:e,scale:r})}var Zy=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.")}),Qy=$(Jy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Zy});async function Yy(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Xy({zoom:t},e){let{mapView:r}=oe(e,["mapView"]);return await Yy(t,r)}var e_=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),t_=$(Xy,{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:e_}),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}
|
|
78
78
|
Available prompts:
|
|
79
|
-
${Object.keys(
|
|
80
|
-
`)}`);return await e[1]()}var
|
|
79
|
+
${Object.keys(Bd).join(`
|
|
80
|
+
`)}`);return await e[1]()}var Dn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function r_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=Kg({basemapTheme:await Fd(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=Gg({basemapTheme:await Fd(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 n_(t){return await Bg(t)}async function o_({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 r_(u),d=await n_(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 s_=["mapView"];function Me(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=s_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function a_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await o_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var i_=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)")}),l_=$(a_,{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(Kd).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:i_});function u_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=zi({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 c_(t){return await Vg(t)}async function d_({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=u_(u),d=await c_(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 p_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await d_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var m_=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")}),f_=$(p_,{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:m_});function h_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=zi({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 g_(t){return await Wg(t)}async function y_({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=h_(u),d=await g_(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 __({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await y_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var w_=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")}),b_=$(__,{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:w_});function x_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=zi({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 A_(t){return await Hg(t)}async function I_({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=x_(u),d=await A_(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 v_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await I_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var T_=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")}),S_=$(v_,{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:T_});function k_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=Zg({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 C_(t){return await Jg(t)}async function E_({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=k_(i),l=await C_(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 P_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Me(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await E_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var M_=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")}),O_=$(P_,{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(Kd).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:M_});function R_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=Yg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function $_(t){return await Qg(t)}async function N_({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=R_(i),l=await $_(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 z_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Me(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await N_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var L_=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")}),j_=$(z_,{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:L_});function D_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=ey({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 F_(t){return await Xg(t)}async function U_({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=D_(u),d=await F_(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 q_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await U_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var B_=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)")}),K_=$(q_,{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:U_});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:B_});function G_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=ry({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function V_(t){return await ty(t)}async function W_({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=G_(i),l=await V_(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 H_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Me(n);return await fe({type:"show-legend",data:{layerIds:[t]}},n),await W_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var J_=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")}),Z_=$(H_,{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:J_});function Q_(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 Y_(t){return await ny(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:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Q_(u),d=await Y_(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 ew({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await X_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var tw=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")}),rw=$(ew,{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:tw});function nw(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 ow(t){return await oy(t)}async function sw({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=nw(u),d=await ow(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 aw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await sw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var iw=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")}),lw=$(aw,{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:U_});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:iw});function uw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=ay({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function cw(t){return await sy(t)}async function dw({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=uw(u),d=await cw(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 pw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Me(o);return await fe({type:"show-legend",data:{layerIds:[t]}},o),await dw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var mw=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")}),fw=$(pw,{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: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.
|
|
149
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:mw}),hw=C.Root({...Et(),vectorSearchLayerIds:C(),vectorSearchFieldResults:C(),layerFieldInfo:C(),selectedLayerId:C()}),gw=C.Root({...Et(),vectorSearchLayerIds:C(),vectorSearchFieldResults:C(),layerFieldInfo:C(),queryResponse:C(),dataExplorationMessages:C({reducer:Jn,default:()=>[]})}),yw=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."},_w=async(t,e)=>{let{mapView:r}=oe(e,["mapView"]);return yw(r)},IW=$(_w,{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({})}),ww=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."},bw=async(t,e)=>{let{mapView:r}=oe(e,["mapView"]);return await ww(r)},vW=$(bw,{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 Co(t){return"layerId"in t&&t.layerId!==void 0}var Ws=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(Co(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"}},xw=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)}}},Aw=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 Ws(o,e);if("error"in m)return m.error;i=m.geometry}if(a.featureEffect=null,a.featureEffect=new iy({filter:new Wd({...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 xw(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}`},Iw=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Tt=c.enum(Iw),vw=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}=oe(s,["mapView"]);return await Aw(t,a,n,o,e,r)},Tw=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.")}),Sw=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.")}),kw=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([Tw,Sw]).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.")}),TW=$(vw,{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:kw}),Cw=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 Cw.has(e)},Ci=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},Ew=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Pw=t=>{if(typeof t=="string"&&t)return t;let e=Ci(t);return e?e.toISOString().slice(0,10):null};var Mw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Zd(n))return t;if(n==="date-only"){let s=Pw(t);return s?ly(s,Us("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return uy(t,Us("long-time"));let s=Ci(t);return s?Ud(s,{...Us("long-time"),timeZone:"UTC"}):t}let o=Ci(t);return o?Ud(o,{...Us("short-date-short-time"),timeZone:Ew(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},Ow=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Rw=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},$w=(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}},Nw=(t,e,r)=>{let n=Rw(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=Ow(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"?$w(r,s):s?.type==="date-time"?!n||Zd(n)?Nw(r,s,o):r:Mw(r,n,o)},zw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Qd(e,r,t)??r;return Xd(t,e,s,o?.type,n)},Lw=(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}},jw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Dw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(d=>d.id===t),s=jw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=zw(o,e,i,n.timeZone),l=Lw(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 Fw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=oe(n,["mapView"]),s=await Dw(t,e,r,o);return JSON.stringify(s,null,2)}var Uw=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.")})}),qw=$(Fw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Uw}),Li=(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 Bw=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 Ws(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw Co(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(Co(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 Wd({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let I=Li(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 cy(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await dy({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 Kw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Dn(o,"layersAndFieldsRegistry"),{mapView:a}=oe(o,["mapView"]),i=await Bw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var Gw=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.")}),Vw=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.")}),Ww=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([Gw,Vw]).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.")}),Hw=$(Kw,{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: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.
|
|
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:Ww}),Jw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Zw=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 Ws(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 py({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 my({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,...Jw(e.orderByFields)])],h=Li(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)}}}},Qw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=oe(o,["mapView"]),a=await Zw(t,e,s,r,n);return JSON.stringify(a,null,2)},Yw=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.")}),Xw=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.")}),eb=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([Yw,Xw]).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).")}),tb=$(Qw,{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:eb}),ki=25,rb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),nb=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 Ws(r,e);if("error"in y){let h={error:y.error};if(Co(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(Co(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,...rb(t.orderByFields)])],l=Li(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<=ki&&(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<=ki&&(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>ki&&{note:`${f} features found.`}}}};async function ob({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=oe(n,["mapView"]),s=await nb(t,o,e,r);return JSON.stringify(s,null,2)}var sb=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.")}),ab=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.")}),ib=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([sb,ab]).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).")}),lb=$(ob,{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:ib}),tp=[qw,Hw,tb,lb];var SW=new rt(tp,{handleToolErrors:!1});var ub=C.Root({...Et(),helpInternalState:C({reducer:ko,default:()=>({toolCallMessage:void 0})})}),cb=(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}.`}},
|
|
173
|
+
${o}`},db=({layerTitle:t},e)=>{let r=Dn(e,"layersAndFieldsRegistry");return cb(r,t)},pb=$(db,{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.")})}),mb=C.Root({...Et(),intent:C({reducer:(t,e)=>e}),arcgisKnowledgeMessages:C({reducer:Jn,default:()=>[]}),arcgisKnowledgeToolResult:C({reducer:(t,e)=>e,default:()=>null})});function rp(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 Fn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function Hs(t){!t||Fn(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Po(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)&&rp(r),{view:r}}async function Un(t){let e=t?.configurable?.context;if(fb(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 qd(n)}}else{rp(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 qd(n)}}}}function fb(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 Ei=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Vs.fromDataModel(e)}},Vs=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(Eo.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Pi.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:hb(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}.`}},Eo=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=gb(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:yb(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}},Pi=class extends Eo{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Eo.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},hb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},gb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function yb(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 _b(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 wb(t,e,r,n){let{graphQuery:o,explanation:s}=await ji(t,e,r,n);return{graphQuery:o,explanation:s}}async function ji(t,e,r,n,o){let s={message:await _b(t,o),context:new Ei(e)},a=Js(n);await H({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await Dd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:jd.findCredential(dr.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 Dd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:jd.findCredential(dr.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 bb(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(Ab(t))for(let r of t.path)Ln(r,e);else if(xb(t))e(t);else if(Array.isArray(t))for(let r of t)Ln(r,e);else if(Ib(t))for(let r of Object.values(t.properties??{}))Ln(r,e)}}function xb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Ab(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Ib(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function vb(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 Tb(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 jn=3;function np(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 qn(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 Sb=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 hy(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:qn(f),error:f}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function op({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<=jn;m++){let f;try{f=await ji(t,r.dataModel,n,l,d)}catch(y){return{type:"generation-error",errorMessage:qn(y),error:y}}await H({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let I=await kb(f.graphQuery,e),w=await Sb({kg:r,queryParams:new Jd({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>=jn)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 ${jn} attempts.`)}var kb=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await _y(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},Cb=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 gy(t,new yy({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=qn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},sp="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function ap({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(sp),!Fn(e)&&e.map){let d=await nt("arcgis_knowledge_current_lc_context"),m=vb(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}=Tb(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 Eb(t,e,r,n,o,s){let{view:a}=o,i=await op({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,I)=>{for(let w of I)bb(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),!Fn(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",Pb=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.")}),Mb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=Po(e),{view:o}=n,s=dr.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await ap({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 Eb(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=
|
|
189
|
+
Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:m}}}catch(l){let d=qn(l);return{toolName:qs,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},Ob=$(Mb,{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:Pb});async function Rb(t,e){return await e.map?.applyLayout(t),await Hs(e),{appliedLayout:t}}var Mi="applyLayout",$b=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")}),Nb=async({layout:t},e)=>{let{view:r}=Po(e);if(Fn(r))return{toolName:Mi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await Rb(t,r);return{toolName:Mi,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},zb=$(Nb,{name:Mi,description:"Apply a diagram layout to the link chart",schema:$b});async function Lb(t,e){return e.map?.changeNonspatialDataDisplay(t),await Hs(e),{appliedNonspatialDataDisplayMode:t}}var Oi="changeNonspatialVisibility",jb=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Db=async({setting:t},e)=>{let{view:r}=Po(e);if(Fn(r))return{toolName:Oi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await Lb(t,r);return{toolName:Oi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},Fb=$(Db,{name:Oi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:jb});async function Ub(t,e,r,n,o){let s,a="";for(let i=1;i<=jn;i++){let{graphQuery:u,explanation:l}=await ji(t,e.dataModel,r,o,s);try{await H({text:`Attempting to create link chart from derived query: ${u}`},o);let d=await fy.fromCypherQuery(e,new Jd({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 Gd.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=
|
|
202
|
+
Explanation: ${l}`}):(await Hs(n),{type:"success",graphQuery:u,explanation:l})}catch(d){let m=qn(d);if(i>=jn){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 ${jn} attempts. Last error: ${a}`}}var Bs="createLinkChart",qb=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.")}),Bb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),{view:n}=Po(e);if(Fn(n))return{toolName:Bs,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=dr.getDefault().helperServices,s=await Ub(`${t}
|
|
203
203
|
|
|
204
|
-
${
|
|
204
|
+
${sp}`,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}}}},Kb=$(Bb,{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:qb}),Ri="queryGraphData",Gb=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.")}),Vb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=dr.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Po(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await ap({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await op({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:Ri,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=>np(h));let I=50,w=d.slice(0,I).map(b=>JSON.stringify(b));return{toolName:Ri,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}}},Wb=$(Vb,{name:Ri,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:Gb}),$i="generateCypher",Hb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Jb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=dr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await wb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:$i,status:"success",summary:`Generated Graph Query:
|
|
225
225
|
${o}
|
|
226
226
|
|
|
227
|
-
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=
|
|
227
|
+
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=qn(o);return{toolName:$i,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},Zb=$(Jb,{name:$i,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:Hb}),Qb=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 Yb(t,e,r){let n=await nt("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:Qb(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 So({promptText:n,inputVariables:o,schema:u,config:r})}var Ni="searchGraphData",Xb=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.")}),ex=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e);await H({text:"Generating search query for the user inquiry"},e);let n=await Yb(t,r,e);await H({text:"Executing graph search with generated search query"},e);let o=await Cb({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:Ni,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)Ln(i,u=>np(u));let s=10,a=o.results.slice(0,s);return{toolName:Ni,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 nx(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}}},tx=$(ex,{name:Ni,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 nx(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:Xb});var nH=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 nx(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 bH=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 KH=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 nx(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 l4=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 nx(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 S4=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
|
|
337
|
+
_example: "What is the average age of all people who work for Esri?"_`;var Oe=So;var te=H,lp=Nd;var Bn=()=>Jo(),Qs=async(t,e)=>await fe(t,e),Ys=async({modelTier:t="default",temperature:e=0,config:r}={})=>await Ti({modelTier:t,temperature:e,config:r});var Cp=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function mr(t){if(!Cp(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var sx=`
|
|
338
338
|
Write a concise, friendly success message for adding members to a group.
|
|
339
339
|
|
|
340
340
|
Rules:
|
|
@@ -349,12 +349,12 @@ Added members:
|
|
|
349
349
|
|
|
350
350
|
Not added members:
|
|
351
351
|
{notAddedMembers}
|
|
352
|
-
`,
|
|
352
|
+
`,ax=t=>t.map(e=>`"${e}"`).join(", "),ix=c.object({successMessage:c.string().default("")}),cp="portal-group-creation",dp="approveAddMembers",lx=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let 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!==cp||s.id!==dp){let m={agentId:cp,id:dp,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 ${ax(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;mr(a);let{result:i,error:u}=await kl(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 Oe({promptText:sx,schema:ix,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(m)return{status:"success",outputMessage:m}}catch(m){console.error("Error generating add-members success message:",m)}return{}},ux=`
|
|
358
358
|
Write a concise, friendly success message after creating a portal group.
|
|
359
359
|
|
|
360
360
|
Rules:
|
|
@@ -365,7 +365,7 @@ Rules:
|
|
|
365
365
|
|
|
366
366
|
Group title:
|
|
367
367
|
{groupTitle}
|
|
368
|
-
`,
|
|
368
|
+
`,cx=`
|
|
369
369
|
Write a concise, friendly failure message after an attempt to create a portal group.
|
|
370
370
|
|
|
371
371
|
Rules:
|
|
@@ -380,7 +380,7 @@ Group title:
|
|
|
380
380
|
|
|
381
381
|
Failure reason:
|
|
382
382
|
{failureReason}
|
|
383
|
-
`,
|
|
383
|
+
`,pp="portal-group-creation",mp="approveCreateGroup",dx=c.object({successMessage:c.string().default("")}),px=c.object({failureMessage:c.string().default("")}),mx=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==pp||o.id!==mp){let l={agentId:pp,id:mp,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;mr(s);let{result:a,error:i}=await Sl(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let d=(await Oe({promptText:cx,schema:px,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(d)return{status:"success",outputMessage:d}}catch(d){console.error("Error generating create-group failure message:",d)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Oe({promptText:ux,schema:dx,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},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""},fx=`
|
|
384
384
|
You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
|
|
385
385
|
|
|
386
386
|
Rules:
|
|
@@ -406,17 +406,17 @@ Examples:
|
|
|
406
406
|
|
|
407
407
|
User message:
|
|
408
408
|
{userMessage}
|
|
409
|
-
`,
|
|
409
|
+
`,hx=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),gx=async(t,e)=>{await te({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Ue(t.agentExecutionContext.messages).trim(),n=await Oe({promptText:fx,schema:hx,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:""}},yx=["customSignInSection","loginsSection","changeLoginProviderSection","multiFactorAuthSection","multifactorEnforcementSection","multifactorDesignatedAdminsSection"],_x=["customSignInCard","loginCard","multifactorAuthCard"],wx=["newItem","createLayer","developerCredentials"],bx={customSignInSection:"customSignInCard",loginsSection:"loginCard",changeLoginProviderSection:"loginCard",multiFactorAuthSection:"multifactorAuthCard",multifactorEnforcementSection:"multifactorAuthCard",multifactorDesignatedAdminsSection:"multifactorAuthCard"},xx=["favorites","group","living-atlas","org"],Ax=["featured","my","organization"],Ix=["licenses","members","overview","reports","settings","status"],vx=c.object({destinationType:c.literal("portal-content"),hash:c.enum(xx).optional(),queryParams:c.object({newItem:c.enum(wx).optional()}).optional()}),Tx=c.object({destinationType:c.literal("portal-groups"),hash:c.enum(Ax).optional()}),Sx=c.object({destinationType:c.literal("portal-org"),hash:c.enum(Ix).optional(),queryParams:c.object({tab:c.literal("security").optional(),section:c.enum(_x).optional(),subsection:c.enum(yx).optional(),period:c.string().optional(),startTime:c.string().optional(),endTime:c.string().optional()}).optional()}),kx=c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),Cx=c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1)}),Ex=c.object({destinationType:c.union([c.literal("portal-gallery"),c.literal("portal-map-viewer"),c.literal("portal-notebooks"),c.literal("portal-scene-viewer")])}),Px=c.union([vx,Tx,Sx,kx,Cx,Ex]),Ep="portal-navigation",na=async(t,e)=>{let r=e?.configurable?.context;!Cp(r)||!r.navigationTargetMap?.[t.destinationType]||await Qs({type:Ep,data:{...t}},e)},Mx=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),{}):{}},fp=(t,e)=>e??t,Pp=C.Root({...Bn(),intentParams:C({reducer:fp,default:()=>({intent:"clarify"})}),createdGroupId:C({reducer:fp,default:()=>""})}),Ox=()=>new ce(Pp).addNode("detectGroupCreationIntent",gx).addNode("createPortalGroup",mx).addNode("addMembersToPortalGroup",lx).addNode("suggestCreatedGroupNavigation",Mx).addEdge(ue,"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),Rx=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
|
-
`),Vx=`
|
|
412
|
+
`,$x={id:"portal-group-creation",name:"Portal Group Creation",description:Rx,createGraph:Ox,workspace:Pp},Mp="portalDocAssistantMemory",Nx=()=>({conversationId:""}),zx=t=>{let e=t?.[Mp]?.value;if(!e||typeof e!="object")return Nx();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Lx=t=>({[Mp]:{value:t}}),jx={pipeline:{follow_up:{allow:!1}}};function Dx(t){return{kind:"DocAIAssistantRequest",filters:{...jx,persona:{persona:t}}}}async function Fx({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=Dx(r),i=await Ux({portal:t,skillId:s,message:e,options:{context:a,previousConversationId:n,signal:o}});return{reply:qx(i,s),conversationId:i[0]?.conversationId??""}}async function Ux({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:nx.findCredential(t.url)?.token??""},a=await up(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 ol(500);let w=await up(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 qx(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 Bx=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;mr(n);let o=zx(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Fx({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})}},Op=$(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;mr(n);try{return(await Tl(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.")})}),Rp=$(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;mr(n);let{result:o,error:s}=await Cl(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 Oo(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}function Kx(t){let e=Ro(t).flatMap(r=>{let n=r,o=t[r],s=[n,{description:o.description,hints:o.hints}],a=o.sections?Ro(o.sections).map(i=>{let u=o.sections?.[i];return[`${n}-${i}`,u]}):[];return[s,...a]});return Object.fromEntries(e)}function Gx(t){return Object.entries(t).map(([e,{description:r,hints:n}])=>` - ${e}: ${r} (hints: ${n.join(", ")})`).join(`
|
|
413
|
+
`)}var Vx={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"]},"portal-content-favorites":{description:"The Favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"]},"portal-content-group":{description:"The Groups view under Content in the portal.",hints:["Content groups","Group content","My groups content"]},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content living atlas"]},"portal-content-organization":{description:"The Organization view under Content in the portal.",hints:["Organization content","Content organization","My organization content"]},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"]},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"]},"portal-groups":{description:"The groups listing page of the portal.",hints:["Groups","Browse groups"]},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"]},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"]},"portal-groups-organization":{description:"The Organization groups view under Groups in the portal.",hints:["Organization groups","Groups organization","My organization groups"]},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"]},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"]},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"]},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"]},"portal-org-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],sections:{"custom-sign-in":{description:"The Organization > Settings > Security > Custom Sign In section of the portal.",hints:["Custom Sign In","Organization > Settings > Security > Custom Sign In"]},logins:{description:"The Organization > Settings > Security > Logins section of the portal.",hints:["Logins","Organization > Settings > Security > Logins"]},"change-login-provider":{description:"The Organization > Settings > Security > Change Login Provider section of the portal.",hints:["Change Login Provider","Organization > Settings > Security > Change Login Provider"]},"multifactor-auth":{description:"The Organization > Settings > Security > Multifactor Authentication section of the portal.",hints:["MFA","Multifactor Authentication","Organization > Settings > Security > MFA"]},"multifactor-enforcement":{description:"The Organization > Settings > Security > Enforce MFA section of the portal.",hints:["Enforce MFA","MFA enforcement","Organization > Settings > Security > Enforce MFA"]},"multifactor-designated-admins":{description:"The Organization > Settings > Security > Designated Admins section of the portal.",hints:["Designated admins","MFA designated admins","Organization > Settings > Security > Designated Admins"]}}},"portal-content-new-item":{description:"The Content page with the New Item flow opened.",hints:["New item","Create new item","Content > My Content > New Item"],sections:{"feature-layer":{description:"The Content page with New Item flow set to Feature Layer as the starting step.",hints:["Feature Layer","New Feature Layer","Content > My Content > New Item > Feature Layer"]},"developer-credentials":{description:"The Content page with New Item flow set to Developer Credentials as the starting step.",hints:["Developer Credentials","New developer credentials","Content > My Content > New Item > Developer Credentials"]}}}},$p=Kx(Vx),Wx=Ro($p),Hx=Gx($p),Jx=`
|
|
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
|
+
${Hx}
|
|
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
|
+
`,hp=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...Wx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),Zx=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 hr.fromTemplate(Jx).format({question:n,response:r}),s=(await Ys({modelTier:"fast"})).withStructuredOutput(hp),a=hp.parse(await s.invoke(o));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Oo(n,"#");u&&(a.itemId=await Rp.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Oo(n,"$")??Oo(n,"#");u&&(a.groupId=await Op.invoke({groupTitle:u},e)??"")}let i=Qx(a);return i?(await na(i,e),{}):{}};function Qx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":case"portal-gallery":case"portal-groups":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":return{destinationType:t};case"portal-org-security":return{destinationType:"portal-org",hash:"settings",queryParams:{tab:"security"}};case"portal-content-new-item":case"portal-content-new-item-feature-layer":case"portal-content-new-item-developer-credentials":return{queryParams:{newItem:Yx[t]},destinationType:"portal-content"};case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":return{destinationType:"portal-content",hash:Xx[t]};case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":return{destinationType:"portal-groups",hash:eA[t]};case"portal-org-security-custom-sign-in":case"portal-org-security-logins":case"portal-org-security-change-login-provider":case"portal-org-security-multifactor-auth":case"portal-org-security-multifactor-enforcement":case"portal-org-security-multifactor-designated-admins":let n=tA[t];return{destinationType:"portal-org",hash:"settings",queryParams:{tab:"security",section:bx[n],subsection:n}};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 Yx={"portal-content-new-item":"newItem","portal-content-new-item-feature-layer":"createLayer","portal-content-new-item-developer-credentials":"developerCredentials"},Xx={"portal-content-favorites":"favorites","portal-content-group":"group","portal-content-living-atlas":"living-atlas","portal-content-organization":"org"},eA={"portal-groups-featured":"featured","portal-groups-my":"my","portal-groups-organization":"organization"},tA={"portal-org-security-custom-sign-in":"customSignInSection","portal-org-security-logins":"loginsSection","portal-org-security-change-login-provider":"changeLoginProviderSection","portal-org-security-multifactor-auth":"multiFactorAuthSection","portal-org-security-multifactor-enforcement":"multifactorEnforcementSection","portal-org-security-multifactor-designated-admins":"multifactorDesignatedAdminsSection"},Np=C.Root({...Bn()}),rA=()=>new ce(Np).addNode("answerDocQuestion",Bx).addNode("extractNavigationIntent",Zx).addEdge(ue,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",U),nA=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
|
+
`,oA={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:nA,createGraph:rA,workspace:Np},sA=()=>({latestGroupId:null,memory:{}}),oa=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:sA()},zp=`
|
|
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
|
+
`,aA=`
|
|
453
453
|
You answer follow-up questions about ArcGIS group analytics.
|
|
454
454
|
|
|
455
|
-
${
|
|
455
|
+
${zp}
|
|
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
|
+
`,iA=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 Oe({promptText:aA,schema:lA,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>."}},lA=c.object({answer:c.string(),isRelevant:c.boolean()}),uA=`
|
|
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
|
+
`,cA=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 hr.fromTemplate(uA).format({userMessage:r,hasAnalyticsContext:String(n)}),s=(await Ys({modelTier:"fast"})).withStructuredOutput(gp),a=gp.parse(await s.invoke(o)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let I=Oo(r,"$");I&&(i=await Op.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":""}},gp=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),dA=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 Lp({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var pA=720*60*60*1e3;function mA(t){let e=Pl(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:Ml(t),membershipAccess:Ol(t),isOpenData:Rl(t),isDistributedCollaborationGroup:$l(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function fA(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 hA(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 gA(t,e){return t.filter(r=>r.modified?Lp({timestamp:r.modified,now:e,windowMs:pA}):!1)}function yA(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 _A(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=hA(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:gA(r,n),topItemTypes:yA(r)}}async function wA(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=mA(r),o=await fA(r),s=await _A(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 bA=`
|
|
507
507
|
You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
|
|
508
508
|
|
|
509
|
-
${
|
|
509
|
+
${zp}
|
|
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
|
+
`,xA=2160*60*60*1e3,AA=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;mr(n);let{result:o,error:s}=await wA(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?Lp({timestamp:l,now:u,windowMs:xA}):!1,m=i.recentlyModifiedItems.length,f=m>0,I=d||f,w=await Oe({promptText:bA,schema:IA,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}}}},IA=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Ui=(t,e)=>e??t,jp=C.Root({...Bn(),groupSummaryIntent:C({reducer:Ui,default:()=>"clarify"}),groupSummaryGroupId:C({reducer:Ui,default:()=>null}),groupSummaryQuestion:C({reducer:Ui,default:()=>""})}),vA=()=>new ce(jp).addNode("detectGroupSummaryIntent",cA).addNode("summarizePortalGroup",AA).addNode("answerGroupSummaryFollowUp",iA).addNode("suggestGroupSummaryNavigation",dA).addEdge(ue,"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),TA=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
|
+
`,SA={id:"portal-group-analytics",name:"Portal Group Analytics",description:TA,createGraph:vA,workspace:jp},kA=()=>({latestItemId:null,memory:{}}),Hi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:kA()},yp=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),CA=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),EA=c.object({answer:c.string(),isRelevant:c.boolean()}),PA=`
|
|
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
|
+
`,MA=async(t,e)=>{await te({text:"Answering follow-up...",agentName:"analytics"},e);let r=Hi(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 Oe({promptText:PA,schema:EA,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>."}},OA=`
|
|
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
|
+
`,RA=async(t,e)=>{await te({text:"Analyzing intent...",agentName:"analytics"},e);let r=Ue(t.agentExecutionContext.messages),n=!!Hi(t).latestItemId,o=await hr.fromTemplate(OA).format({userMessage:r,hasSummaryContext:String(n)}),s=(await Ys({modelTier:"fast"})).withStructuredOutput(yp),a=yp.parse(await s.invoke(o)),i=a.itemId;if(a.intent==="summarize"&&!i){let m=Oo(r,"#");m&&(i=await Rp.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>".':""}},$A=`
|
|
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
|
+
`,NA=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;mr(n);let{portal:o,user:s}=n,{result:a,error:i}=await El(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 Oe({promptText:$A,schema:CA,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:m}=l,f=Hi(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}}}},qi=(t,e)=>e??t,Dp=C.Root({...Bn(),analyticsIntent:C({reducer:qi,default:()=>"clarify"}),analyticsItemId:C({reducer:qi,default:()=>null}),analyticsQuestion:C({reducer:qi,default:()=>""})}),zA=()=>new ce(Dp).addNode("detectAnalyticsIntent",RA).addNode("summarizePortalItem",NA).addNode("answerAnalyticsFollowUp",MA).addEdge(ue,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":U).addEdge("summarizePortalItem",U).addEdge("answerAnalyticsFollowUp",U),LA=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
|
+
`,jA={id:"portal-item-analytics",name:"Portal Item Analytics",description:LA,createGraph:zA,workspace:Dp},DA={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"}}}]},FA={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"}}}]},UA={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"}}}]},qA={"contentRouteRegistry.ts":DA,"groupsRouteRegistry.ts":FA,"orgSettingsRouteRegistry.ts":UA};function _p(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 pr(t){return t?Xs=_p({customCapabilities:t}):Xs||(Xs=_p(qA)),Xs}var BA=/^(?: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(BA,"").trim()}var KA=c.object({capabilityIds:c.array(c.string()).default([]),confidence:c.number().min(0).max(1).default(0),reason:c.string().default("")}),wp=.8,GA=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}`,VA=async(t,e)=>{if(t.outputMessage||t.targets.length===0)return{};let r=Ue(t.agentExecutionContext.messages).trim(),n=WA(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 Oe({promptText:GA,schema:KA,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<wp?{chosenCapabilityIds:[],status:"failed",summary:`Navigation selection confidence ${s.confidence} is below the required ${wp}; 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 WA(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 Fp=new Set(["1d","7d","14d","30d","3m","6m"]),HA=c.object({period:c.string(),startTime:c.string(),endTime:c.string()}),JA=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 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:
|
|
654
|
+
{userRequest}`;async function ZA(t,e=new Date){let r=t.trim();if(!r)return{};try{let n=await Oe({promptText:JA,schema:HA,modelTier:"fast",inputVariables:{nowEpochMs:String(e.getTime()),nowIso:e.toISOString(),userRequest:r}});return QA(n,e)}catch(n){return console.error(n),{}}}function QA(t,e=new Date){let r=bp(t.startTime),n=bp(t.endTime),o=YA(t.period);if(o){if(r!==void 0&&n!==void 0&&r<n)return{period:o,startTime:String(r),endTime:String(n)};let s=Fp.has(o);if(!s||n!==void 0&&!eI(n,e.getTime())){let a=n??e.getTime(),i=XA(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 YA(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(Fp.has(`${o}d`))return`${o}d`}return`${r}${n}`}function XA(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 eI(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 tI(t,e,r){let n=pr().find(s=>s.id===t);if(!n)return;let o=await nI(rI(n),r);return o&&sI(o,e)?{capability:n,target:o}:void 0}function rI(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"};case"create-feature-layer":return{destinationType:"portal-content"};case"create-folder":return{destinationType:"portal-content"};default:return{destinationType:"portal-content"}}case"groups":if(e==="featured")return{destinationType:"portal-groups",hash:"featured"};if(e==="organization")return{destinationType:"portal-groups",hash:"organization"};switch(t.id){case"my groups":return{destinationType:"portal-groups",hash:"my"};case"create-group":return{destinationType:"portal-groups"};default:return{destinationType:"portal-groups"}}case"organization":return{destinationType:"portal-org",hash:e,queryParams:r,buttonLabel:t.buttonLabel};default:return}}async function nI(t,e){if(!t||!e||!oI(t))return t;let r=await ZA(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 oI(t){return t.destinationType==="portal-org"&&t.hash==="status"}function sI(t,e){return!e||!!e[t.destinationType]}var aI=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 tI(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 Up(t){return t.length===0?[]:(await ox.getDefault().load(),await lp(t))}var iI=Object.freeze(Object.defineProperty({__proto__:null,generateEmbeddings:Up},Symbol.toStringTag,{value:"Module"}));function lI(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,Ji,ta=0;async function uI(t={}){let e=ta;return ea??=dI(t.embed??pI).then(r=>(e===ta&&(Ji=r),r)).catch(r=>{throw e===ta&&(ea=void 0),r}),await ea}function cI(){return Ji}function Ap(){ta+=1,Ji=void 0,ea=void 0}async function dI(t){let e=mI(),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 pI(t){let{generateEmbeddings:e}=await Promise.resolve().then(()=>iI);return await e(t)}function mI(){return pr().flatMap(t=>lI(t).map(({field:e,text:r})=>({capabilityId:t.id,field:e,text:r})))}var Ip=1.2,vp=.75,fI=60,hI=.65,Bi={description:1,hint:2,title:3},Vi;function gI(){Vi=void 0}async function yI(t,e={}){let r=xI(qp(t)),n=[],o=!1,s;if(t.trim()){let a=e.loadEmbeddings,i=cI();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:II(r,n,e.topN??5)}}function _I(){return Vi??=wI(pr()),Vi}function wI(t){let e=new Map,r=t.map(n=>{let o=new Map;Ki(o,n.title,Bi.title),Ki(o,n.description,Bi.description);for(let s of n.hints)Ki(o,s,Bi.hint);for(let s of o.keys())e.set(s,(e.get(s)??0)+1);return{capability:n,length:bI(o),termFrequencies:o}});return{averageDocumentLength:r.length?r.reduce((n,o)=>n+o.length,0)/r.length:0,documentFrequency:e,documents:r}}function Ki(t,e,r){for(let n of qp(e))t.set(n,(t.get(n)??0)+r)}function bI(t){return[...t.values()].reduce((e,r)=>e+r,0)}function qp(t){return t.toLowerCase().split(/[^a-z0-9]+/u).filter(Boolean)}function xI(t){let e=_I(),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(Bp)}function Tp(t,e){let r=new Map;for(let o of e){let s=AI(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(pr().map(o=>[o.id,o]));return[...r.entries()].flatMap(([o,s])=>{let a=n.get(o);return a&&s>=hI?[{capability:a,score:s}]:[]}).sort(Bp)}function AI(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 Up([t]);if(!e)throw new Error("Expected one query embedding.");return e}function II(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/(fI+a),r==="keyword"?(i.keywordRank=a,i.keywordScore=s):(i.semanticRank=a,i.semanticScore=s),t.set(o.id,i)}}function Bp(t,e){return e.score-t.score||t.capability.id.localeCompare(e.capability.id)}var vI=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 yI(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:TI(r,n.matches)}}catch{return{chosenCapabilityIds:[],outputMessage:"I couldn't look up a Portal page right now. Please try again.",status:"failed",targets:[]}}};function TI(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 Gi=(t,e)=>e??t,Kp=C.Root({...Bn(),chosenCapabilityIds:C({reducer:Gi,default:()=>[]}),retrievalDegraded:C({reducer:Gi,default:()=>""}),targets:C({reducer:Gi,default:()=>[]})}),SI=()=>new ce(Kp).addNode("retrieveNavigationTargets",vI).addNode("chooseNavigationTargets",VA).addNode("respondWithNavigation",aI).addEdge(ue,"retrieveNavigationTargets").addEdge("retrieveNavigationTargets","chooseNavigationTargets").addEdge("chooseNavigationTargets","respondWithNavigation").addEdge("respondWithNavigation",U);function kI(){let t=pr().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 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)
|
|
660
|
+
`}var CI={id:"navigation",name:"Portal Navigation",get description(){return kI()},createGraph:SI,workspace:Kp},EI=Yi`: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 PI(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":return e[r]?.(t.hash,t.queryParams);case"portal-groups":return e[r]?.(t.hash);case"portal-org":return e[r]?.(t.hash,t.queryParams);case"portal-gallery":return e[r];case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId);default:return Vn(r)}}function MI(t){let e=Px.safeParse(t);return e.success?e.data:void 0}function OI(t,e){let r=e.navigation;switch(t.destinationType){case"portal-content":switch(t.hash){case"favorites":return r.openContentFavorites;case"group":return r.openContentGroup;case"living-atlas":return r.openContentLivingAtlas;case"org":return r.openContentOrganization;default:return r.openContent}case"portal-gallery":return r.openGallery;case"portal-groups":switch(t.hash){case"featured":return r.openGroupsFeatured;case"my":return r.openGroupsMy;case"organization":return r.openGroupsOrganization;default:return r.openGroups}case"portal-map-viewer":return r.openMapViewer;case"portal-notebooks":return r.openNotebooks;case"portal-scene-viewer":return r.openSceneViewer;case"portal-org":return r.openOrgSettings;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return Vn(t)}}var Wi=class extends rl{constructor(){super(),this.t9n=sl({blocking:!0}),this.assistantEl=Kn(),this.formEl=Kn(),this.voiceInputEl=Kn(),this.inputEl=Kn(),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=el(),pr()}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=EI}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{pr(this.navigationCapabilities),gI(),Ap(),await uI()}catch(e){console.warn("[arcgis-portal-ai-assistant] embeddings warm-up failed:",e)}}getNavigationAction(e){if(e?.type!==Ep)return;let r=e.data,n=MI(r);if(!n)return;let o=PI(r,this.navigationTargetMap);if(o)return{href:o,targetDetail:r,label:r?.buttonLabel||OI(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)),Xi(Ae`<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?Ae`<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 Ae`<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()})}} ${Gn(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="")}} ${Gn(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??""}} ${Gn(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}} ${Gn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&Ae`<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")&&Ae`<arcgis-assistant-agent .agent=${jA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupCreation")&&Ae`<arcgis-assistant-agent .agent=${$x} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("docAssistant")&&Ae`<arcgis-assistant-agent .agent=${oA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("groupAnalytics")&&Ae`<arcgis-assistant-agent .agent=${SA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.isAgentEnabled("navigation")&&Ae`<arcgis-assistant-agent .agent=${CI} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>`||""}${this.interrupt&&Ae`<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>`}};nl("arcgis-portal-ai-assistant",Wi);return Wi},"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)
|