@esri/solutions-components 5.1.0 → 5.1.1
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/dist/cdn/{LV5KMTCD.js → 224NND54.js} +1 -1
- package/dist/cdn/{Y2MAVMNV.js → 2MDEEI52.js} +1 -1
- package/dist/cdn/{R27S3IDW.js → 3BL4GCSN.js} +1 -1
- package/dist/cdn/{MKSUYITL.js → 3T56IY7B.js} +1 -1
- package/dist/cdn/{SEG43OPO.js → 4G5PYXFM.js} +1 -1
- package/dist/cdn/{CVXDL2AT.js → 4MAH5ULJ.js} +1 -1
- package/dist/cdn/4RWJ22V3.js +2 -0
- package/dist/cdn/{PIAGRMMB.js → 4SYZADNV.js} +47 -47
- package/dist/cdn/{FSHV53TK.js → 4VP3KTLL.js} +1 -1
- package/dist/cdn/{EWS72RFR.js → 5A5W5PLO.js} +1 -1
- package/dist/cdn/{TWN7DOAU.js → 5FW45CM6.js} +1 -1
- package/dist/cdn/{YUI2MSOK.js → 5VUSSAPX.js} +1 -1
- package/dist/cdn/{5UW2NTSN.js → 5YD3IE6V.js} +1 -1
- package/dist/cdn/{TWJ6DAY5.js → 65I4AUS4.js} +1 -1
- package/dist/cdn/{GMAAQEP7.js → 67KMG355.js} +1 -1
- package/dist/cdn/{2R7Y2ZVX.js → 6CVQ3V2G.js} +1 -1
- package/dist/cdn/{RCWYHGZ5.js → 6FNUCCS3.js} +1 -1
- package/dist/cdn/{OYRMCWNZ.js → 7GVLJERR.js} +1 -1
- package/dist/cdn/{BI3I22IR.js → AIM6JKQK.js} +3 -3
- package/dist/cdn/{DIBK4RSG.js → AIZ2P72X.js} +1 -1
- package/dist/cdn/{KSIYOSLP.js → AXEZNIEX.js} +1 -1
- package/dist/cdn/{TZHRYPII.js → B7CVHLVL.js} +1 -1
- package/dist/cdn/{3A3CPQX4.js → B7TH7XYI.js} +1 -1
- package/dist/cdn/{JO6WZKYF.js → BQ2LFMED.js} +1 -1
- package/dist/cdn/{VPXGD2H4.js → CJJEWE3Q.js} +1 -1
- package/dist/cdn/{WNVC3PSY.js → D25JFQEK.js} +1 -1
- package/dist/cdn/D5OMLQMV.js +2 -0
- package/dist/cdn/{6FY64JKN.js → DEATAJID.js} +1 -1
- package/dist/cdn/{LGWAEUZM.js → DGY2VKHA.js} +1 -1
- package/dist/cdn/{5X43GK3C.js → DJXQKOIX.js} +1 -1
- package/dist/cdn/DQPIAF2T.js +3 -0
- package/dist/cdn/{V5UJ5VTY.js → DXQBDTBG.js} +1 -1
- package/dist/cdn/{BIX5DRQP.js → E4OPUBGE.js} +1 -1
- package/dist/cdn/{NXX22DHX.js → E5A7A2YY.js} +1 -1
- package/dist/cdn/{47FRMYZ4.js → ECUD4NU6.js} +1 -1
- package/dist/cdn/EL34IIAJ.js +2 -0
- package/dist/cdn/{Y6JJY3IC.js → ERQAH6G3.js} +1 -1
- package/dist/cdn/{SXTON3QW.js → EWIPITVN.js} +1 -1
- package/dist/cdn/{7O4E4IAA.js → F6LBLCUM.js} +1 -1
- package/dist/cdn/{M6AOD7GG.js → FDNEF4QD.js} +1 -1
- package/dist/cdn/{SXEL7KTE.js → G772MFBV.js} +1 -1
- package/dist/cdn/{O4DB2EXV.js → GSLDFLWZ.js} +1 -1
- package/dist/cdn/{6GBSXKKJ.js → GSOMYPWB.js} +1 -1
- package/dist/cdn/{Q4UI3ZGH.js → GV3GU3O3.js} +1 -1
- package/dist/cdn/{PUYJYHQM.js → GYVIOOMC.js} +1 -1
- package/dist/cdn/{PM4EFNB2.js → HMZ4VIJQ.js} +1 -1
- package/dist/cdn/{G4V4JPFI.js → HOSSEVH5.js} +1 -1
- package/dist/cdn/{RRWG2OJP.js → HQIM7CQS.js} +1 -1
- package/dist/cdn/{IXRFWVBT.js → IGY23J7D.js} +1 -1
- package/dist/cdn/{56DNSWXG.js → IVMHEGLY.js} +1 -1
- package/dist/cdn/{F4MS4NQL.js → JB5XLSNA.js} +1 -1
- package/dist/cdn/{IAEFPE3L.js → JF2ASXUT.js} +1 -1
- package/dist/cdn/{7QKF26VG.js → JGSZS6VC.js} +1 -1
- package/dist/cdn/{D22STVK5.js → JKUPRPWA.js} +1 -1
- package/dist/cdn/{2TEBTKD4.js → K5EP7XDM.js} +1 -1
- package/dist/cdn/{BOFA5RH7.js → K6GC6RUA.js} +1 -1
- package/dist/cdn/{SJLSYFK3.js → KENYVRIH.js} +1 -1
- package/dist/cdn/{CLHUIZMU.js → KLFAQLC6.js} +1 -1
- package/dist/cdn/{5IDPOFIN.js → KLZWOBGK.js} +1 -1
- package/dist/cdn/{XQ7SXIHI.js → KPEPW4QL.js} +1 -1
- package/dist/cdn/{3JCHYXHA.js → KPKJ2OVD.js} +1 -1
- package/dist/cdn/{BHLMO6KY.js → KWOBLDUS.js} +1 -1
- package/dist/cdn/{463CZQF6.js → KXANPOG5.js} +1 -1
- package/dist/cdn/LADUP3BG.js +2 -0
- package/dist/cdn/{HOCCKT72.js → LIEHXKWK.js} +1 -1
- package/dist/cdn/{XKFX43FE.js → LKVPVQIC.js} +1 -1
- package/dist/cdn/{GUSPFJUQ.js → LQFA6HOT.js} +1 -1
- package/dist/cdn/{UCYR537P.js → LRGW6G5E.js} +1 -1
- package/dist/cdn/{H4LZV33O.js → LSMP2ZCO.js} +1 -1
- package/dist/cdn/{5LSNDSHW.js → M5VGNDPK.js} +1 -1
- package/dist/cdn/{NX7HKBFH.js → MHMM4RFR.js} +1 -1
- package/dist/cdn/{2RL6H5TB.js → MVSQRD5M.js} +1 -1
- package/dist/cdn/MXPZF4RB.js +2 -0
- package/dist/cdn/{ZHCAZ2TH.js → MZOWOFAE.js} +1 -1
- package/dist/cdn/{54A4C4RG.js → N5D7USS3.js} +1 -1
- package/dist/cdn/{7P57UVVG.js → NEZAEPUJ.js} +1 -1
- package/dist/cdn/{SSCE4O7V.js → NQP26Q5H.js} +1 -1
- package/dist/cdn/{3BG6WS6Q.js → NWNUNME7.js} +1 -1
- package/dist/cdn/{HM2QALUN.js → O6IGMQN7.js} +1 -1
- package/dist/cdn/{ZZZPISEE.js → ONAAPGO3.js} +1 -1
- package/dist/cdn/{NIYY6XUQ.js → OSOSX7F3.js} +1 -1
- package/dist/cdn/{QEUKNYOL.js → OTTBXOCQ.js} +1 -1
- package/dist/cdn/{UIZL3C3H.js → OU4VLS5H.js} +1 -1
- package/dist/cdn/{BT6SXXE2.js → OYMJFSWN.js} +1 -1
- package/dist/cdn/{MIV34H66.js → P2QNOVPZ.js} +1 -1
- package/dist/cdn/{SWY74BKB.js → P4ZYEBFM.js} +1 -1
- package/dist/cdn/{2AWUR4ZA.js → P734JXTN.js} +1 -1
- package/dist/cdn/{5N4KGIIY.js → PDJXTJHO.js} +1 -1
- package/dist/cdn/{4PDT6TEX.js → PEI3LZZL.js} +1 -1
- package/dist/cdn/{KTW6BSEC.js → PGFW2YO5.js} +1 -1
- package/dist/cdn/{SGQEHPTT.js → Q5LSIHQ4.js} +1 -1
- package/dist/cdn/{MDWJ6JLF.js → Q5XHG472.js} +1 -1
- package/dist/cdn/{BWWX52HV.js → Q6CXYCV6.js} +1 -1
- package/dist/cdn/{37P3IMFV.js → QKPUJ5CZ.js} +1 -1
- package/dist/cdn/{FQTDRS3G.js → QKQXW6OQ.js} +1 -1
- package/dist/cdn/{PLQEDCUG.js → QMQAQSIA.js} +1 -1
- package/dist/cdn/{FFZ2XVRE.js → QTCXH2O3.js} +1 -1
- package/dist/cdn/{4CSMWYIO.js → QWQ535RX.js} +1 -1
- package/dist/cdn/{RLYEATAS.js → R6ANOQU2.js} +1 -1
- package/dist/cdn/{KDDHPA54.js → R7DGMKJ5.js} +1 -1
- package/dist/cdn/{GFBJLNEH.js → RPUUOIRT.js} +1 -1
- package/dist/cdn/{EUI2Y6R4.js → RY7S2ICL.js} +1 -1
- package/dist/cdn/{5FWKODDH.js → S57RXN34.js} +1 -1
- package/dist/cdn/{GSR2GEY7.js → SD3DV4KO.js} +1 -1
- package/dist/cdn/{77753TPX.js → SEII6Y3C.js} +1 -1
- package/dist/cdn/{I4QWYULN.js → SUOJTOE2.js} +1 -1
- package/dist/cdn/{HIB4BVGK.js → SWUMBQ6T.js} +1 -1
- package/dist/cdn/{6WNKGSHD.js → TDDVICGP.js} +1 -1
- package/dist/cdn/{KRP5SGSU.js → US5ONKMV.js} +1 -1
- package/dist/cdn/{BXSBR2GT.js → V24CDHGH.js} +1 -1
- package/dist/cdn/{376KPQCJ.js → VEBBZ2RS.js} +1 -1
- package/dist/cdn/{XYKQ6M25.js → VIZY55AV.js} +1 -1
- package/dist/cdn/{KFRHOPZY.js → VNYXOWZX.js} +113 -113
- package/dist/cdn/{AZKNC2SR.js → VPHEAUEZ.js} +1 -1
- package/dist/cdn/{4SORDX5Z.js → VTRC64F6.js} +1 -1
- package/dist/cdn/{FSF3T3OT.js → VX3K6KJB.js} +1 -1
- package/dist/cdn/{FYJMHXWV.js → VXIWNY5G.js} +1 -1
- package/dist/cdn/{743J2ZUC.js → VZ2ZZK3Y.js} +1 -1
- package/dist/cdn/{X257ACPD.js → W3SEKNJO.js} +1 -1
- package/dist/cdn/{JHOJZDXC.js → WJRVHF3G.js} +1 -1
- package/dist/cdn/WNM5Z4SM.js +2 -0
- package/dist/cdn/{AIM7NSD3.js → WZHA7MTK.js} +1 -1
- package/dist/cdn/{VKHBBAXO.js → XA6ZDTKA.js} +1 -1
- package/dist/cdn/{X3YRR4BO.js → XDLYXP3W.js} +58 -58
- package/dist/cdn/{ARFBMFQW.js → XXRBPKMI.js} +1 -1
- package/dist/cdn/{INLWMPGE.js → XYAVR2MM.js} +1 -1
- package/dist/cdn/{6HZBPFHA.js → XYJU325L.js} +1 -1
- package/dist/cdn/{NNY2YF2L.js → Y3PEQHDX.js} +1 -1
- package/dist/cdn/{4RCC4KA2.js → Y7Z6LFBH.js} +1 -1
- package/dist/cdn/YJ3DKEEZ.js +2 -0
- package/dist/cdn/{HKFXHTYU.js → YVNBCXBJ.js} +1 -1
- package/dist/cdn/{VUXNHQGR.js → Z324WI3X.js} +1 -1
- package/dist/cdn/{A6ZTIX3P.js → ZSATEDPE.js} +1 -1
- package/dist/cdn/{LO35PCP7.js → ZX5GQTIE.js} +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/converter.js +88 -88
- package/dist/chunks/interfaces.js +19 -19
- package/dist/chunks/runtime.js +2 -2
- package/dist/chunks/solution-builder-assistant.js +1 -1
- package/dist/components/arcgis-solutions-assistant/customElement.js +331 -321
- package/dist/components/create-feature/customElement.js +23 -18
- package/dist/components/create-related-feature/customElement.js +8 -6
- package/dist/components/layer-table/customElement.js +1 -1
- package/dist/components/map-tools/customElement.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/solutions-components_commit.txt +4 -7
- package/package.json +5 -5
- package/dist/cdn/E3F63VW4.js +0 -2
- package/dist/cdn/F7XCLL7U.js +0 -3
- package/dist/cdn/HIPZRG2Q.js +0 -2
- package/dist/cdn/IXPNZCW6.js +0 -2
- package/dist/cdn/J3SDL3LR.js +0 -2
- package/dist/cdn/KR2PPIBX.js +0 -2
- package/dist/cdn/QPHNKFC6.js +0 -2
- package/dist/cdn/S4GBMN37.js +0 -2
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import{d as
|
|
2
|
+
import{d as wr,e as ro,f as Fi,g as ji,h as zi}from"./NQH7ZZWD.js";import{a as Di}from"./MHMM4RFR.js";import{a as lc,b as cc,c as uc,f as is,g as as,j as dc}from"./BSIPKI63.js";import c from"./4RWJ22V3.js";import a from"./TK5EXRZL.js";import{b as zl,c as Ul}from"./2B4SGB3I.js";import{b as Si}from"./RLSY4VUQ.js";import"./CGQALCTZ.js";import{a as jl}from"./AIZ2P72X.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as Jl,Aa as ic,Ba as es,Ca as ts,Da as rs,Db as os,Ea as ns,Eb as ss,Fa as _r,Fb as fe,Ga as b,Ha as L,Ia as Ni,J as Wl,Ja as Li,K as xe,L as Hl,M as Wo,N as Ei,O as ki,P as Ho,Q as Xn,R as B,S as Oi,T as j,Ta as E,U as Be,V as at,W as Vo,X as Vl,Y as Gl,Z as Pi,_ as Go,a as me,aa as Zl,b as K,ba as eo,ca as Jo,da as Ql,ea as Yl,fa as Xl,g as Kl,ga as Zo,ha as ec,ia as Pt,j as qe,ja as Mi,k as Ot,ka as Qo,la as N,ma as x,mb as ac,na as Mt,oa as lt,pa as tc,qa as Yo,ra as rc,s as Ko,sa as nc,ta as Xo,ua as Ri,va as yr,wa as $i,xa as oc,y as Yn,ya as sc,zb as to}from"./VNYXOWZX.js";import"./TEHBW75B.js";import"./RSPNBIIE.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./36LRAUE4.js";import"./JMY4B4WQ.js";import"./VQ5ZAQUF.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./6ERMTA3J.js";import"./GF4QELNV.js";import{l as ql,v as Ci}from"./3TAQSXLA.js";import"./PY6RTQDR.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as Fl}from"./YJ3DKEEZ.js";import{F as Nl,G as Ll,H as Dl,L as Ti,h as kl,i as it,k as Ol,l as vi,q as Ii,t as Pl,w as Ml,x as Rl,y as $l}from"./T3EPRHTT.js";import{c as El}from"./EXBEKVP5.js";export default $arcgis.t(([yl,HW,GW,Jd,Mg,Rg,Wg,e2,r2,uJ,uA,fp,mr,Za,Ap,,hp,Jg,{addressToLocations:Zg},Qg,Yg,xp,{createRenderer:Xg},{getSchemesByTag:ey,getSchemes:ty},{getBackgroundColorTheme:gp},{createAgeRenderer:ry,createContinuousRenderer:ny},{getSchemesByTag:il},{createContinuousRenderer:oy},{createRenderer:sy},{getSchemesByTag:iy},{createRenderer:ay},{getSchemesByTag:ly},{createRenderer:cy},{getSchemesByTag:uy},{createRenderer:dy},{getSchemesByTag:py},{createAgeRenderer:my,createContinuousRenderer:fy},{createRenderer:hy},{getSchemesByTag:gy},yy,vp,Ip,{formatDateOnly:_y,convertDateFormatToIntlOptions:Ys,formatTimeOnly:wy,formatDate:yp},by,Ay,xy,vy,Iy,Tp,,{fetchKnowledgeGraph:_p,executeQueryStreaming:Ty,executeSearchStreaming:Sy},Cy,,,,,,,,,,,,,,,,,,,,,,,,,dG,mG,,,,,,,,,,,,,TA,Up,SA,DJ,jJ,KA,WA,{r:Bl},{r:Qn}])=>{var no=class extends $l{constructor(e){if(super(e),this.it=vi,e.type!==Ml.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===vi||e==null)return this._t=void 0,this.it=e;if(e===Ol)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;let r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};no.directiveName="unsafeHTML",no.resultType=1;var pc=Rl(no);var d=b;async function ls(t,e,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
|
|
3
3
|
|
|
4
4
|
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
5
5
|
|
|
6
6
|
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
7
7
|
|`,`
|
|
8
8
|
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
9
|
-
`].join(" "));let n=await Zl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var J=async(t,e)=>{await ls("trace_message",t,e)},ge=async(t,e)=>{await ls("graph_ux_suggestion",t,e)};var cm={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"}},Rv=Object.keys(cm);var
|
|
9
|
+
`].join(" "));let n=await Zl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var J=async(t,e)=>{await ls("trace_message",t,e)},ge=async(t,e)=>{await ls("graph_ux_suggestion",t,e)};var cm={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"}},Rv=Object.keys(cm);var Bi=Symbol.for("langgraph-zod");Bi in globalThis||(globalThis[Bi]=new WeakSet);function hc(t){let e=globalThis[Bi];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return ss(r,{jsonSchemaExtra:n})},reducer(n,o){return ss(r,{default:Qo(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{hc(x.ZodType.prototype),hc(b.ZodType.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var gc=class extends Yl{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)}},mm=new gc(os);var km=x.function().args(x.custom()).returns(x.union([x.boolean(),x.promise(x.boolean())])),Om=x.function().args(x.custom(),x.custom(),x.custom()).returns(x.union([x.string(),x.promise(x.string())])),Pm=["approve","edit","reject"],Mm=x.enum(Pm),Rm=x.object({allowedDecisions:x.array(Mm),description:x.union([x.string(),Om]).optional(),argsSchema:x.record(x.any()).optional(),when:km.optional()}),qS=x.object({interruptOn:x.record(x.union([x.boolean(),Rm])).optional(),descriptionPrefix:x.string().default("Tool execution requires approval")});var Lm=`<role>
|
|
10
10
|
Context Extraction Assistant
|
|
11
11
|
</role>
|
|
12
12
|
|
|
@@ -32,23 +32,23 @@ Respond ONLY with the extracted context. Do not include any additional informati
|
|
|
32
32
|
<messages>
|
|
33
33
|
Messages to summarize:
|
|
34
34
|
{messages}
|
|
35
|
-
</messages>`;var Dm=
|
|
35
|
+
</messages>`;var Dm=x.function().args(x.array(x.custom())).returns(x.union([x.number(),x.promise(x.number())])),Ji=x.object({fraction:x.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().positive("Tokens must be greater than 0").optional(),messages:x.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"}),Tc=x.object({fraction:x.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:x.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"}),iC=x.object({model:x.custom(),trigger:x.union([Ji,x.array(Ji)]).optional(),keep:Tc.optional(),tokenCounter:Dm.optional(),summaryPrompt:x.string().default(Lm),trimTokensToSummarize:x.number().optional(),summaryPrefix:x.string().optional(),maxTokensBeforeSummary:x.number().optional(),messagesToKeep:x.number().optional()});var yC=x.object({model:x.string().or(x.instanceof(rc)).optional(),systemPrompt:x.string().optional(),maxTools:x.number().optional(),alwaysInclude:x.array(x.string()).optional()});var IC=x.object({applyToInput:x.boolean().optional(),applyToOutput:x.boolean().optional(),applyToToolResults:x.boolean().optional()});var kC=x.object({rules:x.record(x.string(),x.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Fm=["continue","error","end"],jm="continue";var zm=x.enum(Fm).default(jm);x.object({toolName:x.string().optional(),threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:zm});var zC=x.object({threadToolCallCount:x.record(x.string(),x.number()).default({}),runToolCallCount:x.record(x.string(),x.number()).default({})});var Um=x.enum(["pending","in_progress","completed"]).describe("Status of the todo"),qm=x.object({content:x.string().describe("Content of the todo item"),status:Um}),GC=x.object({todos:x.array(qm).default([])});var XC=x.object({threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:x.enum(["error","end"]).optional()}),eE=x.object({threadModelCallCount:x.number().default(0),runModelCallCount:x.number().default(0)});var cs=x.object({maxRetries:x.number().min(0).default(2),retryOn:x.union([x.function().args(x.instanceof(Error)).returns(x.boolean()),x.array(x.custom())]).default(()=>()=>!0),backoffFactor:x.number().min(0).default(2),initialDelayMs:x.number().min(0).default(1e3),maxDelayMs:x.number().min(0).default(6e4),jitter:x.boolean().default(!0)});var fE=x.object({onFailure:x.union([x.literal("error"),x.literal("continue"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(cs);var xE=x.object({tools:x.array(x.union([x.custom(),x.custom(),x.string()])).optional(),onFailure:x.union([x.literal("error"),x.literal("continue"),x.literal("raise"),x.literal("return_message"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(cs);var DE=x.object({enableCaching:x.boolean().optional(),ttl:x.enum(["5m","1h"]).optional(),minMessagesToCache:x.number().optional(),unsupportedModelBehavior:x.enum(["ignore","warn","raise"]).optional()});var UE=x.object({enableCaching:x.boolean().optional(),ttl:x.enum(["5m","1h"]).optional(),minMessagesToCache:x.number().optional(),unsupportedModelBehavior:x.enum(["ignore","warn","raise"]).optional()});function oo(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
36
36
|
|
|
37
37
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
38
|
-
`,t}function k(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 Ji=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Ji=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 so(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var io=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var C=class extends Error{},W=class t extends C{constructor(e,r,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 ct({message:n,cause:io(r)});let s=r?.error;return e===400?new br(e,s,n,o):e===401?new xr(e,s,n,o):e===403?new Ar(e,s,n,o):e===404?new vr(e,s,n,o):e===409?new Ir(e,s,n,o):e===422?new Tr(e,s,n,o):e===429?new Sr(e,s,n,o):e>=500?new Cr(e,s,n,o):new t(e,s,n,o)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends W{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Me=class extends ct{constructor({message:e}={}){super({message:e??"Request timed out."})}},br=class extends W{},xr=class extends W{},Ar=class extends W{},vr=class extends W{},Ir=class extends W{},Tr=class extends W{},Sr=class extends W{},Cr=class extends W{},Er=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},kr=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},$t=class extends W{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let i=r;s=i.error;let a=i.error_description;a&&typeof a=="string"?o=a:s&&(o=s)}super(e,r,o,n),this.error_code=s}},ao=class extends C{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Jm=/^[a-z][a-z0-9+.-]*:/i,kc=t=>Jm.test(t),ue=t=>(ue=Array.isArray,ue(t)),Zi=ue;function us(t){return typeof t!="object"?{}:t??{}}function Qi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Oc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function lo(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Pc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var Mc=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var ut="6.44.0";var Lc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Zm(){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 Qm=()=>{let t=Zm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ut,"X-Stainless-OS":$c(Deno.build.os),"X-Stainless-Arch":Rc(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":$c(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Rc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ym();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 Ym(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var Rc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$c=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"),Nc,Dc=()=>Nc??(Nc=Qm());function ds(){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 Yi(...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 ps(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Yi({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Xi(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 ea(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 jc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var ta="RFC3986",ra=t=>String(t),na={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ra},zc="RFC1738";var ms=(t,e)=>(ms=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ms(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var oa=1024,Uc=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=oa){let c=s.length>=oa?s.slice(a,a+oa):s,l=[];for(let u=0;u<c.length;++u){let m=c.charCodeAt(u);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===zc&&(m===40||m===41)){l[l.length]=c.charAt(u);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}u+=1,m=65536+((m&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&63]}i+=l.join("")}return i};function qc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function sa(t,e){if(ue(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Kc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Wc=function(t,e){Array.prototype.push.apply(t,ue(e)?e:[e])},Bc,ee={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Uc,encodeValuesOnly:!1,format:ta,formatter:ra,indices:!1,serializeDate(t){return(Bc??(Bc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function ef(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var ia={};function Hc(t,e,r,n,o,s,i,a,c,l,u,m,f,h,w,x,I,g){let v=t,S=g,L=0,z=!1;for(;(S=S.get(ia))!==void 0&&!z;){let Q=S.get(t);if(L+=1,typeof Q<"u"){if(Q===L)throw new RangeError("Cyclic object value");z=!0}typeof S.get(ia)>"u"&&(L=0)}if(typeof l=="function"?v=l(e,v):v instanceof Date?v=f?.(v):r==="comma"&&ue(v)&&(v=sa(v,function(Q){return Q instanceof Date?f?.(Q):Q})),v===null){if(s)return c&&!x?c(e,ee.encoder,I,"key",h):e;v=""}if(ef(v)||qc(v)){if(c){let Q=x?e:c(e,ee.encoder,I,"key",h);return[w?.(Q)+"="+w?.(c(v,ee.encoder,I,"value",h))]}return[w?.(e)+"="+w?.(String(v))]}let O=[];if(typeof v>"u")return O;let U;if(r==="comma"&&ue(v))x&&c&&(v=sa(v,c)),U=[{value:v.length>0?v.join(",")||null:void 0}];else if(ue(l))U=l;else{let Q=Object.keys(v);U=u?Q.sort(u):Q}let q=a?String(e).replace(/\./g,"%2E"):String(e),ne=n&&ue(v)&&v.length===1?q+"[]":q;if(o&&ue(v)&&v.length===0)return ne+"[]";for(let Q=0;Q<U.length;++Q){let X=U[Q],Sl=typeof X=="object"&&typeof X.value<"u"?X.value:v[X];if(i&&Sl===null)continue;let xi=m&&a?X.replace(/\./g,"%2E"):X,am=ue(v)?typeof r=="function"?r(ne,xi):ne:ne+(m?"."+xi:"["+xi+"]");g.set(t,L);let Cl=new WeakMap;Cl.set(ia,g),Wc(O,Hc(Sl,am,r,n,o,s,i,a,r==="comma"&&x&&ue(v)?null:c,l,u,m,f,h,w,x,I,Cl))}return O}function tf(t=ee){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||ee.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=ta;if(typeof t.format<"u"){if(!ms(na,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=na[r],o=ee.filter;(typeof t.filter=="function"||ue(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Kc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=ee.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:ee.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ee.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ee.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ee.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?ee.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ee.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ee.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ee.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ee.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ee.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ee.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ee.strictNullHandling}}function Vc(t,e={}){let r=t,n=tf(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ue(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=Kc[n.arrayFormat],c=a==="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 h=o[f];n.skipNulls&&r[h]===null||Wc(i,Hc(r[h],h,a,c,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 u=i.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),u.length>0?m+u:""}function Gc(t){return Vc(t,{arrayFormat:"brackets"})}function Qc(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 Jc;function Or(t){let e;return(Jc??(e=new globalThis.TextEncoder,Jc=e.encode.bind(e)))(t)}var Zc;function aa(t){let e;return(Zc??(e=new globalThis.TextDecoder,Zc=e.decode.bind(e)))(t)}var ye,_e,Nt=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),k(this,ye,new Uint8Array,"f"),k(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Or(e):e;k(this,ye,Qc([_(this,ye,"f"),r]),"f");let n=[],o;for(;(o=nf(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(o.carriage&&_(this,_e,"f")==null){k(this,_e,o.index,"f");continue}if(_(this,_e,"f")!=null&&(o.index!==_(this,_e,"f")+1||o.carriage)){n.push(aa(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),k(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),k(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?o.preceding-1:o.preceding,i=aa(_(this,ye,"f").subarray(0,s));n.push(i),k(this,ye,_(this,ye,"f").subarray(o.index),"f"),k(this,_e,null,"f")}return n}flush(){return _(this,ye,"f").length?this.decode(`
|
|
38
|
+
`,t}function k(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 Zi=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Zi=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 so(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var io=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var C=class extends Error{},W=class t extends C{constructor(e,r,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 ct({message:n,cause:io(r)});let s=r?.error;return e===400?new Ar(e,s,n,o):e===401?new xr(e,s,n,o):e===403?new vr(e,s,n,o):e===404?new Ir(e,s,n,o):e===409?new Tr(e,s,n,o):e===422?new Sr(e,s,n,o):e===429?new Cr(e,s,n,o):e>=500?new Er(e,s,n,o):new t(e,s,n,o)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ct=class extends W{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Me=class extends ct{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ar=class extends W{},xr=class extends W{},vr=class extends W{},Ir=class extends W{},Tr=class extends W{},Sr=class extends W{},Cr=class extends W{},Er=class extends W{},kr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Or=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},$t=class extends W{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let i=r;s=i.error;let a=i.error_description;a&&typeof a=="string"?o=a:s&&(o=s)}super(e,r,o,n),this.error_code=s}},ao=class extends C{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var Jm=/^[a-z][a-z0-9+.-]*:/i,kc=t=>Jm.test(t),ue=t=>(ue=Array.isArray,ue(t)),Qi=ue;function us(t){return typeof t!="object"?{}:t??{}}function Yi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Oc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function lo(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Pc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var Mc=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var ut="6.44.0";var Lc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Zm(){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 Qm=()=>{let t=Zm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ut,"X-Stainless-OS":$c(Deno.build.os),"X-Stainless-Arch":Rc(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":$c(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Rc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ym();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 Ym(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var Rc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$c=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"),Nc,Dc=()=>Nc??(Nc=Qm());function ds(){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 Xi(...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 ps(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Xi({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 ta(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 jc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var ra="RFC3986",na=t=>String(t),oa={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:na},zc="RFC1738";var ms=(t,e)=>(ms=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ms(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var sa=1024,Uc=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=sa){let c=s.length>=sa?s.slice(a,a+sa):s,l=[];for(let u=0;u<c.length;++u){let m=c.charCodeAt(u);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===zc&&(m===40||m===41)){l[l.length]=c.charAt(u);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}u+=1,m=65536+((m&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&63]}i+=l.join("")}return i};function qc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ia(t,e){if(ue(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Kc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Wc=function(t,e){Array.prototype.push.apply(t,ue(e)?e:[e])},Bc,ee={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Uc,encodeValuesOnly:!1,format:ra,formatter:na,indices:!1,serializeDate(t){return(Bc??(Bc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function ef(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var aa={};function Hc(t,e,r,n,o,s,i,a,c,l,u,m,f,h,w,A,I,g){let v=t,S=g,$=0,z=!1;for(;(S=S.get(aa))!==void 0&&!z;){let Q=S.get(t);if($+=1,typeof Q<"u"){if(Q===$)throw new RangeError("Cyclic object value");z=!0}typeof S.get(aa)>"u"&&($=0)}if(typeof l=="function"?v=l(e,v):v instanceof Date?v=f?.(v):r==="comma"&&ue(v)&&(v=ia(v,function(Q){return Q instanceof Date?f?.(Q):Q})),v===null){if(s)return c&&!A?c(e,ee.encoder,I,"key",h):e;v=""}if(ef(v)||qc(v)){if(c){let Q=A?e:c(e,ee.encoder,I,"key",h);return[w?.(Q)+"="+w?.(c(v,ee.encoder,I,"value",h))]}return[w?.(e)+"="+w?.(String(v))]}let P=[];if(typeof v>"u")return P;let U;if(r==="comma"&&ue(v))A&&c&&(v=ia(v,c)),U=[{value:v.length>0?v.join(",")||null:void 0}];else if(ue(l))U=l;else{let Q=Object.keys(v);U=u?Q.sort(u):Q}let q=a?String(e).replace(/\./g,"%2E"):String(e),ne=n&&ue(v)&&v.length===1?q+"[]":q;if(o&&ue(v)&&v.length===0)return ne+"[]";for(let Q=0;Q<U.length;++Q){let X=U[Q],Sl=typeof X=="object"&&typeof X.value<"u"?X.value:v[X];if(i&&Sl===null)continue;let xi=m&&a?X.replace(/\./g,"%2E"):X,am=ue(v)?typeof r=="function"?r(ne,xi):ne:ne+(m?"."+xi:"["+xi+"]");g.set(t,$);let Cl=new WeakMap;Cl.set(aa,g),Wc(P,Hc(Sl,am,r,n,o,s,i,a,r==="comma"&&A&&ue(v)?null:c,l,u,m,f,h,w,A,I,Cl))}return P}function tf(t=ee){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||ee.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=ra;if(typeof t.format<"u"){if(!ms(oa,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=oa[r],o=ee.filter;(typeof t.filter=="function"||ue(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Kc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=ee.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:ee.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ee.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ee.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ee.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?ee.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ee.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ee.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ee.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ee.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ee.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ee.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ee.strictNullHandling}}function Vc(t,e={}){let r=t,n=tf(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ue(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=Kc[n.arrayFormat],c=a==="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 h=o[f];n.skipNulls&&r[h]===null||Wc(i,Hc(r[h],h,a,c,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 u=i.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),u.length>0?m+u:""}function Gc(t){return Vc(t,{arrayFormat:"brackets"})}function Qc(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 Jc;function Pr(t){let e;return(Jc??(e=new globalThis.TextEncoder,Jc=e.encode.bind(e)))(t)}var Zc;function la(t){let e;return(Zc??(e=new globalThis.TextDecoder,Zc=e.decode.bind(e)))(t)}var ye,_e,Nt=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),k(this,ye,new Uint8Array,"f"),k(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Pr(e):e;k(this,ye,Qc([_(this,ye,"f"),r]),"f");let n=[],o;for(;(o=nf(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(o.carriage&&_(this,_e,"f")==null){k(this,_e,o.index,"f");continue}if(_(this,_e,"f")!=null&&(o.index!==_(this,_e,"f")+1||o.carriage)){n.push(la(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),k(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),k(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?o.preceding-1:o.preceding,i=la(_(this,ye,"f").subarray(0,s));n.push(i),k(this,ye,_(this,ye,"f").subarray(o.index),"f"),k(this,_e,null,"f")}return n}flush(){return _(this,ye,"f").length?this.decode(`
|
|
39
39
|
`):[]}};ye=new WeakMap,_e=new WeakMap;Nt.NEWLINE_CHARS=new Set([`
|
|
40
|
-
`,"\r"]);Nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function nf(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 Yc(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 hs={off:0,error:200,warn:300,info:400,debug:500},
|
|
41
|
-
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*sf(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new C("Attempted to iterate over a response with no body");let r=new
|
|
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]=lf(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function lf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function gs(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return Z(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):Le.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.json();return ua(f,r)}return await r.text()})();return Z(t).debug(`[${n}] response parsed`,We({retryOfRequestLogID:o,url:r.url,status:r.status,body:i,durationMs:Date.now()-s})),i}function ua(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 po,Lt=class t extends Promise{constructor(e,r,n=gs){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,po.set(this,void 0),k(this,po,e,"f")}_thenUnwrap(e){return new t(_(this,po,"f"),this.responsePromise,async(r,n)=>ua(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,po,"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)}};po=new WeakMap;var ys,Pr=class{constructor(e,r,n,o){ys.set(this,void 0),k(this,ys,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 C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,ys,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ys=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},mo=class extends Lt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await gs(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:{...us(this.options.query),after:r}}:null}},D=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:{...us(this.options.query),after:e}}:null}},Y=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:{...us(this.options.query),after:e}}:null}};var uf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},df="urn:ietf:params:oauth:grant-type:token-exchange",_s=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ds()}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:df,subject_token:e,subject_token_type:uf[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 a=await n.text(),c;try{c=JSON.parse(a)}catch{}throw n.status===400||n.status===401||n.status===403?new $t(n.status,c,n.headers):W.generate(n.status,c,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json(),s=o.expires_in||3600,i=Date.now()+s*1e3;return this.cachedToken={token:o.access_token,expiresAt:i},o.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var ma=()=>{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 ma(),new File(t,e??"unknown_file",r)}function fo(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 ws=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",dt=async(t,e)=>da(t.body)?{...t,body:await tu(t.body,e)}:t,pe=async(t,e)=>({...t,body:await tu(t.body,e)}),eu=new WeakMap;function pf(t){let e=typeof t=="function"?t:t.fetch,r=eu.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return eu.set(e,n),n}var tu=async(t,e)=>{if(!await pf(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])=>pa(r,n,o))),r},ru=t=>t instanceof Blob&&"name"in t,mf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||ws(t)||ru(t)),da=t=>{if(mf(t))return!0;if(Array.isArray(t))return t.some(da);if(t&&typeof t=="object"){for(let e in t)if(da(t[e]))return!0}return!1},pa=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()],fo(r)));else if(ws(r))t.append(e,Mr([await new Response(ps(r)).blob()],fo(r)));else if(ru(r))t.append(e,r,fo(r));else if(Array.isArray(r))await Promise.all(r.map(n=>pa(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>pa(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var nu=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",ff=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&nu(t),hf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function ho(t,e,r){if(ma(),t=await t,ff(t))return t instanceof File?t:Mr([await t.arrayBuffer()],t.name);if(hf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Mr(await fa(o),e,r)}let n=await fa(t);if(e||(e=fo(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 fa(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(nu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(ws(t))for await(let r of t)e.push(...await fa(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${gf(t)}`)}return e}function gf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var y=class{constructor(e){this._client=e}};function su(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ou=Object.freeze(Object.create(null)),_f=(t=su)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i=r.reduce((u,m,f)=>{/[?#]/.test(m)&&(o=!0);let h=n[f],w=(o?encodeURIComponent:t)(""+h);return f!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??ou)??ou)?.toString)&&(w=h+"",s.push({start:u.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),u+m+(f===n.length?"":w)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((u,m)=>u.start-m.start),s.length>0){let u=0,m=s.reduce((f,h)=>{let w=" ".repeat(h.start-u),x="^".repeat(h.length);return u=h.start+h.length,f+w+x},"");throw new C(`Path parameters result in path with invalid segments:
|
|
40
|
+
`,"\r"]);Nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function nf(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 Yc(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 hs={off:0,error:200,warn:300,info:400,debug:500},ca=(t,e,r)=>{if(t){if(Oc(hs,t))return t;Z(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(hs))}`)}};function co(){}function fs(t,e,r){return!e||hs[t]>hs[r]?co:e[t].bind(e)}var of={error:co,warn:co,info:co,debug:co},Xc=new WeakMap;function Z(t){let e=t.logger,r=t.logLevel??"off";if(!e)return of;let n=Xc.get(e);if(n&&n[0]===r)return n[1];let o={error:fs("error",e,r),warn:fs("warn",e,r),info:fs("info",e,r),debug:fs("debug",e,r)};return Xc.set(e,[r,o]),o}var We=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var uo,Le=class t{constructor(e,r,n){this.iterator=e,uo.set(this,void 0),this.controller=r,k(this,uo,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,i=n?Z(n):console;async function*a(){if(s)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let l of sf(e,r))if(!c){if(l.data.startsWith("[DONE]")){c=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let u;try{u=JSON.parse(l.data)}catch(m){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),m}if(u&&u.error)throw new W(void 0,u.error,void 0,e.headers);yield o?{event:l.event,data:u}:u}else{let u;try{u=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 W(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}c=!0}catch(l){if(so(l))return;throw l}finally{c||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let a=new Nt,c=ea(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*i(){if(o)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(so(c))return;throw c}finally{a||r.abort()}}return new t(i,r,n)}[(uo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let i=n.next();e.push(i),r.push(i)}return s.shift()}});return[new t(()=>o(e),this.controller,_(this,uo,"f")),new t(()=>o(r),this.controller,_(this,uo,"f"))]}toReadableStream(){let e=this,r;return Xi({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let i=Pr(JSON.stringify(o)+`
|
|
41
|
+
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*sf(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new C("Attempted to iterate over a response with no body");let r=new ua,n=new Nt,o=ea(t.body);for await(let s of af(o))for(let i of n.decode(s)){let a=r.decode(i);a&&(yield a)}for(let s of n.flush()){let i=r.decode(s);i&&(yield i)}}async function*af(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"?Pr(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Yc(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ua=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
42
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=lf(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function lf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function gs(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return Z(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):Le.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.json();return da(f,r)}return await r.text()})();return Z(t).debug(`[${n}] response parsed`,We({retryOfRequestLogID:o,url:r.url,status:r.status,body:i,durationMs:Date.now()-s})),i}function da(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 po,Lt=class t extends Promise{constructor(e,r,n=gs){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,po.set(this,void 0),k(this,po,e,"f")}_thenUnwrap(e){return new t(_(this,po,"f"),this.responsePromise,async(r,n)=>da(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,po,"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)}};po=new WeakMap;var ys,Mr=class{constructor(e,r,n,o){ys.set(this,void 0),k(this,ys,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 C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,ys,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ys=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},mo=class extends Lt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await gs(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},de=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...us(this.options.query),after:r}}:null}},D=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...us(this.options.query),after:e}}:null}},Y=class extends Mr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...us(this.options.query),after:e}}:null}};var uf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},df="urn:ietf:params:oauth:grant-type:token-exchange",_s=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ds()}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:df,subject_token:e,subject_token_type:uf[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 a=await n.text(),c;try{c=JSON.parse(a)}catch{}throw n.status===400||n.status===401||n.status===403?new $t(n.status,c,n.headers):W.generate(n.status,c,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json(),s=o.expires_in||3600,i=Date.now()+s*1e3;return this.cachedToken={token:o.access_token,expiresAt:i},o.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var fa=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Rr(t,e,r){return fa(),new File(t,e??"unknown_file",r)}function fo(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 ws=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",dt=async(t,e)=>pa(t.body)?{...t,body:await tu(t.body,e)}:t,pe=async(t,e)=>({...t,body:await tu(t.body,e)}),eu=new WeakMap;function pf(t){let e=typeof t=="function"?t:t.fetch,r=eu.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return eu.set(e,n),n}var tu=async(t,e)=>{if(!await pf(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])=>ma(r,n,o))),r},ru=t=>t instanceof Blob&&"name"in t,mf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||ws(t)||ru(t)),pa=t=>{if(mf(t))return!0;if(Array.isArray(t))return t.some(pa);if(t&&typeof t=="object"){for(let e in t)if(pa(t[e]))return!0}return!1},ma=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Rr([await r.blob()],fo(r)));else if(ws(r))t.append(e,Rr([await new Response(ps(r)).blob()],fo(r)));else if(ru(r))t.append(e,r,fo(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ma(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>ma(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var nu=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",ff=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&nu(t),hf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function ho(t,e,r){if(fa(),t=await t,ff(t))return t instanceof File?t:Rr([await t.arrayBuffer()],t.name);if(hf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Rr(await ha(o),e,r)}let n=await ha(t);if(e||(e=fo(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Rr(n,e,r)}async function ha(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(nu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(ws(t))for await(let r of t)e.push(...await ha(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${gf(t)}`)}return e}function gf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var y=class{constructor(e){this._client=e}};function su(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ou=Object.freeze(Object.create(null)),_f=(t=su)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i=r.reduce((u,m,f)=>{/[?#]/.test(m)&&(o=!0);let h=n[f],w=(o?encodeURIComponent:t)(""+h);return f!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??ou)??ou)?.toString)&&(w=h+"",s.push({start:u.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),u+m+(f===n.length?"":w)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((u,m)=>u.start-m.start),s.length>0){let u=0,m=s.reduce((f,h)=>{let w=" ".repeat(h.start-u),A="^".repeat(h.length);return u=h.start+h.length,f+w+A},"");throw new C(`Path parameters result in path with invalid segments:
|
|
43
43
|
${s.map(f=>f.error).join(`
|
|
44
44
|
`)}
|
|
45
45
|
${i}
|
|
46
|
-
${m}`)}return i},p=_f(su);var Dt=class extends y{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function go(t){return t!==void 0&&"function"in t&&t.function!==void 0}function au(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function yo(t){return t?.$brand==="auto-parseable-response-format"}function Ft(t){return t?.$brand==="auto-parseable-tool"}function lu(t,e){return!e||!ha(e)?{...t,choices:t.choices.map(r=>(uu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:_o(t,e)}function _o(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Er;if(n.finish_reason==="content_filter")throw new kr;return uu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>xf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?bf(e,n.message.content):null}}});return{...t,choices:r}}function bf(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 xf(t,e){let r=t.tools?.find(n=>go(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ft(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function cu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>go(n)&&n.function?.name===e.function.name);return go(r)&&(Ft(r)||r?.function.strict||!1)}function ha(t){return yo(t.response_format)?!0:t.tools?.some(e=>Ft(e)||e.type==="function"&&e.function.strict===!0)??!1}function uu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function du(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Rr=t=>t?.role==="assistant",ga=t=>t?.role==="tool";var ya,bs,xs,wo,bo,As,xo,He,Ao,vs,Is,$r,pu,pt=class{constructor(){ya.add(this),this.controller=new AbortController,bs.set(this,void 0),xs.set(this,()=>{}),wo.set(this,()=>{}),bo.set(this,void 0),As.set(this,()=>{}),xo.set(this,()=>{}),He.set(this,{}),Ao.set(this,!1),vs.set(this,!1),Is.set(this,!1),$r.set(this,!1),k(this,bs,new Promise((e,r)=>{k(this,xs,e,"f"),k(this,wo,r,"f")}),"f"),k(this,bo,new Promise((e,r)=>{k(this,As,e,"f"),k(this,xo,r,"f")}),"f"),_(this,bs,"f").catch(()=>{}),_(this,bo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,ya,"m",pu).bind(this))},0)}_connected(){this.ended||(_(this,xs,"f").call(this),this._emit("connect"))}get ended(){return _(this,Ao,"f")}get errored(){return _(this,vs,"f")}get aborted(){return _(this,Is,"f")}abort(){this.controller.abort()}on(e,r){return(_(this,He,"f")[e]||(_(this,He,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,He,"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,He,"f")[e]||(_(this,He,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{k(this,$r,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){k(this,$r,!0,"f"),await _(this,bo,"f")}_emit(e,...r){if(_(this,Ao,"f"))return;e==="end"&&(k(this,Ao,!0,"f"),_(this,As,"f").call(this));let n=_(this,He,"f")[e];if(n&&(_(this,He,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,$r,"f")&&!n?.length&&Promise.reject(o),_(this,wo,"f").call(this,o),_(this,xo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,$r,"f")&&!n?.length&&Promise.reject(o),_(this,wo,"f").call(this,o),_(this,xo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};bs=new WeakMap,xs=new WeakMap,wo=new WeakMap,bo=new WeakMap,As=new WeakMap,xo=new WeakMap,He=new WeakMap,Ao=new WeakMap,vs=new WeakMap,Is=new WeakMap,$r=new WeakMap,ya=new WeakSet,pu=function(e){if(k(this,vs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new H),e instanceof H)return k(this,Is,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function mu(t){return typeof t.parse=="function"}var he,_a,Ts,wa,ba,xa,fu,hu,Af=10,Nr=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),ga(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Rr(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 C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,he,"m",_a).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",Ts).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",wa).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",ba).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",Ts).call(this);r&&this._emit("finalMessage",r);let n=_(this,he,"m",_a).call(this);n&&this._emit("finalContent",n);let o=_(this,he,"m",wa).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,he,"m",ba).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",_(this,he,"m",xa).call(this))}async _createChatCompletion(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,he,"m",fu).call(this,r);let s=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_o(s,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let o="tool",{tool_choice:s="auto",stream:i,...a}=r,c=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:l=Af}=n||{},u=r.tools.map(h=>{if(Ft(h)){if(!h.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),m={};for(let h of u)h.type==="function"&&(m[h.function.name||h.function.function.name]=h.function);let f="tools"in r?u.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of r.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){let x=(await this._createChatCompletion(e,{...a,tool_choice:s,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!x)throw new C("missing message in ChatCompletion response");if(!x.tool_calls?.length)return;for(let I of x.tool_calls){if(I.type!=="function")continue;let g=I.id,{name:v,arguments:S}=I.function,L=m[v];if(L){if(c&&c!==v){let q=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:g,content:q});continue}}else{let q=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(m).map(ne=>JSON.stringify(ne)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:g,content:q});continue}let z;try{z=mu(L)?await L.parse(S):S}catch(q){let ne=q instanceof Error?q.message:String(q);this._addMessage({role:o,tool_call_id:g,content:ne});continue}let O=await L.function(z,this),U=_(this,he,"m",hu).call(this,O);if(this._addMessage({role:o,tool_call_id:g,content:U}),c)return}}}};he=new WeakSet,_a=function(){return _(this,he,"m",Ts).call(this).content??null},Ts=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Rr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},wa=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Rr(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}}},ba=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ga(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},fu=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},hu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var vo=class t extends Nr{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),Rr(e)&&e.content&&this._emit("content",e.content)}};var se={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},Aa=class extends Error{},va=class extends Error{};function vf(t,e=se.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return If(t.trim(),e)}var If=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Aa(`${f} at position ${n}`)},s=f=>{throw new va(`${f} at position ${n}`)},i=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||se.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||se.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||se.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||se.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||se.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||se.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let f=n,h=!1;for(n++;n<r&&(t[n]!=='"'||h&&t[n-1]==="\\");)h=t[n]==="\\"?!h:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(h)))}catch(w){s(String(w))}else if(se.STR&e)try{return JSON.parse(t.substring(f,n-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&se.OBJ&e)return f;let h=a();m(),n++;try{let w=i();Object.defineProperty(f,h,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(se.OBJ&e)return f;throw w}m(),t[n]===","&&n++}}catch{if(se.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(i()),m(),t[n]===","&&n++}catch{if(se.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){t==="-"&&se.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(se.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(h))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(se.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&se.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 i()},
|
|
48
|
-
${Es(t)}`);if(
|
|
49
|
-
${Es(t)}`);if(Q==null)throw new C(`missing choices[${m}].tool_calls[${
|
|
50
|
-
${Es(t)}`);if(ne==null)throw new C(`missing choices[${m}].tool_calls[${
|
|
51
|
-
${Es(t)}`);return{...q,id:U,type:O,function:{...X,name:Q,arguments:ne}}})}}:{...h,message:{...g,content:w,role:v,refusal:l.refusal??null},finish_reason:u,index:m,logprobs:f}}),created:o,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return lu(c,e)}function Es(t){return JSON.stringify(t)}var Io=class t extends jt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,s)),o}};var Ge=class extends y{constructor(){super(...arguments),this.messages=new Dt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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 du(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>_o(n,e))}runTools(e,r){return e.stream?Io.runTools(this._client,e,r):vo.runTools(this._client,e,r)}stream(e,r){return jt.createChatCompletion(this._client,e,r)}};Ge.Messages=Dt;var ft=class extends y{constructor(){super(...arguments),this.completions=new Ge(this._client)}};ft.Completions=Ge;var Dr=class extends y{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 Fr=class extends y{list(e={},r){return this._client.getAPIList("/organization/audit_logs",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var jr=class extends y{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",D,{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 zr=class extends y{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 Ur=class extends y{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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends y{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",Y,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends y{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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends y{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends y{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`,Y,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends y{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`,Y,{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 y{constructor(){super(...arguments),this.users=new Hr(this._client),this.roles=new Wr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(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",Y,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};ht.Users=Hr;ht.Roles=Wr;var Vr=class extends y{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`,D,{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 Gr=class extends y{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,D,{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 Jr=class extends y{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 Zr=class extends y{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 Qr=class extends y{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 Yr=class extends y{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,D,{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 Xr=class extends y{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`,Y,{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 en=class extends y{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`,D,{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 tn=class extends y{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`,D,{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 rn=class extends y{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`,Y,{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 y{constructor(){super(...arguments),this.roles=new rn(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`,Y,{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=rn;var nn=class extends y{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`,Y,{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 Ut=class extends y{constructor(){super(...arguments),this.roles=new nn(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`,D,{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}})}};Ut.Roles=nn;var ie=class extends y{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new en(this._client),this.apiKeys=new Vr(this._client),this.rateLimits=new Yr(this._client),this.modelPermissions=new Qr(this._client),this.hostedToolPermissions=new Zr(this._client),this.groups=new zt(this._client),this.roles=new Xr(this._client),this.dataRetention=new Jr(this._client),this.spendAlerts=new tn(this._client),this.certificates=new Gr(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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ie.Users=Ut;ie.ServiceAccounts=en;ie.APIKeys=Vr;ie.RateLimits=Yr;ie.ModelPermissions=Qr;ie.HostedToolPermissions=Zr;ie.Groups=zt;ie.Roles=Xr;ie.DataRetention=Jr;ie.SpendAlerts=tn;ie.Certificates=Gr;var on=class extends y{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`,Y,{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 qt=class extends y{constructor(){super(...arguments),this.roles=new on(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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=on;var ae=class extends y{constructor(){super(...arguments),this.auditLogs=new Fr(this._client),this.adminAPIKeys=new Dr(this._client),this.usage=new Kr(this._client),this.invites=new Ur(this._client),this.users=new qt(this._client),this.groups=new ht(this._client),this.roles=new qr(this._client),this.dataRetention=new zr(this._client),this.spendAlerts=new Br(this._client),this.certificates=new jr(this._client),this.projects=new ie(this._client)}};ae.AuditLogs=Fr;ae.AdminAPIKeys=Dr;ae.Usage=Kr;ae.Invites=Ur;ae.Users=qt;ae.Groups=ht;ae.Roles=qr;ae.DataRetention=zr;ae.SpendAlerts=Br;ae.Certificates=jr;ae.Projects=ie;var gt=class extends y{constructor(){super(...arguments),this.organization=new ae(this._client)}};gt.Organization=ae;var yu=Symbol("brand.privateNullableHeaders");function*th(t){if(!t)return;if(yu 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():Zi(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=Zi(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,i]of th(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),r.add(a)):(e.append(s,i),r.delete(a))}}return{[yu]:!0,values:e,nulls:r}};var sn=class extends y{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 an=class extends y{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 ln=class extends y{create(e,r){return this._client.post("/audio/translations",pe({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var De=class extends y{constructor(){super(...arguments),this.transcriptions=new an(this._client),this.translations=new ln(this._client),this.speech=new sn(this._client)}};De.Transcriptions=an;De.Translations=ln;De.Speech=sn;var Bt=class extends y{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 cn=class extends y{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 y{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var dn=class extends y{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 y{constructor(){super(...arguments),this.sessions=new un(this._client),this.transcriptionSessions=new dn(this._client)}};yt.Sessions=un;yt.TranscriptionSessions=dn;var pn=class extends y{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 mn=class extends y{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",D,{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`,D,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var _t=class extends y{constructor(){super(...arguments),this.sessions=new pn(this._client),this.threads=new mn(this._client)}};_t.Sessions=pn;_t.Threads=mn;var fn=class extends y{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 hn=class extends y{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:i,...n,headers: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 _u=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var 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 le,Wt,Oa,Fe,ks,Ie,Ht,gn,Kt,Ms,we,Os,Ps,Co,To,So,wu,bu,xu,Au,vu,Iu,Tu,Je=class extends pt{constructor(){super(...arguments),le.add(this),Oa.set(this,[]),Fe.set(this,{}),ks.set(this,{}),Ie.set(this,void 0),Ht.set(this,void 0),gn.set(this,void 0),Kt.set(this,void 0),Ms.set(this,void 0),we.set(this,void 0),Os.set(this,void 0),Ps.set(this,void 0),Co.set(this,void 0)}[(Oa=new WeakMap,Fe=new WeakMap,ks=new WeakMap,Ie=new WeakMap,Ht=new WeakMap,gn=new WeakMap,Kt=new WeakMap,Ms=new WeakMap,we=new WeakMap,Os=new WeakMap,Ps=new WeakMap,Co=new WeakMap,le=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Wt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=Le.fromReadableStream(e,this.controller);for await(let s of o)_(this,le,"m",To).call(this,s);if(o.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Wt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...o,signal:this.controller.signal});this._connected();for await(let c of a)_(this,le,"m",To).call(this,c);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).call(this))}static createThreadAssistantStream(e,r,n){let o=new Wt;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 Wt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Os,"f")}currentRun(){return _(this,Ps,"f")}currentMessageSnapshot(){return _(this,Ie,"f")}currentRunStepSnapshot(){return _(this,Co,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ks,"f"))}async finalRun(){if(await this.done(),!_(this,Ht,"f"))throw Error("Final run was not received.");return _(this,Ht,"f")}async _createThreadAssistantStream(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},i=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of i)_(this,le,"m",To).call(this,a);if(i.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).call(this))}async _createAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...o,signal:this.controller.signal});this._connected();for await(let c of a)_(this,le,"m",To).call(this,c);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).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(lo(s)&&lo(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(i=>typeof i=="string"||typeof i=="number")){s.push(...o);continue}for(let i of o){if(!lo(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s.push(i):s[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};Wt=Je,To=function(e){if(!this.ended)switch(k(this,Os,e,"f"),_(this,le,"m",xu).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,le,"m",Tu).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":_(this,le,"m",bu).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,le,"m",wu).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},So=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Ht,"f"))throw Error("Final run has not been received");return _(this,Ht,"f")},wu=function(e){let[r,n]=_(this,le,"m",vu).call(this,e,_(this,Ie,"f"));k(this,Ie,r,"f"),_(this,ks,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,i=r.content[o.index];if(i&&i.type=="text")this._emit("textDelta",s,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=_(this,gn,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Ie,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Ie,"f"));break}k(this,gn,o.index,"f")}k(this,Kt,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,gn,"f")!==void 0){let o=e.data.content[_(this,gn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,Ie,"f"));break;case"text":this._emit("textDone",o.text,_(this,Ie,"f"));break}}_(this,Ie,"f")&&this._emit("messageDone",e.data),k(this,Ie,void 0,"f")}},bu=function(e){let r=_(this,le,"m",Au).call(this,e);switch(k(this,Co,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,Ms,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),k(this,Ms,s.index,"f"),k(this,we,r.step_details.tool_calls[s.index],"f"),_(this,we,"f")&&this._emit("toolCallCreated",_(this,we,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Co,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),k(this,we,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},xu=function(e){_(this,Oa,"f").push(e),this._emit("event",e)},Au=function(e){switch(e.event){case"thread.run.step.created":return _(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Fe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=Wt.accumulateDelta(r,n.delta);_(this,Fe,"f")[e.data.id]=o}return _(this,Fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":_(this,Fe,"f")[e.data.id]=e.data;break}if(_(this,Fe,"f")[e.data.id])return _(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},vu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let i=r.content[s.index];r.content[s.index]=_(this,le,"m",Iu).call(this,s,i)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Iu=function(e,r){return Wt.accumulateDelta(r,e)},Tu=function(e){switch(k(this,Ps,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":k(this,Ht,e.data,"f"),_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),k(this,we,void 0,"f"));break;case"thread.run.cancelling":break}};var Vt=class extends y{constructor(){super(...arguments),this.steps=new hn(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 Je.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:i}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Je.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 Je.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Vt.Steps=hn;var wt=class extends y{constructor(){super(...arguments),this.runs=new Vt(this._client),this.messages=new fn(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 Je.createThreadAssistantStream(e,this._client.beta.threads,r)}};wt.Runs=Vt;wt.Messages=fn;var Te=class extends y{constructor(){super(...arguments),this.realtime=new yt(this._client),this.chatkit=new _t(this._client),this.assistants=new cn(this._client),this.threads=new wt(this._client)}};Te.Realtime=yt;Te.ChatKit=_t;Te.Assistants=cn;Te.Threads=wt;var Gt=class extends y{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var yn=class extends y{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 Jt=class extends y{constructor(){super(...arguments),this.content=new yn(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}})}};Jt.Content=yn;var bt=class extends y{constructor(){super(...arguments),this.files=new Jt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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=Jt;var _n=class extends y{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`,D,{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 y{constructor(){super(...arguments),this.items=new _n(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=_n;var Zt=class extends y{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&Z(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:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=_u(c)}),i)))}};var wn=class extends y{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 Qt=class extends y{constructor(){super(...arguments),this.outputItems=new wn(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}})}};Qt.OutputItems=wn;var At=class extends y{constructor(){super(...arguments),this.runs=new Qt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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=Qt;var Yt=class extends y{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(),i=await this.retrieve(e);for(;!i.status||!o.has(i.status);)if(await $e(r),i=await this.retrieve(e),Date.now()-s>n)throw new Me({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var bn=class extends y{};var xn=class extends y{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var Xt=class extends y{constructor(){super(...arguments),this.graders=new xn(this._client)}};Xt.Graders=xn;var An=class extends y{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`,D,{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 er=class extends y{constructor(){super(...arguments),this.permissions=new An(this._client)}};er.Permissions=An;var vn=class extends y{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var tr=class extends y{constructor(){super(...arguments),this.checkpoints=new vn(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}})}};tr.Checkpoints=vn;var Se=class extends y{constructor(){super(...arguments),this.methods=new bn(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};Se.Methods=bn;Se.Jobs=tr;Se.Checkpoints=er;Se.Alpha=Xt;var In=class extends y{};var vt=class extends y{constructor(){super(...arguments),this.graderModels=new In(this._client)}};vt.GraderModels=In;var rr=class extends y{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 nr=class extends y{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 or=class extends y{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Tn=class extends y{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 Sn=class extends y{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Ze=class extends y{constructor(){super(...arguments),this.clientSecrets=new Sn(this._client),this.calls=new Tn(this._client)}};Ze.ClientSecrets=Sn;Ze.Calls=Tn;function Su(t,e){return!e||!Mh(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:Pa(t,e)}function Pa(t,e){let r=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:Nh(e,o)};if(o.type==="message"){let s=o.content.map(i=>i.type==="output_text"?{...i,parsed:Ph(e,i.text)}:i);return{...o,content:s}}return o}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||Eo(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let s of o.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function Ph(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Mh(t){return!!yo(t.text?.format)}function Rh(t){return t?.$brand==="auto-parseable-tool"}function $h(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Nh(t,e){let r=$h(t.tools??[],e.name);return{...e,...e,parsed_arguments:Rh(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Eo(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var Cn,Rs,It,$s,Cu,Eu,ku,Ou,Ns=class t extends pt{constructor(e){super(),Cn.add(this),Rs.set(this,void 0),It.set(this,void 0),$s.set(this,void 0),k(this,Rs,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,Cn,"m",Cu).call(this);let s,i=null;"response_id"in r?(s=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=r.starting_after??null):s=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)_(this,Cn,"m",Eu).call(this,a,i);if(s.controller.signal?.aborted)throw new H;return _(this,Cn,"m",ku).call(this)}[(Rs=new WeakMap,It=new WeakMap,$s=new WeakMap,Cn=new WeakSet,Cu=function(){this.ended||k(this,It,void 0,"f")},Eu=function(r,n){if(this.ended)return;let o=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},s=_(this,Cn,"m",Ou).call(this,r);switch(o("event",r),r.type){case"response.output_text.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new C(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new C(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:o(r.type,r);break}},ku=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,It,"f");if(!r)throw new C("request ended without sending any events");k(this,It,void 0,"f");let n=Lh(r,_(this,Rs,"f"));return k(this,$s,n,"f"),n},Ou=function(r){let n=_(this,It,"f");if(!n){if(r.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=k(this,It,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);let s=o.type,i=r.part;s==="message"&&i.type!=="reasoning_text"?o.content.push(i):s==="reasoning"&&i.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(i));break}case"response.output_text.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);if(o.type==="message"){let s=o.content[r.content_index];if(!s)throw new C(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new C(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta}break}case"response.function_call_arguments.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);o.type==="function_call"&&(o.arguments+=r.delta);break}case"response.reasoning_text.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);if(o.type==="reasoning"){let s=o.content?.[r.content_index];if(!s)throw new C(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{k(this,It,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=_(this,$s,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function Lh(t,e){return Su(t,e)}var En=class extends y{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var kn=class extends y{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var je=class extends y{constructor(){super(...arguments),this.inputItems=new En(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"&&Eo(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"&&Eo(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=>Pa(n,e))}stream(e,r){return Ns.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}})}};je.InputItems=En;je.InputTokens=kn;var On=class extends y{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 Pn=class extends y{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 sr=class extends y{constructor(){super(...arguments),this.content=new Pn(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}})}};sr.Content=Pn;var Qe=class extends y{constructor(){super(...arguments),this.content=new On(this._client),this.versions=new sr(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}})}};Qe.Content=On;Qe.Versions=sr;var Mn=class extends y{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,pe({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Tt=class extends y{constructor(){super(...arguments),this.parts=new Mn(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}})}};Tt.Parts=Mn;var Pu=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 Rn=class extends y{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:i}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,i=Math.min(s,r.length),a=this._client,c=r.values(),l=[...n];async function u(f){for(let h of f){let w=await a.files.create({file:h,purpose:"assistants"},o);l.push(w.id)}}let m=Array(i).fill(c).map(u);return await Pu(m),await this.createAndPoll(e,{file_ids:l})}};var $n=class extends y{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(),i=s.data;switch(i.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"failed":case"completed":return i}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(p`/vector_stores/${o}/files/${e}/content`,de,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ye=class extends y{constructor(){super(...arguments),this.files=new $n(this._client),this.fileBatches=new Rn(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}})}};Ye.Files=$n;Ye.FileBatches=Rn;var ir=class extends y{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",D,{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`,dt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Nn,Mu,Ls,ar=class extends y{constructor(){super(...arguments),Nn.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,Nn,"m",Mu).call(this,n);let s=T([r]).values,i=_(this,Nn,"m",Ls).call(this,s,"webhook-signature"),a=_(this,Nn,"m",Ls).call(this,s,"webhook-timestamp"),c=_(this,Nn,"m",Ls).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new Re("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>o)throw new Re("Webhook timestamp is too old");if(l>u+o)throw new Re("Webhook timestamp is too new");let m=i.split(" ").map(x=>x.startsWith("v1,")?x.substring(3):x),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=c?`${c}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let x of m)try{let I=Buffer.from(x,"base64");if(await crypto.subtle.verify("HMAC",w,I,new TextEncoder().encode(h)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}};Nn=new WeakSet,Mu=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Ls=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Ma,Ra,Ds,$u,Wh="workload-identity-auth",P=class{constructor({baseURL:e=ve("OPENAI_BASE_URL"),apiKey:r=ve("OPENAI_API_KEY")??null,adminAPIKey:n=ve("OPENAI_ADMIN_KEY")??null,organization:o=ve("OPENAI_ORG_ID")??null,project:s=ve("OPENAI_PROJECT_ID")??null,webhookSecret:i=ve("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:a,...c}={}){Ma.add(this),Ds.set(this,void 0),this.completions=new Gt(this),this.chat=new ft(this),this.embeddings=new Zt(this),this.files=new Yt(this),this.images=new rr(this),this.audio=new De(this),this.moderations=new or(this),this.models=new nr(this),this.fineTuning=new Se(this),this.graders=new vt(this),this.vectorStores=new Ye(this),this.webhooks=new ar(this),this.beta=new Te(this),this.batches=new Bt(this),this.uploads=new Tt(this),this.admin=new gt(this),this.responses=new je(this),this.realtime=new Ze(this),this.conversations=new xt(this),this.evals=new At(this),this.containers=new bt(this),this.skills=new Qe(this),this.videos=new ir(this);let l={apiKey:r,adminAPIKey:n,organization:o,project:s,webhookSecret:i,workloadIdentity:a,...c,baseURL:e||"https://api.openai.com/v1"};if(r&&a)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!a)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&Lc())throw new C(`It looks like you're running in a browser-like environment.
|
|
46
|
+
${m}`)}return i},p=_f(su);var Dt=class extends y{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function go(t){return t!==void 0&&"function"in t&&t.function!==void 0}function au(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function yo(t){return t?.$brand==="auto-parseable-response-format"}function Ft(t){return t?.$brand==="auto-parseable-tool"}function lu(t,e){return!e||!ga(e)?{...t,choices:t.choices.map(r=>(uu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:_o(t,e)}function _o(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new kr;if(n.finish_reason==="content_filter")throw new Or;return uu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Af(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?bf(e,n.message.content):null}}});return{...t,choices:r}}function bf(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 Af(t,e){let r=t.tools?.find(n=>go(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ft(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function cu(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>go(n)&&n.function?.name===e.function.name);return go(r)&&(Ft(r)||r?.function.strict||!1)}function ga(t){return yo(t.response_format)?!0:t.tools?.some(e=>Ft(e)||e.type==="function"&&e.function.strict===!0)??!1}function uu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function du(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var $r=t=>t?.role==="assistant",ya=t=>t?.role==="tool";var _a,bs,As,wo,bo,xs,Ao,He,xo,vs,Is,Nr,pu,pt=class{constructor(){_a.add(this),this.controller=new AbortController,bs.set(this,void 0),As.set(this,()=>{}),wo.set(this,()=>{}),bo.set(this,void 0),xs.set(this,()=>{}),Ao.set(this,()=>{}),He.set(this,{}),xo.set(this,!1),vs.set(this,!1),Is.set(this,!1),Nr.set(this,!1),k(this,bs,new Promise((e,r)=>{k(this,As,e,"f"),k(this,wo,r,"f")}),"f"),k(this,bo,new Promise((e,r)=>{k(this,xs,e,"f"),k(this,Ao,r,"f")}),"f"),_(this,bs,"f").catch(()=>{}),_(this,bo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,_a,"m",pu).bind(this))},0)}_connected(){this.ended||(_(this,As,"f").call(this),this._emit("connect"))}get ended(){return _(this,xo,"f")}get errored(){return _(this,vs,"f")}get aborted(){return _(this,Is,"f")}abort(){this.controller.abort()}on(e,r){return(_(this,He,"f")[e]||(_(this,He,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,He,"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,He,"f")[e]||(_(this,He,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{k(this,Nr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){k(this,Nr,!0,"f"),await _(this,bo,"f")}_emit(e,...r){if(_(this,xo,"f"))return;e==="end"&&(k(this,xo,!0,"f"),_(this,xs,"f").call(this));let n=_(this,He,"f")[e];if(n&&(_(this,He,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,Nr,"f")&&!n?.length&&Promise.reject(o),_(this,wo,"f").call(this,o),_(this,Ao,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Nr,"f")&&!n?.length&&Promise.reject(o),_(this,wo,"f").call(this,o),_(this,Ao,"f").call(this,o),this._emit("end")}}_emitFinal(){}};bs=new WeakMap,As=new WeakMap,wo=new WeakMap,bo=new WeakMap,xs=new WeakMap,Ao=new WeakMap,He=new WeakMap,xo=new WeakMap,vs=new WeakMap,Is=new WeakMap,Nr=new WeakMap,_a=new WeakSet,pu=function(e){if(k(this,vs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new H),e instanceof H)return k(this,Is,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function mu(t){return typeof t.parse=="function"}var he,wa,Ts,ba,Aa,xa,fu,hu,xf=10,Lr=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),ya(e)&&e.content)this._emit("functionToolCallResult",e.content);else if($r(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 C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,he,"m",wa).call(this)}async finalMessage(){return await this.done(),_(this,he,"m",Ts).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,he,"m",ba).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,he,"m",Aa).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",Ts).call(this);r&&this._emit("finalMessage",r);let n=_(this,he,"m",wa).call(this);n&&this._emit("finalContent",n);let o=_(this,he,"m",ba).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,he,"m",Aa).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",_(this,he,"m",xa).call(this))}async _createChatCompletion(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,he,"m",fu).call(this,r);let s=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_o(s,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let o="tool",{tool_choice:s="auto",stream:i,...a}=r,c=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:l=xf}=n||{},u=r.tools.map(h=>{if(Ft(h)){if(!h.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),m={};for(let h of u)h.type==="function"&&(m[h.function.name||h.function.function.name]=h.function);let f="tools"in r?u.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of r.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){let A=(await this._createChatCompletion(e,{...a,tool_choice:s,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!A)throw new C("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let I of A.tool_calls){if(I.type!=="function")continue;let g=I.id,{name:v,arguments:S}=I.function,$=m[v];if($){if(c&&c!==v){let q=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:g,content:q});continue}}else{let q=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(m).map(ne=>JSON.stringify(ne)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:g,content:q});continue}let z;try{z=mu($)?await $.parse(S):S}catch(q){let ne=q instanceof Error?q.message:String(q);this._addMessage({role:o,tool_call_id:g,content:ne});continue}let P=await $.function(z,this),U=_(this,he,"m",hu).call(this,P);if(this._addMessage({role:o,tool_call_id:g,content:U}),c)return}}}};he=new WeakSet,wa=function(){return _(this,he,"m",Ts).call(this).content??null},Ts=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if($r(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},ba=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if($r(r)&&r?.tool_calls?.length)for(let n=r.tool_calls.length-1;n>=0;n--){let o=r.tool_calls[n];if(o?.type==="function")return o.function}}},Aa=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ya(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},fu=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},hu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var vo=class t extends Lr{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),$r(e)&&e.content&&this._emit("content",e.content)}};var se={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},va=class extends Error{},Ia=class extends Error{};function vf(t,e=se.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return If(t.trim(),e)}var If=(t,e)=>{let r=t.length,n=0,o=f=>{throw new va(`${f} at position ${n}`)},s=f=>{throw new Ia(`${f} at position ${n}`)},i=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||se.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||se.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||se.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||se.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||se.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||se.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let f=n,h=!1;for(n++;n<r&&(t[n]!=='"'||h&&t[n-1]==="\\");)h=t[n]==="\\"?!h:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(h)))}catch(w){s(String(w))}else if(se.STR&e)try{return JSON.parse(t.substring(f,n-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&se.OBJ&e)return f;let h=a();m(),n++;try{let w=i();Object.defineProperty(f,h,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(se.OBJ&e)return f;throw w}m(),t[n]===","&&n++}}catch{if(se.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(i()),m(),t[n]===","&&n++}catch{if(se.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){t==="-"&&se.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(se.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(h))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(se.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&se.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 i()},Ta=t=>vf(t,se.ALL^se.NUM);var te,Ve,Dr,mt,Sa,Ss,Ca,Ea,ka,Cs,Oa,gu,jt=class t extends Lr{constructor(e){super(),te.add(this),Ve.set(this,void 0),Dr.set(this,void 0),mt.set(this,void 0),k(this,Ve,e,"f"),k(this,Dr,[],"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;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,te,"m",Sa).call(this);let s=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let i of s)_(this,te,"m",Ca).call(this,i);if(s.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,te,"m",Cs).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),_(this,te,"m",Sa).call(this),this._connected();let o=Le.fromReadableStream(e,this.controller),s;for await(let i of o)s&&s!==i.id&&this._addChatCompletion(_(this,te,"m",Cs).call(this)),_(this,te,"m",Ca).call(this,i),s=i.id;if(o.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,te,"m",Cs).call(this))}[(Ve=new WeakMap,Dr=new WeakMap,mt=new WeakMap,te=new WeakSet,Sa=function(){this.ended||k(this,mt,void 0,"f")},Ss=function(r){let n=_(this,Dr,"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,Dr,"f")[r.index]=n,n)},Ca=function(r){if(this.ended)return;let n=_(this,te,"m",gu).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index];o.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.delta.content,s.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),o.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let i=_(this,te,"m",Ss).call(this,s);s.finish_reason&&(_(this,te,"m",ka).call(this,s),i.current_tool_call_index!=null&&_(this,te,"m",Ea).call(this,s,i.current_tool_call_index));for(let a of o.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(_(this,te,"m",ka).call(this,s),i.current_tool_call_index!=null&&_(this,te,"m",Ea).call(this,s,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of o.delta.tool_calls??[]){let c=s.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},Ea=function(r,n){if(_(this,te,"m",Ss).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let i=_(this,Ve,"f")?.tools?.find(a=>go(a)&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Ft(i)?i.$parseRaw(s.function.arguments):i?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},ka=function(r){let n=_(this,te,"m",Ss).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,te,"m",Oa).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}))},Cs=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,mt,"f");if(!r)throw new C("request ended without sending any chunks");return k(this,mt,void 0,"f"),k(this,Dr,[],"f"),Tf(r,_(this,Ve,"f"))},Oa=function(){let r=_(this,Ve,"f")?.response_format;return yo(r)?r:null},gu=function(r){var n,o,s,i;let a=_(this,mt,"f"),{choices:c,...l}=r;a?Object.assign(a,l):a=k(this,mt,{...l,choices:[]},"f");for(let{delta:u,finish_reason:m,index:f,logprobs:h=null,...w}of r.choices){let A=a.choices[f];if(A||(A=a.choices[f]={finish_reason:m,index:f,message:{},logprobs:h,...w}),h)if(!A.logprobs)A.logprobs=Object.assign({},h);else{let{content:P,refusal:U,...q}=h;Object.assign(A.logprobs,q),P&&((n=A.logprobs).content??(n.content=[]),A.logprobs.content.push(...P)),U&&((o=A.logprobs).refusal??(o.refusal=[]),A.logprobs.refusal.push(...U))}if(m&&(A.finish_reason=m,_(this,Ve,"f")&&ga(_(this,Ve,"f")))){if(m==="length")throw new kr;if(m==="content_filter")throw new Or}if(Object.assign(A,w),!u)continue;let{content:I,refusal:g,function_call:v,role:S,tool_calls:$,...z}=u;if(Object.assign(A.message,z),g&&(A.message.refusal=(A.message.refusal||"")+g),S&&(A.message.role=S),v&&(A.message.function_call?(v.name&&(A.message.function_call.name=v.name),v.arguments&&((s=A.message.function_call).arguments??(s.arguments=""),A.message.function_call.arguments+=v.arguments)):A.message.function_call=v),I&&(A.message.content=(A.message.content||"")+I,!A.message.refusal&&_(this,te,"m",Oa).call(this)&&(A.message.parsed=Ta(A.message.content))),$){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:P,id:U,type:q,function:ne,...Q}of $){let X=(i=A.message.tool_calls)[P]??(i[P]={});Object.assign(X,Q),U&&(X.id=U),q&&(X.type=q),ne&&(X.function??(X.function={name:ne.name??"",arguments:""})),ne?.name&&(X.function.name=ne.name),ne?.arguments&&(X.function.arguments+=ne.arguments,cu(_(this,Ve,"f"),X)&&(X.function.parsed_arguments=Ta(X.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Tf(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:i,...a}=t,c={...a,id:r,choices:n.map(({message:l,finish_reason:u,index:m,logprobs:f,...h})=>{if(!u)throw new C(`missing finish_reason for choice ${m}`);let{content:w=null,function_call:A,tool_calls:I,...g}=l,v=l.role;if(!v)throw new C(`missing role for choice ${m}`);if(A){let{arguments:S,name:$}=A;if(S==null)throw new C(`missing function_call.arguments for choice ${m}`);if(!$)throw new C(`missing function_call.name for choice ${m}`);return{...h,message:{content:w,function_call:{arguments:S,name:$},role:v,refusal:l.refusal??null},finish_reason:u,index:m,logprobs:f}}return I?{...h,index:m,finish_reason:u,logprobs:f,message:{...g,role:v,content:w,refusal:l.refusal??null,tool_calls:I.map((S,$)=>{let{function:z,type:P,id:U,...q}=S,{arguments:ne,name:Q,...X}=z||{};if(U==null)throw new C(`missing choices[${m}].tool_calls[${$}].id
|
|
48
|
+
${Es(t)}`);if(P==null)throw new C(`missing choices[${m}].tool_calls[${$}].type
|
|
49
|
+
${Es(t)}`);if(Q==null)throw new C(`missing choices[${m}].tool_calls[${$}].function.name
|
|
50
|
+
${Es(t)}`);if(ne==null)throw new C(`missing choices[${m}].tool_calls[${$}].function.arguments
|
|
51
|
+
${Es(t)}`);return{...q,id:U,type:P,function:{...X,name:Q,arguments:ne}}})}}:{...h,message:{...g,content:w,role:v,refusal:l.refusal??null},finish_reason:u,index:m,logprobs:f}}),created:o,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return lu(c,e)}function Es(t){return JSON.stringify(t)}var Io=class t extends jt{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,s)),o}};var Ge=class extends y{constructor(){super(...arguments),this.messages=new Dt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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 du(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>_o(n,e))}runTools(e,r){return e.stream?Io.runTools(this._client,e,r):vo.runTools(this._client,e,r)}stream(e,r){return jt.createChatCompletion(this._client,e,r)}};Ge.Messages=Dt;var ft=class extends y{constructor(){super(...arguments),this.completions=new Ge(this._client)}};ft.Completions=Ge;var Fr=class extends y{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 y{list(e={},r){return this._client.getAPIList("/organization/audit_logs",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var zr=class extends y{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",D,{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 Ur=class extends y{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 qr=class extends y{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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends y{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",Y,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends y{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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends y{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends y{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`,Y,{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 Vr=class extends y{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`,Y,{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 y{constructor(){super(...arguments),this.users=new Vr(this._client),this.roles=new Hr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(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",Y,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};ht.Users=Vr;ht.Roles=Hr;var Gr=class extends y{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`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends y{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,D,{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 Zr=class extends y{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 Qr=class extends y{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 Yr=class extends y{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 Xr=class extends y{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,D,{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 en=class extends y{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`,Y,{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 tn=class extends y{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`,D,{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 rn=class extends y{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`,D,{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 nn=class extends y{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`,Y,{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 y{constructor(){super(...arguments),this.roles=new nn(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`,Y,{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=nn;var on=class extends y{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`,Y,{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 Ut=class extends y{constructor(){super(...arguments),this.roles=new on(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`,D,{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}})}};Ut.Roles=on;var ie=class extends y{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new tn(this._client),this.apiKeys=new Gr(this._client),this.rateLimits=new Xr(this._client),this.modelPermissions=new Yr(this._client),this.hostedToolPermissions=new Qr(this._client),this.groups=new zt(this._client),this.roles=new en(this._client),this.dataRetention=new Zr(this._client),this.spendAlerts=new rn(this._client),this.certificates=new Jr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ie.Users=Ut;ie.ServiceAccounts=tn;ie.APIKeys=Gr;ie.RateLimits=Xr;ie.ModelPermissions=Yr;ie.HostedToolPermissions=Qr;ie.Groups=zt;ie.Roles=en;ie.DataRetention=Zr;ie.SpendAlerts=rn;ie.Certificates=Jr;var sn=class extends y{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`,Y,{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 qt=class extends y{constructor(){super(...arguments),this.roles=new sn(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",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=sn;var ae=class extends y{constructor(){super(...arguments),this.auditLogs=new jr(this._client),this.adminAPIKeys=new Fr(this._client),this.usage=new Wr(this._client),this.invites=new qr(this._client),this.users=new qt(this._client),this.groups=new ht(this._client),this.roles=new Br(this._client),this.dataRetention=new Ur(this._client),this.spendAlerts=new Kr(this._client),this.certificates=new zr(this._client),this.projects=new ie(this._client)}};ae.AuditLogs=jr;ae.AdminAPIKeys=Fr;ae.Usage=Wr;ae.Invites=qr;ae.Users=qt;ae.Groups=ht;ae.Roles=Br;ae.DataRetention=Ur;ae.SpendAlerts=Kr;ae.Certificates=zr;ae.Projects=ie;var gt=class extends y{constructor(){super(...arguments),this.organization=new ae(this._client)}};gt.Organization=ae;var yu=Symbol("brand.privateNullableHeaders");function*th(t){if(!t)return;if(yu 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():Qi(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=Qi(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,i]of th(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),r.add(a)):(e.append(s,i),r.delete(a))}}return{[yu]:!0,values:e,nulls:r}};var an=class extends y{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 ln=class extends y{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 cn=class extends y{create(e,r){return this._client.post("/audio/translations",pe({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var De=class extends y{constructor(){super(...arguments),this.transcriptions=new ln(this._client),this.translations=new cn(this._client),this.speech=new an(this._client)}};De.Transcriptions=ln;De.Translations=cn;De.Speech=an;var Bt=class extends y{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 un=class extends y{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 dn=class extends y{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var pn=class extends y{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 y{constructor(){super(...arguments),this.sessions=new dn(this._client),this.transcriptionSessions=new pn(this._client)}};yt.Sessions=dn;yt.TranscriptionSessions=pn;var mn=class extends y{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 fn=class extends y{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",D,{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`,D,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var _t=class extends y{constructor(){super(...arguments),this.sessions=new mn(this._client),this.threads=new fn(this._client)}};_t.Sessions=mn;_t.Threads=fn;var hn=class extends y{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 gn=class extends y{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:i,...n,headers: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 _u=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var 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 le,Wt,Pa,Fe,ks,Ie,Ht,yn,Kt,Ms,we,Os,Ps,Co,To,So,wu,bu,Au,xu,vu,Iu,Tu,Je=class extends pt{constructor(){super(...arguments),le.add(this),Pa.set(this,[]),Fe.set(this,{}),ks.set(this,{}),Ie.set(this,void 0),Ht.set(this,void 0),yn.set(this,void 0),Kt.set(this,void 0),Ms.set(this,void 0),we.set(this,void 0),Os.set(this,void 0),Ps.set(this,void 0),Co.set(this,void 0)}[(Pa=new WeakMap,Fe=new WeakMap,ks=new WeakMap,Ie=new WeakMap,Ht=new WeakMap,yn=new WeakMap,Kt=new WeakMap,Ms=new WeakMap,we=new WeakMap,Os=new WeakMap,Ps=new WeakMap,Co=new WeakMap,le=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Wt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=Le.fromReadableStream(e,this.controller);for await(let s of o)_(this,le,"m",To).call(this,s);if(o.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Wt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...o,signal:this.controller.signal});this._connected();for await(let c of a)_(this,le,"m",To).call(this,c);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).call(this))}static createThreadAssistantStream(e,r,n){let o=new Wt;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 Wt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Os,"f")}currentRun(){return _(this,Ps,"f")}currentMessageSnapshot(){return _(this,Ie,"f")}currentRunStepSnapshot(){return _(this,Co,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,ks,"f"))}async finalRun(){if(await this.done(),!_(this,Ht,"f"))throw Error("Final run was not received.");return _(this,Ht,"f")}async _createThreadAssistantStream(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},i=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of i)_(this,le,"m",To).call(this,a);if(i.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).call(this))}async _createAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...o,signal:this.controller.signal});this._connected();for await(let c of a)_(this,le,"m",To).call(this,c);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",So).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(lo(s)&&lo(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(i=>typeof i=="string"||typeof i=="number")){s.push(...o);continue}for(let i of o){if(!lo(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s.push(i):s[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};Wt=Je,To=function(e){if(!this.ended)switch(k(this,Os,e,"f"),_(this,le,"m",Au).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":_(this,le,"m",Tu).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":_(this,le,"m",bu).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,le,"m",wu).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},So=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Ht,"f"))throw Error("Final run has not been received");return _(this,Ht,"f")},wu=function(e){let[r,n]=_(this,le,"m",vu).call(this,e,_(this,Ie,"f"));k(this,Ie,r,"f"),_(this,ks,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,i=r.content[o.index];if(i&&i.type=="text")this._emit("textDelta",s,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=_(this,yn,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Ie,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Ie,"f"));break}k(this,yn,o.index,"f")}k(this,Kt,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,yn,"f")!==void 0){let o=e.data.content[_(this,yn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,Ie,"f"));break;case"text":this._emit("textDone",o.text,_(this,Ie,"f"));break}}_(this,Ie,"f")&&this._emit("messageDone",e.data),k(this,Ie,void 0,"f")}},bu=function(e){let r=_(this,le,"m",xu).call(this,e);switch(k(this,Co,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,Ms,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),k(this,Ms,s.index,"f"),k(this,we,r.step_details.tool_calls[s.index],"f"),_(this,we,"f")&&this._emit("toolCallCreated",_(this,we,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Co,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),k(this,we,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Au=function(e){_(this,Pa,"f").push(e),this._emit("event",e)},xu=function(e){switch(e.event){case"thread.run.step.created":return _(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Fe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=Wt.accumulateDelta(r,n.delta);_(this,Fe,"f")[e.data.id]=o}return _(this,Fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":_(this,Fe,"f")[e.data.id]=e.data;break}if(_(this,Fe,"f")[e.data.id])return _(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},vu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let i=r.content[s.index];r.content[s.index]=_(this,le,"m",Iu).call(this,s,i)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Iu=function(e,r){return Wt.accumulateDelta(r,e)},Tu=function(e){switch(k(this,Ps,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":k(this,Ht,e.data,"f"),_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),k(this,we,void 0,"f"));break;case"thread.run.cancelling":break}};var Vt=class extends y{constructor(){super(...arguments),this.steps=new gn(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 Je.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:i}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Je.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 Je.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Vt.Steps=gn;var wt=class extends y{constructor(){super(...arguments),this.runs=new Vt(this._client),this.messages=new hn(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 Je.createThreadAssistantStream(e,this._client.beta.threads,r)}};wt.Runs=Vt;wt.Messages=hn;var Te=class extends y{constructor(){super(...arguments),this.realtime=new yt(this._client),this.chatkit=new _t(this._client),this.assistants=new un(this._client),this.threads=new wt(this._client)}};Te.Realtime=yt;Te.ChatKit=_t;Te.Assistants=un;Te.Threads=wt;var Gt=class extends y{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var _n=class extends y{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 Jt=class extends y{constructor(){super(...arguments),this.content=new _n(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}})}};Jt.Content=_n;var bt=class extends y{constructor(){super(...arguments),this.files=new Jt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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=Jt;var wn=class extends y{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`,D,{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 At=class extends y{constructor(){super(...arguments),this.items=new wn(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}})}};At.Items=wn;var Zt=class extends y{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&Z(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:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=_u(c)}),i)))}};var bn=class extends y{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 Qt=class extends y{constructor(){super(...arguments),this.outputItems=new bn(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}})}};Qt.OutputItems=bn;var xt=class extends y{constructor(){super(...arguments),this.runs=new Qt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(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=Qt;var Yt=class extends y{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(),i=await this.retrieve(e);for(;!i.status||!o.has(i.status);)if(await $e(r),i=await this.retrieve(e),Date.now()-s>n)throw new Me({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var An=class extends y{};var xn=class extends y{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var Xt=class extends y{constructor(){super(...arguments),this.graders=new xn(this._client)}};Xt.Graders=xn;var vn=class extends y{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`,D,{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 er=class extends y{constructor(){super(...arguments),this.permissions=new vn(this._client)}};er.Permissions=vn;var In=class extends y{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var tr=class extends y{constructor(){super(...arguments),this.checkpoints=new In(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}})}};tr.Checkpoints=In;var Se=class extends y{constructor(){super(...arguments),this.methods=new An(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};Se.Methods=An;Se.Jobs=tr;Se.Checkpoints=er;Se.Alpha=Xt;var Tn=class extends y{};var vt=class extends y{constructor(){super(...arguments),this.graderModels=new Tn(this._client)}};vt.GraderModels=Tn;var rr=class extends y{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 nr=class extends y{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 or=class extends y{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Sn=class extends y{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 Cn=class extends y{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Ze=class extends y{constructor(){super(...arguments),this.clientSecrets=new Cn(this._client),this.calls=new Sn(this._client)}};Ze.ClientSecrets=Cn;Ze.Calls=Sn;function Su(t,e){return!e||!Mh(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:Ma(t,e)}function Ma(t,e){let r=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:Nh(e,o)};if(o.type==="message"){let s=o.content.map(i=>i.type==="output_text"?{...i,parsed:Ph(e,i.text)}:i);return{...o,content:s}}return o}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||Eo(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let s of o.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function Ph(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Mh(t){return!!yo(t.text?.format)}function Rh(t){return t?.$brand==="auto-parseable-tool"}function $h(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Nh(t,e){let r=$h(t.tools??[],e.name);return{...e,...e,parsed_arguments:Rh(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Eo(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var En,Rs,It,$s,Cu,Eu,ku,Ou,Ns=class t extends pt{constructor(e){super(),En.add(this),Rs.set(this,void 0),It.set(this,void 0),$s.set(this,void 0),k(this,Rs,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,En,"m",Cu).call(this);let s,i=null;"response_id"in r?(s=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=r.starting_after??null):s=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)_(this,En,"m",Eu).call(this,a,i);if(s.controller.signal?.aborted)throw new H;return _(this,En,"m",ku).call(this)}[(Rs=new WeakMap,It=new WeakMap,$s=new WeakMap,En=new WeakSet,Cu=function(){this.ended||k(this,It,void 0,"f")},Eu=function(r,n){if(this.ended)return;let o=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},s=_(this,En,"m",Ou).call(this,r);switch(o("event",r),r.type){case"response.output_text.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new C(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new C(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:o(r.type,r);break}},ku=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,It,"f");if(!r)throw new C("request ended without sending any events");k(this,It,void 0,"f");let n=Lh(r,_(this,Rs,"f"));return k(this,$s,n,"f"),n},Ou=function(r){let n=_(this,It,"f");if(!n){if(r.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=k(this,It,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);let s=o.type,i=r.part;s==="message"&&i.type!=="reasoning_text"?o.content.push(i):s==="reasoning"&&i.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(i));break}case"response.output_text.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);if(o.type==="message"){let s=o.content[r.content_index];if(!s)throw new C(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new C(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta}break}case"response.function_call_arguments.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);o.type==="function_call"&&(o.arguments+=r.delta);break}case"response.reasoning_text.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);if(o.type==="reasoning"){let s=o.content?.[r.content_index];if(!s)throw new C(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{k(this,It,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=_(this,$s,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function Lh(t,e){return Su(t,e)}var kn=class extends y{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var On=class extends y{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var je=class extends y{constructor(){super(...arguments),this.inputItems=new kn(this._client),this.inputTokens=new On(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"&&Eo(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"&&Eo(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=>Ma(n,e))}stream(e,r){return Ns.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}})}};je.InputItems=kn;je.InputTokens=On;var Pn=class extends y{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 Mn=class extends y{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 sr=class extends y{constructor(){super(...arguments),this.content=new Mn(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}})}};sr.Content=Mn;var Qe=class extends y{constructor(){super(...arguments),this.content=new Pn(this._client),this.versions=new sr(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}})}};Qe.Content=Pn;Qe.Versions=sr;var Rn=class extends y{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,pe({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Tt=class extends y{constructor(){super(...arguments),this.parts=new Rn(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}})}};Tt.Parts=Rn;var Pu=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 $n=class extends y{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:i}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,i=Math.min(s,r.length),a=this._client,c=r.values(),l=[...n];async function u(f){for(let h of f){let w=await a.files.create({file:h,purpose:"assistants"},o);l.push(w.id)}}let m=Array(i).fill(c).map(u);return await Pu(m),await this.createAndPoll(e,{file_ids:l})}};var Nn=class extends y{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(),i=s.data;switch(i.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"failed":case"completed":return i}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(p`/vector_stores/${o}/files/${e}/content`,de,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ye=class extends y{constructor(){super(...arguments),this.files=new Nn(this._client),this.fileBatches=new $n(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}})}};Ye.Files=Nn;Ye.FileBatches=$n;var ir=class extends y{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",D,{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`,dt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Ln,Mu,Ls,ar=class extends y{constructor(){super(...arguments),Ln.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,Ln,"m",Mu).call(this,n);let s=T([r]).values,i=_(this,Ln,"m",Ls).call(this,s,"webhook-signature"),a=_(this,Ln,"m",Ls).call(this,s,"webhook-timestamp"),c=_(this,Ln,"m",Ls).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new Re("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>o)throw new Re("Webhook timestamp is too old");if(l>u+o)throw new Re("Webhook timestamp is too new");let m=i.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=c?`${c}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of m)try{let I=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",w,I,new TextEncoder().encode(h)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}};Ln=new WeakSet,Mu=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Ls=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Ra,$a,Ds,$u,Wh="workload-identity-auth",O=class{constructor({baseURL:e=ve("OPENAI_BASE_URL"),apiKey:r=ve("OPENAI_API_KEY")??null,adminAPIKey:n=ve("OPENAI_ADMIN_KEY")??null,organization:o=ve("OPENAI_ORG_ID")??null,project:s=ve("OPENAI_PROJECT_ID")??null,webhookSecret:i=ve("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:a,...c}={}){Ra.add(this),Ds.set(this,void 0),this.completions=new Gt(this),this.chat=new ft(this),this.embeddings=new Zt(this),this.files=new Yt(this),this.images=new rr(this),this.audio=new De(this),this.moderations=new or(this),this.models=new nr(this),this.fineTuning=new Se(this),this.graders=new vt(this),this.vectorStores=new Ye(this),this.webhooks=new ar(this),this.beta=new Te(this),this.batches=new Bt(this),this.uploads=new Tt(this),this.admin=new gt(this),this.responses=new je(this),this.realtime=new Ze(this),this.conversations=new At(this),this.evals=new xt(this),this.containers=new bt(this),this.skills=new Qe(this),this.videos=new ir(this);let l={apiKey:r,adminAPIKey:n,organization:o,project:s,webhookSecret:i,workloadIdentity:a,...c,baseURL:e||"https://api.openai.com/v1"};if(r&&a)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!a)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&Lc())throw new C(`It looks like you're running in a browser-like environment.
|
|
52
52
|
|
|
53
53
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
54
54
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -57,15 +57,15 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
57
57
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
58
58
|
|
|
59
59
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
60
|
-
`);this.baseURL=l.baseURL,this.timeout=l.timeout
|
|
61
|
-
`)){let w=h.indexOf(":");w>=0&&(f[h.substring(0,w).trim()]=h.substring(w+1).trim())}l.defaultHeaders=T([f,l.defaultHeaders])}this._options=l,a&&(this._workloadIdentityAuth=new _s(a,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=o,this.project=s,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return 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 Gc(e)}getUserAgent(){return`${this.constructor.name}/JS ${ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ji()}`}makeStatusError(e,r,n,o){return W.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof C?n:new C(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,Ma,"m",$u).call(this)&&n||this.baseURL,s=kc(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!Qi(i)||!Qi(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Lt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:i,url:a,timeout:c}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(i,{url:a,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(Z(this).debug(`[${l}] sending request`,We({retryOfRequestLogID:n,method:o.method,url:a,options:o,headers:i.headers})),o.signal?.aborted)throw new H;let f=o.__security??{bearerAuth:!0},h=new AbortController,w=await this.fetchWithAuth(a,i,c,h,f).catch(io),x=Date.now();if(w instanceof globalThis.Error){let v=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new H;let S=so(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Z(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${v}`),Z(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${v})`,We({retryOfRequestLogID:n,url:a,durationMs:x-m,message:w.message})),this.retryRequest(o,r,n??l);throw Z(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,We({retryOfRequestLogID:n,url:a,durationMs:x-m,message:w.message})),w instanceof $t||w instanceof ao?w:S?new Me:new ct({message:Hh(w),cause:w})}let I=[...w.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,S])=>", "+v+": "+JSON.stringify(S)).join(""),g=`[${l}${u}${I}] ${i.method} ${a} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${x-m}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await ea(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let v=await this.shouldRetry(w);if(r&&v){let q=`retrying, ${r} attempts remaining`;return await ea(w.body),Z(this).info(`${g} - ${q}`),Z(this).debug(`[${l}] response error (${q})`,We({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:x-m})),this.retryRequest(o,r,n??l,w.headers)}let S=v?"error; no more retries left":"error; not retryable";Z(this).info(`${g} - ${S}`);let L=await w.text().catch(q=>io(q).message),z=Mc(L),O=z?void 0:L;throw Z(this).debug(`[${l}] response error (${S})`,We({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:O,durationMs:Date.now()-m})),this.makeStatusError(w.status,z,O,w.headers)}return Z(this).info(g),Z(this).debug(`[${l}] response start`,We({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:x-m})),{response:w,options:o,controller:h,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 mo(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let a=r.headers,c=a.get("Authorization");if(!c||c===`Bearer ${Wh}`){let l=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:i,...a}=r||{},c=this._makeAbort(o);s&&s.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,m={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,i=o?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(s=c)}let a=o?.get("retry-after");if(a&&!s){let c=parseFloat(a);Number.isNaN(c)?s=Date.parse(a)-Date.now():s=c*1e3}if(s===void 0){let c=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await $e(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,i=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:i,defaultBaseURL:a}=n,c=this.buildURL(s,i,a);"timeout"in n&&Pc("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u,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&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let i=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))}:{},...Dc(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=T([r]),o=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,s=!o&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||o?{bodyHeaders:void 0,body:e,isStreamingBody:!s}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ps(e),isStreamingBody:!0}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{..._(this,Ds,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};Ra=P,Ds=new WeakMap,Ma=new WeakSet,$u=function(){return this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=Ra;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=C;P.APIError=W;P.APIConnectionError=ct;P.APIConnectionTimeoutError=Me;P.APIUserAbortError=H;P.NotFoundError=vr;P.ConflictError=Ir;P.RateLimitError=Sr;P.BadRequestError=br;P.AuthenticationError=xr;P.InternalServerError=Cr;P.PermissionDeniedError=Ar;P.UnprocessableEntityError=Tr;P.InvalidWebhookSignatureError=Re;P.toFile=ho;P.Completions=Gt;P.Chat=ft;P.Embeddings=Zt;P.Files=Yt;P.Images=rr;P.Audio=De;P.Moderations=or;P.Models=nr;P.FineTuning=Se;P.Graders=vt;P.VectorStores=Ye;P.Webhooks=ar;P.Beta=Te;P.Batches=Bt;P.Uploads=Tt;P.Admin=gt;P.Responses=je;P.Realtime=Ze;P.Conversations=xt;P.Evals=At;P.Containers=bt;P.Skills=Qe;P.Videos=ir;function Hh(t){if(Vh(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 Vh(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 Gh(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===Me.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===H.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Gh(t)?e=Hl.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=oo(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=oo(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=oo(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=oo(t,"MODEL_NOT_FOUND"):e=t,e}var Ce=t=>t();function Xe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Jh(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 Na(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Zh="LC_AUTOGENERATED";function Ln(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'."),Zh)}function et(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Vo.isInstance(t))throw new Error("Invalid generic chat message");return Jh(t);default:throw new Error(`Unknown message type: ${e}`)}}function Nu(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function tt(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((n||i)&&o&&e)return`${o}/${e}`;if((n||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function La(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Lu(t){let e=Ce(()=>{if(La(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&La(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 Du(){let t=Wl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function rt(t,e=!1,r="1.0.0"){let n=Lu(t),o=Du(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function Fu(t,e){let r;return yr(t)?r=Ni(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 ju(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(zu(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
62
|
-
`)}function zu(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${
|
|
63
|
-
`)}function
|
|
64
|
-
`);case"array":return t.items?`${Fs(t.items,e)}[]`:"any[]";default:return""}}function js(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function Dn(t){return"type"in t&&t.type!=="function"}function Uu(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 qu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function lr(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 zs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Bu(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 Ku(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 Wu(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Hu(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 Vu(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 Gu(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var Zu=Symbol("Let zodToJsonSchema decide on which parser to use"),Ju={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Qu=t=>typeof t=="string"?{...Ju,basePath:["#"],definitions:{},name:t}:{...Ju,basePath:["#"],definitions:{},...t};var ko=t=>"_def"in t?t._def:t;function Yu(t){if(!t)return!0;for(let e in t)return!1;return!0}var Xu=t=>{let e=Qu(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])=>[ko(o),{def:ko(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Da(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function F(t,e,r,n,o){t[e]=r,Da(t,e,n,o)}function ed(){return{}}function td(t,e){let r={type:"array"};return t.type?._def?.typeName!==$.ZodAny&&(r.items=M(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&F(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&F(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(F(r,"minItems",t.exactLength.value,t.exactLength.message,e),F(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function rd(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?F(r,"minimum",n.value,n.message,e):F(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),F(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?F(r,"maximum",n.value,n.message,e):F(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),F(r,"maximum",n.value,n.message,e));break;case"multipleOf":F(r,"multipleOf",n.value,n.message,e);break}return r}function nd(){return{type:"boolean"}}function od(t,e){return M(t.type._def,e)}var sd=(t,e)=>M(t.innerType._def,e);function Fa(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Fa(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 Yh(t,e)}}var Yh=(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":F(r,"minimum",n.value,n.message,e);break;case"max":F(r,"maximum",n.value,n.message,e);break}return r};function id(t,e){return{...M(t.innerType._def,e),default:t.defaultValue()}}function ad(t,e,r){return e.effectStrategy==="input"?M(t.schema._def,e,r):{}}function ld(t){return{type:"string",enum:[...t.values]}}var Xh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function cd(t,e){let r=[M(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),M(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(Xh(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function ud(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 ja,cr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ja===void 0&&(ja=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ja),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 Us(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?eg(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":F(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":F(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":ke(r,cr.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":ke(r,o.regex,o.message,e);break;case"cuid":ke(r,cr.cuid,o.message,e);break;case"cuid2":ke(r,cr.cuid2,o.message,e);break;case"startsWith":ke(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":ke(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":F(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),F(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ke(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":ke(r,cr.emoji,o.message,e);break;case"ulid":{ke(r,cr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ee(r,"binary",o.message,e);break}case"contentEncoding:base64":{F(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ke(r,cr.base64,o.message,e);break}}break}case"nanoid":ke(r,cr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var eg=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}}})):F(t,"format",e,r,n)},ke=(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:dd(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):F(t,"pattern",dd(e,n),r,n)},dd=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",i=!1,a=!1,c=!1;for(let l=0;l<o.length;l++){if(i){s+=o[l],i=!1;continue}if(n.i){if(a){if(o[l].match(/[a-z]/)){c?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),c=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],c=!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
|
|
60
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??$a.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=ca(l.logLevel,"ClientOptions.logLevel",this)??ca(ve("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ds(),k(this,Ds,jc,"f");let m=ve("OPENAI_CUSTOM_HEADERS");if(m){let f={};for(let h of m.split(`
|
|
61
|
+
`)){let w=h.indexOf(":");w>=0&&(f[h.substring(0,w).trim()]=h.substring(w+1).trim())}l.defaultHeaders=T([f,l.defaultHeaders])}this._options=l,a&&(this._workloadIdentityAuth=new _s(a,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=o,this.project=s,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return 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 Gc(e)}getUserAgent(){return`${this.constructor.name}/JS ${ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Zi()}`}makeStatusError(e,r,n,o){return W.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof C?n:new C(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,Ra,"m",$u).call(this)&&n||this.baseURL,s=kc(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!Yi(i)||!Yi(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Lt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:i,url:a,timeout:c}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(i,{url:a,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(Z(this).debug(`[${l}] sending request`,We({retryOfRequestLogID:n,method:o.method,url:a,options:o,headers:i.headers})),o.signal?.aborted)throw new H;let f=o.__security??{bearerAuth:!0},h=new AbortController,w=await this.fetchWithAuth(a,i,c,h,f).catch(io),A=Date.now();if(w instanceof globalThis.Error){let v=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new H;let S=so(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Z(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${v}`),Z(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${v})`,We({retryOfRequestLogID:n,url:a,durationMs:A-m,message:w.message})),this.retryRequest(o,r,n??l);throw Z(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,We({retryOfRequestLogID:n,url:a,durationMs:A-m,message:w.message})),w instanceof $t||w instanceof ao?w:S?new Me:new ct({message:Hh(w),cause:w})}let I=[...w.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,S])=>", "+v+": "+JSON.stringify(S)).join(""),g=`[${l}${u}${I}] ${i.method} ${a} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${A-m}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await ta(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let v=await this.shouldRetry(w);if(r&&v){let q=`retrying, ${r} attempts remaining`;return await ta(w.body),Z(this).info(`${g} - ${q}`),Z(this).debug(`[${l}] response error (${q})`,We({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:A-m})),this.retryRequest(o,r,n??l,w.headers)}let S=v?"error; no more retries left":"error; not retryable";Z(this).info(`${g} - ${S}`);let $=await w.text().catch(q=>io(q).message),z=Mc($),P=z?void 0:$;throw Z(this).debug(`[${l}] response error (${S})`,We({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:P,durationMs:Date.now()-m})),this.makeStatusError(w.status,z,P,w.headers)}return Z(this).info(g),Z(this).debug(`[${l}] response start`,We({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:A-m})),{response:w,options:o,controller:h,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 mo(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let a=r.headers,c=a.get("Authorization");if(!c||c===`Bearer ${Wh}`){let l=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:i,...a}=r||{},c=this._makeAbort(o);s&&s.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,m={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,i=o?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(s=c)}let a=o?.get("retry-after");if(a&&!s){let c=parseFloat(a);Number.isNaN(c)?s=Date.parse(a)-Date.now():s=c*1e3}if(s===void 0){let c=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await $e(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,i=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:i,defaultBaseURL:a}=n,c=this.buildURL(s,i,a);"timeout"in n&&Pc("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u,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&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let i=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))}:{},...Dc(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=T([r]),o=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,s=!o&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||o?{bodyHeaders:void 0,body:e,isStreamingBody:!s}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ps(e),isStreamingBody:!0}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{..._(this,Ds,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};$a=O,Ds=new WeakMap,Ra=new WeakSet,$u=function(){return this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=$a;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=C;O.APIError=W;O.APIConnectionError=ct;O.APIConnectionTimeoutError=Me;O.APIUserAbortError=H;O.NotFoundError=Ir;O.ConflictError=Tr;O.RateLimitError=Cr;O.BadRequestError=Ar;O.AuthenticationError=xr;O.InternalServerError=Er;O.PermissionDeniedError=vr;O.UnprocessableEntityError=Sr;O.InvalidWebhookSignatureError=Re;O.toFile=ho;O.Completions=Gt;O.Chat=ft;O.Embeddings=Zt;O.Files=Yt;O.Images=rr;O.Audio=De;O.Moderations=or;O.Models=nr;O.FineTuning=Se;O.Graders=vt;O.VectorStores=Ye;O.Webhooks=ar;O.Beta=Te;O.Batches=Bt;O.Uploads=Tt;O.Admin=gt;O.Responses=je;O.Realtime=Ze;O.Conversations=At;O.Evals=xt;O.Containers=bt;O.Skills=Qe;O.Videos=ir;function Hh(t){if(Vh(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 Vh(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 Gh(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===Me.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===H.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Gh(t)?e=Hl.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=oo(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=oo(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=oo(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=oo(t,"MODEL_NOT_FOUND"):e=t,e}var Ce=t=>t();function Xe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Jh(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 Fs(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Zh="LC_AUTOGENERATED";function lr(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'."),Zh)}function et(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Vo.isInstance(t))throw new Error("Invalid generic chat message");return Jh(t);default:throw new Error(`Unknown message type: ${e}`)}}function Nu(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function tt(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((n||i)&&o&&e)return`${o}/${e}`;if((n||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function La(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Lu(t){let e=Ce(()=>{if(La(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&La(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 Du(){let t=Wl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function rt(t,e=!1,r="1.0.0"){let n=Lu(t),o=Du(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function Fu(t,e){let r;return _r(t)?r=Li(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 ju(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(zu(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
62
|
+
`)}function zu(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${js(o,e)},`):r.push(`${n}?: ${js(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
|
|
63
|
+
`)}function js(t,e){if(Qh(t))return t.anyOf.map(r=>js(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",zu(t,e+2),"}"].join(`
|
|
64
|
+
`);case"array":return t.items?`${js(t.items,e)}[]`:"any[]";default:return""}}function zs(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 Dn(t){return"type"in t&&t.type!=="function"}function Uu(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 qu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function cr(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Us(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Bu(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 Ku(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 Wu(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Hu(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 Vu(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 Gu(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var Zu=Symbol("Let zodToJsonSchema decide on which parser to use"),Ju={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Qu=t=>typeof t=="string"?{...Ju,basePath:["#"],definitions:{},name:t}:{...Ju,basePath:["#"],definitions:{},...t};var ko=t=>"_def"in t?t._def:t;function Yu(t){if(!t)return!0;for(let e in t)return!1;return!0}var Xu=t=>{let e=Qu(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])=>[ko(o),{def:ko(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Da(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function F(t,e,r,n,o){t[e]=r,Da(t,e,n,o)}function ed(){return{}}function td(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=M(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&F(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&F(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(F(r,"minItems",t.exactLength.value,t.exactLength.message,e),F(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function rd(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?F(r,"minimum",n.value,n.message,e):F(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),F(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?F(r,"maximum",n.value,n.message,e):F(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),F(r,"maximum",n.value,n.message,e));break;case"multipleOf":F(r,"multipleOf",n.value,n.message,e);break}return r}function nd(){return{type:"boolean"}}function od(t,e){return M(t.type._def,e)}var sd=(t,e)=>M(t.innerType._def,e);function Fa(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Fa(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 Yh(t,e)}}var Yh=(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":F(r,"minimum",n.value,n.message,e);break;case"max":F(r,"maximum",n.value,n.message,e);break}return r};function id(t,e){return{...M(t.innerType._def,e),default:t.defaultValue()}}function ad(t,e,r){return e.effectStrategy==="input"?M(t.schema._def,e,r):{}}function ld(t){return{type:"string",enum:[...t.values]}}var Xh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function cd(t,e){let r=[M(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),M(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(Xh(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function ud(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 ja,ur={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:()=>(ja===void 0&&(ja=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ja),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function qs(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?eg(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":F(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":F(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":ke(r,ur.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":ke(r,o.regex,o.message,e);break;case"cuid":ke(r,ur.cuid,o.message,e);break;case"cuid2":ke(r,ur.cuid2,o.message,e);break;case"startsWith":ke(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":ke(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":F(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),F(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ke(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":ke(r,ur.emoji,o.message,e);break;case"ulid":{ke(r,ur.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ee(r,"binary",o.message,e);break}case"contentEncoding:base64":{F(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ke(r,ur.base64,o.message,e);break}}break}case"nanoid":ke(r,ur.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var eg=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}}})):F(t,"format",e,r,n)},ke=(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:dd(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):F(t,"pattern",dd(e,n),r,n)},dd=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",i=!1,a=!1,c=!1;for(let l=0;l<o.length;l++){if(i){s+=o[l],i=!1;continue}if(n.i){if(a){if(o[l].match(/[a-z]/)){c?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),c=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],c=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
|
|
65
65
|
]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
|
|
66
66
|
]))`;continue}}if(n.s&&o[l]==="."){s+=a?`${o[l]}\r
|
|
67
67
|
`:`[${o[l]}\r
|
|
68
|
-
]`;continue}s+=o[l],o[l]==="\\"?i=!0:a&&o[l]==="]"?a=!1:!a&&o[l]==="["&&(a=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function qs(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===$.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Us(t.keyType._def,e)).reduce((o,[s,i])=>s==="type"?o:{...o,[s]:i},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===$.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function pd(t,e){if(e.mapStrategy==="record")return qs(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=M(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 md(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 fd(){return{not:{}}}function hd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Oo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yd(t,e){if(e.target==="openApi3")return gd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Oo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Oo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return gd(t,e)}var gd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(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 _d(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Oo[t.innerType._def.typeName],nullable:!0}:{type:[Oo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function wd(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",Da(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?F(r,"minimum",n.value,n.message,e):F(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),F(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?F(r,"maximum",n.value,n.message,e):F(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),F(r,"maximum",n.value,n.message,e));break;case"multipleOf":F(r,"multipleOf",n.value,n.message,e);break}return r}function tg(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function bd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let i=[...e.currentPath,"properties",o],a=M(s._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:a},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:tg(t,e)};return r.required.length||delete r.required,r}var xd=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return M(t.innerType._def,{...e,currentPath:e.currentPath});let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var Ad=(t,e)=>{if(e.pipeStrategy==="input")return M(t.in._def,e);if(e.pipeStrategy==="output")return M(t.out._def,e);let r=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function vd(t,e){return M(t.type._def,e)}function Id(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&F(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&F(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Td(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Sd(){return{not:{}}}function Cd(){return{}}var Ed=(t,e)=>M(t.innerType._def,e);function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let i=e.override?.(t,e,n,r);if(i!==Zu)return i}if(n&&!r){let i=rg(n,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=og(t,t.typeName,e,r);return s&&sg(t,e,s),o.jsonSchema=s,s}var rg=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:ng(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ng=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},og=(t,e,r,n)=>{switch(e){case $.ZodString:return Us(t,r);case $.ZodNumber:return wd(t,r);case $.ZodObject:return bd(t,r);case $.ZodBigInt:return rd(t,r);case $.ZodBoolean:return nd();case $.ZodDate:return Fa(t,r);case $.ZodUndefined:return Sd();case $.ZodNull:return hd(r);case $.ZodArray:return td(t,r);case $.ZodUnion:case $.ZodDiscriminatedUnion:return yd(t,r);case $.ZodIntersection:return cd(t,r);case $.ZodTuple:return Td(t,r);case $.ZodRecord:return qs(t,r);case $.ZodLiteral:return ud(t,r);case $.ZodEnum:return ld(t);case $.ZodNativeEnum:return md(t);case $.ZodNullable:return _d(t,r);case $.ZodOptional:return xd(t,r);case $.ZodMap:return pd(t,r);case $.ZodSet:return Id(t,r);case $.ZodLazy:return M(t.getter()._def,r);case $.ZodPromise:return vd(t,r);case $.ZodNaN:case $.ZodNever:return fd();case $.ZodEffects:return ad(t,r,n);case $.ZodAny:return ed();case $.ZodUnknown:return Cd();case $.ZodDefault:return id(t,r);case $.ZodBranded:return od(t,r);case $.ZodReadonly:return Ed(t,r);case $.ZodCatch:return sd(t,r);case $.ZodPipeline:return Ad(t,r);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(o=>{})(e)}},sg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var za=(t,e)=>{let r=Xu(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=M(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let i=(()=>{if(Yu(r.definitions))return;let c={},l=new Set;for(let u=0;u<500;u++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,h]of m)c[f]=M(ko(h),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return c})(),a=n===void 0?i?{...o,[r.definitionPath]:i}:o:r.nameStrategy==="duplicate-ref"?{...o,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function kd(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 nt(e,[],e)}function Ua(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Ua(e))return!0;for(let e of t.anyOf??[])if(Ua(e))return!0;return!1}function nt(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,h]of Object.entries(n))nt(h,[...e,"$defs",f],r);let o=t.definitions;if(ur(o))for(let[f,h]of Object.entries(o))nt(h,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(ur(a)){for(let[f,h]of Object.entries(a))if(!Ua(h)&&!i.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(a),t.properties=Object.fromEntries(Object.entries(a).map(([f,h])=>[f,nt(h,[...e,"properties",f],r)]))}let c=t.items;ur(c)&&(t.items=nt(c,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,h)=>nt(f,[...e,"anyOf",String(h)],r)));let u=t.allOf;if(Array.isArray(u))if(u.length===1){let f=nt(u[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=u.map((f,h)=>nt(f,[...e,"allOf",String(h)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&ag(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=ig(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,nt(t,e,r)}return t}function ig(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 ag(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function lg(t,e){return za(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function cg(t){return kd(Xl(t,{target:"draft-7"}))}function ug(t){return"_zod"in t}function Od(t,e,r){return au({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:ug(t)?cg(t):lg(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var Pd=["jsonSchema","functionCalling","jsonMode"];function Md(t,e){if(typeof e<"u"&&!Pd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Pd.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 dg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Rd(t,e,r){if(ec(t))return Od(t,e,r);if(Zo(t))return dg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Mt(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Ql(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function $d(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 Nd={"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 Fn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var dr=class extends es{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_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.1")}_getReasoningParams(t){if(!Xe(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Pt(t.json_schema.schema)?Rd(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=tt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=rt(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return lr(t)?Gu(t.metadata.customTool):Yo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Fu(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(Dn(n)||lr(n))return n;if(Uu(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[i,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(et(s))]),c=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=i+r+a+c,u=s;if(u._getType()==="function"&&(l-=2),u.additional_kwargs?.function_call&&(l+=3),u?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(u.additional_kwargs.function_call?.name)),u.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(u.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(u.additional_kwargs.function_call)),l+=await this.getNumTokens(u.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=ju(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 Nd[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=Md(this.model,e?.method);if(a==="jsonMode"){n=Ri(o);let c=Mt(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...c}}})}else if(a==="jsonSchema"){let c=Mt(o),l={name:s??"extract",description:Pi(c),schema:Pt(o)?o:c,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,...c}}}),Pt(o)||Jo(o)){let u=Ri(o);n=lt.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:u.invoke(m.content))}else n=new nc}else{let c=s??"extract",l=Mt(o),u;Pt(o)||Jo(o)?u={name:c,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(u=o,c=o.name):(c=o.title??c,u={name:c,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:u}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=oc(o,c)}return sc(r,n,i)}};var Bs={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=Ei({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=Ci(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=Ci(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=Ei({dataUrl:t.url}),r=Ln(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=Ln(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`)}},qa=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],i=[];for(let l of n??[])try{s.push(Xo(l,{returnId:!0}))}catch(u){i.push(gr(l,u.message))}let a={function_call:t.function_call,tool_calls:n};r!==void 0&&(a.__raw_response=e),o!==void 0&&(a.reasoning_content=o);let c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new j({content:$d(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Vo(t.content||"",t.role??"unknown")}},Ba=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Oi({content:s,response_metadata:a});if(o==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)c.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new at({content:s,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return o==="system"?new Go({content:s,response_metadata:a}):o==="developer"?new Go({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Gl({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new ki({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Vl({content:s,role:o,response_metadata:a})},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=Jl(()=>{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=Ln(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=et(t);if(r==="system"&&Xe(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 j.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(Mi):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&B.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let i=Ld(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},jn=({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=et(r);n==="system"&&Xe(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>Wo(i)?Ho(i,Bs):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),j.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Mi):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),B.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var Ks=class extends dr{constructor(t,e){super(Fn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:js(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),Xe(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=jn({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let h of i){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let w=h.generationInfo?.completion??0;a[w]===void 0?a[w]=h:a[w]=a[w].concat(h)}let c=Object.entries(a).sort(([h],[w])=>parseInt(h,10)-parseInt(w,10)).map(([h,w])=>w),{functions:l,function_call:u}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,u),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let i=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:l,prompt_tokens_details:u,completion_tokens_details:m}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),c&&(n.input_tokens=(n.input_tokens??0)+c),l&&(n.total_tokens=(n.total_tokens??0)+l),(u?.audio_tokens!==null||u?.cached_tokens!==null)&&(n.input_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.cached_tokens!==null&&{cache_read:u?.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 h of i?.choices??[]){let w={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},i)};w.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},Be(w.message)&&(w.message.usage_metadata=n),w.message=new j(Object.fromEntries(Object.entries(w.message).filter(([x])=>!x.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=jn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),i=this.streamUsage??e.streamUsage;yield*ts(async function*(c,l){for await(let u of c){if(l?.aborted)return;yield u}}(s,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=jn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,i=await this.completionWithRetry(o,e),a;for await(let c of i){if(e.signal?.aborted)return;let l=c?.choices?.[0];if(c.usage&&(a=c.usage),!l)continue;let{delta:u}=l;if(!u)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(u,c,s);s=u.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 h={...f};l.finish_reason!=null&&(h.finish_reason=l.finish_reason,h.system_fingerprint=c.system_fingerprint,h.model_name=c.model,h.service_tier=c.service_tier),this.logprobs&&(h.logprobs=l.logprobs);let w=new eo({message:m,text:m.content,generationInfo:h});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},l={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},u=new eo({message:new at({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield u,await r?.handleLLMNewToken(u.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:u})}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 Ba({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return qa({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Ws="__openai_function_call_ids__",Hs="__openai_custom_tool_call_ids__";function Kd(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 mg(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 Po=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}},Vs=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),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},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(Kd),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Xo(c,{returnId:!0}))}catch(l){let u;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(u=l.message),n.push(gr(c,u))}i[Ws]??={},a.id&&(i[Ws][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(l=>l.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=Bu(a);c?(r.push(c),i[Hs]??={},a.id&&a.call_id&&(i[Hs][a.call_id]=a.id)):n.push(gr(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=Ku(a);c?r.push(c):n.push(gr(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new j({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Po(t.usage),additional_kwargs:i,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}},Ka=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[Kd(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Ws]={[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}),i[Hs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=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"){a=t.response.id;let c=Vs(t.response);if(n=Po(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[l,u]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=c.response_metadata.output:s[l]=u)}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.completed"||t.type==="response.file_search_call.completed")r={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let c=t.item.summary?t.item.summary.map((u,m)=>({...u,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let l=t.item.summary?.map(u=>u.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new eo({text:e.map(c=>c.text).join(""),message:new at({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},Hd=t=>{let e=j.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ce(()=>{try{let g=et(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),o,s=new Set,i=new Set,a=new Map,c=new Map;function*l(){if(!o)return;let g=o.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield o),o=void 0}let u=(g,v)=>{o||(o={type:"message",role:n,content:[],...v?{phase:v}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...g]:[...g]:o.content.push(...g)},m=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},f=g=>{let v=Ce(()=>{let S=g.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(g.fileId)return{type:"input_image",detail:v,file_id:g.fileId};if(g.url)return{type:"input_image",detail:v,image_url:g.url};if(g.data){let S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:v,image_url:`data:${g.mimeType??"image/png"};base64,${S}`}}},h=g=>{if(g.fileId){let v=Na(g);return{type:"input_file",file_id:g.fileId,...v?{filename:v}:{}}}if(g.url){let v=Na(g);return{...v?{filename:v}:{},type:"input_file",file_url:g.url}}if(g.data){let v=Ln(g),S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${S}`,filename:v}}},w=g=>{let v=Ce(()=>{if(Array.isArray(g.summary)){let z=g.summary?.map(O=>O?.text).filter(O=>typeof O=="string")??[];if(z.length>0)return z}return g.reasoning?[g.reasoning]:[]}),S=v.length>0?v.map(z=>({type:"summary_text",text:z})):[{type:"summary_text",text:""}],L={type:"reasoning",id:g.id??"",summary:S};return g.reasoning&&(L.content=[{type:"reasoning_text",text:g.reasoning}]),L},x=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:m(g.args)}),I=g=>{let v=m(g.output),S=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:v,...S?{status:S}:{}}};for(let g of t.contentBlocks)if(g.type==="text"){let v=Ce(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});u([{type:"input_text",text:g.text}],v)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield w(g);else if(g.type==="tool_call"){yield*l();let v=g.id??"";v&&(s.add(v),a.delete(v)),yield x(g)}else if(g.type==="tool_call_chunk"){if(g.id){let v=a.get(g.id)??{name:g.name,args:[]};g.name&&(v.name=g.name),g.args&&v.args.push(g.args),a.set(g.id,v)}}else if(g.type==="server_tool_call"){yield*l();let v=g.id??"";v&&(i.add(v),c.delete(v)),yield x(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let v=c.get(g.id)??{name:g.name,args:[]};g.name&&(v.name=g.name),g.args&&v.args.push(g.args),c.set(g.id,v)}}else if(g.type==="server_tool_call_result")yield*l(),yield I(g);else if(g.type!=="audio")if(g.type==="file"){let v=h(g);v&&u([v])}else if(g.type==="image"){let v=f(g);v&&u([v])}else if(g.type==="video"){let v=h(g);v&&u([v])}else g.type==="text-plain"?g.text&&u([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(let[g,v]of a){if(!g||s.has(g))continue;let S=v.args.join("");!v.name&&!S||(yield{type:"function_call",call_id:g,name:v.name??"",arguments:S})}for(let[g,v]of c){if(!g||i.has(g))continue;let S=v.args.join("");!v.name&&!S||(yield{type:"function_call",call_id:g,name:v.name??"",arguments:S})}}return Array.from(r())},Mo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Hd(n);let s=n.additional_kwargs,i=et(n);if(i==="system"&&Xe(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(f=>f.type==="input_image");if(l)return l;let u=a.content.find(f=>f.type==="computer_screenshot");if(u)return u;let m=a.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:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(x=>"type"in x))return o?.output;let a=[],c=s?.reasoning,l=!!c?.encrypted_content;if(c&&(!e||l)){let x=Wd(c);a.push(x)}let{content:u}=n;if(s?.refusal&&(typeof u=="string"&&(u=[{type:"output_text",text:u,annotations:[]}]),u=[...u,{type:"refusal",refusal:s.refusal}]),typeof u=="string"||u.length>0){let x={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ce(()=>typeof u=="string"?u:u.flatMap(I=>{if(I.type==="text"){let g=I;return{type:"output_text",text:g.text,annotations:(g.annotations??[]).map(mg)}}return I.type==="output_text"||I.type==="refusal"?I:[]})),phase:Ce(()=>{if(Array.isArray(u))return u.find(I=>"phase"in I&&typeof I.phase=="string")?.phase})};a.push(x)}let m=s?.[Ws],f=s?.[Hs];j.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(x=>Hu(x,f)?{type:"custom_tool_call",id:"call_id"in x&&typeof x.call_id=="string"?x.call_id:f?.[x.id??""]??"",call_id:x.id??"",input:x.args.input,name:x.name}:Wu(x)?{type:"computer_call",id:x.call_id,call_id:x.id??"",action:x.args.action}:{type:"function_call",name:x.name,arguments:JSON.stringify(x.args),call_id:x.id,...e?{}:{id:m?.[x.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(x=>({type:"function_call",name:x.function.name,call_id:x.id,arguments:x.function.arguments,...e?{}:{id:m?.[x.id]}})));let h=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(h!=null){let x=h?.filter(I=>w.includes(I.type));x.length>0&&a.push(...x)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],c=n.content.flatMap(l=>(l.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Wo(l)?Ho(l,Bs):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 c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Wa(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,i=0,a=!1,c,l,u,m,f=new Set,h=(I,g)=>{let v=s.get(I);if(v!==void 0)return{index:v,isNew:!1};let S=i++;return s.set(I,S),o.set(S,{...g}),{index:S,isNew:!0}},w=function*(){a||(a=!0,yield{event:"message-start",id:c})},x=function*(I){if(f.has(I))return;let g=o.get(I);g&&(f.add(I),yield{event:"content-block-finish",index:I,content:ic(g)})};for await(let I of t){if(I.type==="response.created"){c=I.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:I.response.model,id:I.response.id}};continue}if(I.type==="response.output_text.delta"){yield*w();let{index:g,isNew:v}=h(`text:${I.output_index}:${I.content_index}`,{type:"text",text:""});v&&(yield{event:"content-block-start",index:g,content:{type:"text",text:""}});let S=o.get(g);S.text=(S.text??"")+I.delta,yield{event:"content-block-delta",index:g,delta:{type:"text-delta",text:I.delta}};continue}if(I.type==="response.reasoning_summary_text.delta"){yield*w();let{index:g,isNew:v}=h(`reasoning:${I.output_index}:${I.summary_index}`,{type:"reasoning",reasoning:""});v&&(yield{event:"content-block-start",index:g,content:{type:"reasoning",reasoning:""}});let S=o.get(g);S.reasoning=(S.reasoning??"")+I.delta,yield{event:"content-block-delta",index:g,delta:{type:"reasoning-delta",reasoning:I.delta}};continue}if(I.type==="response.output_item.added"&&(I.item.type==="function_call"||I.item.type==="custom_tool_call")){yield*w();let g=`tool:${I.output_index}`,v=I.item.type==="custom_tool_call",S=I.item.type==="function_call"?I.item.arguments??"":I.item.input??"",{index:L,isNew:z}=h(g,{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:S,index:I.output_index,...v?{isCustomTool:!0}:{}});if(z&&(yield{event:"content-block-start",index:L,content:{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:S,index:I.output_index}}),S){let O=o.get(L);yield{event:"content-block-delta",index:L,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...O.id!=null?{id:O.id}:{},...O.name!=null?{name:O.name}:{},args:O.args}}}}continue}if(I.type==="response.function_call_arguments.delta"||I.type==="response.custom_tool_call_input.delta"){yield*w();let{index:g,isNew:v}=h(`tool:${I.output_index}`,{type:"tool_call_chunk",args:"",index:I.output_index,...I.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});v&&(yield{event:"content-block-start",index:g,content:{type:"tool_call_chunk",args:"",index:I.output_index}});let S=o.get(g);S.args=(S.args??"")+I.delta,yield{event:"content-block-delta",index:g,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(I.type==="response.output_item.done"&&(I.item.type==="function_call"||I.item.type==="custom_tool_call")){yield*w();let g=`tool:${I.output_index}`,v=I.item.type==="function_call"?I.item.arguments??"":I.item.input??"",{index:S,isNew:L}=h(g,{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:v,index:I.output_index});if(L)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:v,index:I.output_index}};else{let z=o.get(S);z.args=v,z.id=I.item.call_id,z.name=I.item.name}yield*x(S);continue}if(I.type==="response.completed"||I.type==="response.incomplete"){yield*w(),c=I.response.id,u=fg(I.response.status,I.type),m={model_provider:n,id:I.response.id,model:I.response.model,status:I.response.status},r&&I.response.usage&&(l=Po(I.response.usage),yield{event:"usage",usage:l});continue}I.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:I.type,payload:I})}a||(yield{event:"message-start"});for(let[I]of o)f.has(I)||(yield*x(I));yield{event:"message-finish",reason:u,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function fg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Gs=class extends dr{constructor(t,e){super(Fn(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:qu(t?.tool_choice)?t?.tool_choice:(()=>{let o=js(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let i of o)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},s=s?.concat(i)??i;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:Mo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Vs(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:Mo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Wa(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(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:Mo({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=Ka(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(Dn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(lr(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Yo(n)){let o={};for(let[s,i]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=i);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else zs(n)&&r.push(Vu(n));return r}};var zn=class Vd extends dr{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=Fn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Gs(n),this.completions=n?.completions??new Ks(n)}_useResponsesApi(e){let r=e?.tools?.some(Dn),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(zs)||e?.tools?.some(lr);return this.useResponsesApi||r||n||o||Nu(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 Vd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ro=class extends tc{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=$i(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let i={model:this.model,input:s};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let i=e[s],{data:a}=n[s];for(let c=0;c<i.length;c+=1)o.push(a[c].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=tt({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=rt(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 _g=b.object({type:b.literal("screenshot")}),wg=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),bg=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),xg=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),Ag=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),vg=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),Ig=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),Tg=b.object({type:b.literal("type"),text:b.string()}),Sg=b.object({type:b.literal("wait"),duration:b.number().optional()}),Cg=b.union([_g,wg,bg,xg,Ag,vg,Ig,Tg,Sg]),sK=b.object({action:Cg});var Eg=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),cK=b.union([Eg]);var mK=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var kg=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),Og=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),Pg=b.object({type:b.literal("delete_file"),path:b.string()}),yK=b.union([kg,Og,Pg]);var Zd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Va={default:"text-embedding-ada-002"},Ha=new Map,Js=null,$g=()=>{let t=Jd.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},Qd=async t=>{let e=$g();Ha.size===0&&(Js||(Js=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>Ha.set(o.name,o))}catch(n){throw Js=null,n}})()),await Js);let r=Ha.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Ng=async(t="default")=>await Qd(Zd[t]),Yd=async(t="default")=>await Qd(Va[t]),qn=(t,e)=>e,Xd=(t,e)=>({...t,...e}),ep=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
|
|
68
|
+
]`;continue}s+=o[l],o[l]==="\\"?i=!0:a&&o[l]==="]"?a=!1:!a&&o[l]==="["&&(a=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Bs(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]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:M(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(qs(t.keyType._def,e)).reduce((o,[s,i])=>s==="type"?o:{...o,[s]:i},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function pd(t,e){if(e.mapStrategy==="record")return Bs(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=M(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 md(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 fd(){return{not:{}}}function hd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Oo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yd(t,e){if(e.target==="openApi3")return gd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Oo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Oo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return gd(t,e)}var gd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(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 _d(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Oo[t.innerType._def.typeName],nullable:!0}:{type:[Oo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function wd(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",Da(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?F(r,"minimum",n.value,n.message,e):F(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),F(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?F(r,"maximum",n.value,n.message,e):F(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),F(r,"maximum",n.value,n.message,e));break;case"multipleOf":F(r,"multipleOf",n.value,n.message,e);break}return r}function tg(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function bd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let i=[...e.currentPath,"properties",o],a=M(s._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:a},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:tg(t,e)};return r.required.length||delete r.required,r}var Ad=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return M(t.innerType._def,{...e,currentPath:e.currentPath});let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var xd=(t,e)=>{if(e.pipeStrategy==="input")return M(t.in._def,e);if(e.pipeStrategy==="output")return M(t.out._def,e);let r=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function vd(t,e){return M(t.type._def,e)}function Id(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&F(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&F(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Td(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Sd(){return{not:{}}}function Cd(){return{}}var Ed=(t,e)=>M(t.innerType._def,e);function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let i=e.override?.(t,e,n,r);if(i!==Zu)return i}if(n&&!r){let i=rg(n,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=og(t,t.typeName,e,r);return s&&sg(t,e,s),o.jsonSchema=s,s}var rg=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:ng(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ng=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},og=(t,e,r,n)=>{switch(e){case N.ZodString:return qs(t,r);case N.ZodNumber:return wd(t,r);case N.ZodObject:return bd(t,r);case N.ZodBigInt:return rd(t,r);case N.ZodBoolean:return nd();case N.ZodDate:return Fa(t,r);case N.ZodUndefined:return Sd();case N.ZodNull:return hd(r);case N.ZodArray:return td(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return yd(t,r);case N.ZodIntersection:return cd(t,r);case N.ZodTuple:return Td(t,r);case N.ZodRecord:return Bs(t,r);case N.ZodLiteral:return ud(t,r);case N.ZodEnum:return ld(t);case N.ZodNativeEnum:return md(t);case N.ZodNullable:return _d(t,r);case N.ZodOptional:return Ad(t,r);case N.ZodMap:return pd(t,r);case N.ZodSet:return Id(t,r);case N.ZodLazy:return M(t.getter()._def,r);case N.ZodPromise:return vd(t,r);case N.ZodNaN:case N.ZodNever:return fd();case N.ZodEffects:return ad(t,r,n);case N.ZodAny:return ed();case N.ZodUnknown:return Cd();case N.ZodDefault:return id(t,r);case N.ZodBranded:return od(t,r);case N.ZodReadonly:return Ed(t,r);case N.ZodCatch:return sd(t,r);case N.ZodPipeline:return xd(t,r);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},sg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var za=(t,e)=>{let r=Xu(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=M(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let i=(()=>{if(Yu(r.definitions))return;let c={},l=new Set;for(let u=0;u<500;u++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,h]of m)c[f]=M(ko(h),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return c})(),a=n===void 0?i?{...o,[r.definitionPath]:i}:o:r.nameStrategy==="duplicate-ref"?{...o,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function kd(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 nt(e,[],e)}function Ua(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Ua(e))return!0;for(let e of t.anyOf??[])if(Ua(e))return!0;return!1}function nt(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!dr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(dr(n))for(let[f,h]of Object.entries(n))nt(h,[...e,"$defs",f],r);let o=t.definitions;if(dr(o))for(let[f,h]of Object.entries(o))nt(h,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(dr(a)){for(let[f,h]of Object.entries(a))if(!Ua(h)&&!i.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(a),t.properties=Object.fromEntries(Object.entries(a).map(([f,h])=>[f,nt(h,[...e,"properties",f],r)]))}let c=t.items;dr(c)&&(t.items=nt(c,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,h)=>nt(f,[...e,"anyOf",String(h)],r)));let u=t.allOf;if(Array.isArray(u))if(u.length===1){let f=nt(u[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=u.map((f,h)=>nt(f,[...e,"allOf",String(h)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&ag(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=ig(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!dr(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,nt(t,e,r)}return t}function ig(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(!dr(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 dr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ag(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function lg(t,e){return za(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function cg(t){return kd(Xl(t,{target:"draft-7"}))}function ug(t){return"_zod"in t}function Od(t,e,r){return au({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:ug(t)?cg(t):lg(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var Pd=["jsonSchema","functionCalling","jsonMode"];function Md(t,e){if(typeof e<"u"&&!Pd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Pd.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 dg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Rd(t,e,r){if(ec(t))return Od(t,e,r);if(Zo(t))return dg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Mt(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Ql(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function $d(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 Nd={"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 Fn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var pr=class extends es{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??xe("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??xe("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.2")}_getReasoningParams(t){if(!Xe(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Pt(t.json_schema.schema)?Rd(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=tt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=rt(r.defaultHeaders),this.client=new O(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return cr(t)?Gu(t.metadata.customTool):Yo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Fu(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(Dn(n)||cr(n))return n;if(Uu(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return _r(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[i,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(et(s))]),c=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=i+r+a+c,u=s;if(u._getType()==="function"&&(l-=2),u.additional_kwargs?.function_call&&(l+=3),u?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(u.additional_kwargs.function_call?.name)),u.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(u.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(u.additional_kwargs.function_call)),l+=await this.getNumTokens(u.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=ju(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 Nd[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=Md(this.model,e?.method);if(a==="jsonMode"){n=$i(o);let c=Mt(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...c}}})}else if(a==="jsonSchema"){let c=Mt(o),l={name:s??"extract",description:Mi(c),schema:Pt(o)?o:c,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,...c}}}),Pt(o)||Jo(o)){let u=$i(o);n=lt.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:u.invoke(m.content))}else n=new nc}else{let c=s??"extract",l=Mt(o),u;Pt(o)||Jo(o)?u={name:c,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(u=o,c=o.name):(c=o.title??c,u={name:c,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:u}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=oc(o,c)}return sc(r,n,i)}};var Ks={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=ki({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=Ei(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=Ei(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=ki({dataUrl:t.url}),r=lr(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=lr(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`)}},qa=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],i=[];for(let l of n??[])try{s.push(Xo(l,{returnId:!0}))}catch(u){i.push(yr(l,u.message))}let a={function_call:t.function_call,tool_calls:n};r!==void 0&&(a.__raw_response=e),o!==void 0&&(a.reasoning_content=o);let c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new j({content:$d(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Vo(t.content||"",t.role??"unknown")}},Ba=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Pi({content:s,response_metadata:a});if(o==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)c.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new at({content:s,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return o==="system"?new Go({content:s,response_metadata:a}):o==="developer"?new Go({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Gl({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new Oi({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Vl({content:s,role:o,response_metadata:a})},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=Jl(()=>{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=lr(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=et(t);if(r==="system"&&Xe(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 j.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(Ri):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&B.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let i=Ld(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},jn=({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=et(r);n==="system"&&Xe(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>Wo(i)?Ho(i,Ks):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),j.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Ri):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),B.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var Ws=class extends pr{constructor(t,e){super(Fn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:zs(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),Xe(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=jn({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let h of i){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let w=h.generationInfo?.completion??0;a[w]===void 0?a[w]=h:a[w]=a[w].concat(h)}let c=Object.entries(a).sort(([h],[w])=>parseInt(h,10)-parseInt(w,10)).map(([h,w])=>w),{functions:l,function_call:u}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,u),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let i=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:l,prompt_tokens_details:u,completion_tokens_details:m}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),c&&(n.input_tokens=(n.input_tokens??0)+c),l&&(n.total_tokens=(n.total_tokens??0)+l),(u?.audio_tokens!==null||u?.cached_tokens!==null)&&(n.input_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.cached_tokens!==null&&{cache_read:u?.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 h of i?.choices??[]){let w={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},i)};w.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},Be(w.message)&&(w.message.usage_metadata=n),w.message=new j(Object.fromEntries(Object.entries(w.message).filter(([A])=>!A.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=jn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),i=this.streamUsage??e.streamUsage;yield*ts(async function*(c,l){for await(let u of c){if(l?.aborted)return;yield u}}(s,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=jn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,i=await this.completionWithRetry(o,e),a;for await(let c of i){if(e.signal?.aborted)return;let l=c?.choices?.[0];if(c.usage&&(a=c.usage),!l)continue;let{delta:u}=l;if(!u)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(u,c,s);s=u.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 h={...f};l.finish_reason!=null&&(h.finish_reason=l.finish_reason,h.system_fingerprint=c.system_fingerprint,h.model_name=c.model,h.service_tier=c.service_tier),this.logprobs&&(h.logprobs=l.logprobs);let w=new eo({message:m,text:m.content,generationInfo:h});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},l={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},u=new eo({message:new at({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield u,await r?.handleLLMNewToken(u.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:u})}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 Ba({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return qa({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Hs="__openai_function_call_ids__",Vs="__openai_custom_tool_call_ids__";function Kd(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 mg(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 Po=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}},Gs=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),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},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(Kd),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Xo(c,{returnId:!0}))}catch(l){let u;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(u=l.message),n.push(yr(c,u))}i[Hs]??={},a.id&&(i[Hs][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(l=>l.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=Bu(a);c?(r.push(c),i[Vs]??={},a.id&&a.call_id&&(i[Vs][a.call_id]=a.id)):n.push(yr(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=Ku(a);c?r.push(c):n.push(yr(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new j({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Po(t.usage),additional_kwargs:i,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}},Ka=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[Kd(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Hs]={[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}),i[Vs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=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"){a=t.response.id;let c=Gs(t.response);if(n=Po(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[l,u]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=c.response_metadata.output:s[l]=u)}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[,c,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:l}}}else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let c=t.item.summary?t.item.summary.map((u,m)=>({...u,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let l=t.item.summary?.map(u=>u.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new eo({text:e.map(c=>c.text).join(""),message:new at({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},Hd=t=>{let e=j.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ce(()=>{try{let g=et(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),o,s=new Set,i=new Set,a=new Map,c=new Map;function*l(){if(!o)return;let g=o.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield o),o=void 0}let u=(g,v)=>{o||(o={type:"message",role:n,content:[],...v?{phase:v}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...g]:[...g]:o.content.push(...g)},m=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},f=g=>{let v=Ce(()=>{let S=g.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(g.fileId)return{type:"input_image",detail:v,file_id:g.fileId};if(g.url)return{type:"input_image",detail:v,image_url:g.url};if(g.data){let S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:v,image_url:`data:${g.mimeType??"image/png"};base64,${S}`}}},h=g=>{if(g.fileId){let v=Fs(g);return{type:"input_file",file_id:g.fileId,...v?{filename:v}:{}}}if(g.url){let v=Fs(g);return{...v?{filename:v}:{},type:"input_file",file_url:g.url}}if(g.data){let v=lr(g),S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${S}`,filename:v}}},w=g=>{let v=Ce(()=>{if(Array.isArray(g.summary)){let $=g.summary?.map(z=>z?.text).filter(z=>typeof z=="string")??[];if($.length>0)return $}return g.reasoning?[g.reasoning]:[]}),S=v.length>0?v.map($=>({type:"summary_text",text:$})):[{type:"summary_text",text:""}];return{type:"reasoning",...g.id?{id:g.id}:{},summary:S}},A=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:m(g.args)}),I=g=>{let v=m(g.output),S=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:v,...S?{status:S}:{}}};for(let g of t.contentBlocks)if(g.type==="text"){let v=Ce(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});u([{type:"input_text",text:g.text}],v)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield w(g);else if(g.type==="tool_call"){yield*l();let v=g.id??"";v&&(s.add(v),a.delete(v)),yield A(g)}else if(g.type==="tool_call_chunk"){if(g.id){let v=a.get(g.id)??{name:g.name,args:[]};g.name&&(v.name=g.name),g.args&&v.args.push(g.args),a.set(g.id,v)}}else if(g.type==="server_tool_call"){yield*l();let v=g.id??"";v&&(i.add(v),c.delete(v)),yield A(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let v=c.get(g.id)??{name:g.name,args:[]};g.name&&(v.name=g.name),g.args&&v.args.push(g.args),c.set(g.id,v)}}else if(g.type==="server_tool_call_result")yield*l(),yield I(g);else if(g.type!=="audio")if(g.type==="file"){let v=h(g);v&&u([v])}else if(g.type==="image"){let v=f(g);v&&u([v])}else if(g.type==="video"){let v=h(g);v&&u([v])}else g.type==="text-plain"?g.text&&u([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(let[g,v]of a){if(!g||s.has(g))continue;let S=v.args.join("");!v.name&&!S||(yield{type:"function_call",call_id:g,name:v.name??"",arguments:S})}for(let[g,v]of c){if(!g||i.has(g))continue;let S=v.args.join("");!v.name&&!S||(yield{type:"function_call",call_id:g,name:v.name??"",arguments:S})}}return Array.from(r())},Mo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Hd(n);let s=n.additional_kwargs,i=et(n);if(i==="system"&&Xe(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(f=>f.type==="input_image");if(l)return l;let u=a.content.find(f=>f.type==="computer_screenshot");if(u)return u;let m=a.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:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(A=>"type"in A))return o?.output;let a=[],c=s?.reasoning,l=!!c?.encrypted_content;if(c&&(!e||l)){let A=Wd(c);a.push(A)}let{content:u}=n;if(s?.refusal&&(typeof u=="string"&&(u=[{type:"output_text",text:u,annotations:[]}]),u=[...u,{type:"refusal",refusal:s.refusal}]),typeof u=="string"||u.length>0){let A={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ce(()=>typeof u=="string"?u:u.flatMap(I=>{if(I.type==="text"){let g=I;return{type:"output_text",text:g.text,annotations:(g.annotations??[]).map(mg)}}return I.type==="output_text"||I.type==="refusal"?I:[]})),phase:Ce(()=>{if(Array.isArray(u))return u.find(I=>"phase"in I&&typeof I.phase=="string")?.phase})};a.push(A)}let m=s?.[Hs],f=s?.[Vs];j.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(A=>Hu(A,f)?{type:"custom_tool_call",id:"call_id"in A&&typeof A.call_id=="string"?A.call_id:f?.[A.id??""]??"",call_id:A.id??"",input:A.args.input,name:A.name}:Wu(A)?{type:"computer_call",id:A.call_id,call_id:A.id??"",action:A.args.action}:{type:"function_call",name:A.name,arguments:JSON.stringify(A.args),call_id:A.id,...e?{}:{id:m?.[A.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(A=>({type:"function_call",name:A.function.name,call_id:A.id,arguments:A.function.arguments,...e?{}:{id:m?.[A.id]}})));let h=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(h!=null){let A=h?.filter(I=>w.includes(I.type));A.length>0&&a.push(...A)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],c=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Wo(l)){if(l.type==="file"){let u=Fs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...u?{filename:u}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...u?{filename:u}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:lr(l)}}return Ho(l,Ks)}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 c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Wa(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,i=0,a=!1,c,l,u,m,f=new Set,h=(I,g)=>{let v=s.get(I);if(v!==void 0)return{index:v,isNew:!1};let S=i++;return s.set(I,S),o.set(S,{...g}),{index:S,isNew:!0}},w=function*(){a||(a=!0,yield{event:"message-start",id:c})},A=function*(I){if(f.has(I))return;let g=o.get(I);g&&(f.add(I),yield{event:"content-block-finish",index:I,content:ic(g)})};for await(let I of t){if(I.type==="response.created"){c=I.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:I.response.model,id:I.response.id}};continue}if(I.type==="response.output_text.delta"){yield*w();let{index:g,isNew:v}=h(`text:${I.output_index}:${I.content_index}`,{type:"text",text:""});v&&(yield{event:"content-block-start",index:g,content:{type:"text",text:""}});let S=o.get(g);S.text=(S.text??"")+I.delta,yield{event:"content-block-delta",index:g,delta:{type:"text-delta",text:I.delta}};continue}if(I.type==="response.reasoning_summary_text.delta"){yield*w();let{index:g,isNew:v}=h(`reasoning:${I.output_index}:${I.summary_index}`,{type:"reasoning",reasoning:""});v&&(yield{event:"content-block-start",index:g,content:{type:"reasoning",reasoning:""}});let S=o.get(g);S.reasoning=(S.reasoning??"")+I.delta,yield{event:"content-block-delta",index:g,delta:{type:"reasoning-delta",reasoning:I.delta}};continue}if(I.type==="response.output_item.added"&&(I.item.type==="function_call"||I.item.type==="custom_tool_call")){yield*w();let g=`tool:${I.output_index}`,v=I.item.type==="custom_tool_call",S=I.item.type==="function_call"?I.item.arguments??"":I.item.input??"",{index:$,isNew:z}=h(g,{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:S,index:I.output_index,...v?{isCustomTool:!0}:{}});if(z&&(yield{event:"content-block-start",index:$,content:{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:S,index:I.output_index}}),S){let P=o.get($);yield{event:"content-block-delta",index:$,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...P.id!=null?{id:P.id}:{},...P.name!=null?{name:P.name}:{},args:P.args}}}}continue}if(I.type==="response.function_call_arguments.delta"||I.type==="response.custom_tool_call_input.delta"){yield*w();let{index:g,isNew:v}=h(`tool:${I.output_index}`,{type:"tool_call_chunk",args:"",index:I.output_index,...I.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});v&&(yield{event:"content-block-start",index:g,content:{type:"tool_call_chunk",args:"",index:I.output_index}});let S=o.get(g);S.args=(S.args??"")+I.delta,yield{event:"content-block-delta",index:g,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(I.type==="response.output_item.done"&&(I.item.type==="function_call"||I.item.type==="custom_tool_call")){yield*w();let g=`tool:${I.output_index}`,v=I.item.type==="function_call"?I.item.arguments??"":I.item.input??"",{index:S,isNew:$}=h(g,{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:v,index:I.output_index});if($)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:I.item.call_id,name:I.item.name,args:v,index:I.output_index}};else{let z=o.get(S);z.args=v,z.id=I.item.call_id,z.name=I.item.name}yield*A(S);continue}if(I.type==="response.completed"||I.type==="response.incomplete"){yield*w(),c=I.response.id,u=fg(I.response.status,I.type),m={model_provider:n,id:I.response.id,model:I.response.model,status:I.response.status},r&&I.response.usage&&(l=Po(I.response.usage),yield{event:"usage",usage:l});continue}I.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:I.type,payload:I})}a||(yield{event:"message-start"});for(let[I]of o)f.has(I)||(yield*A(I));yield{event:"message-finish",reason:u,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function fg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Js=class extends pr{constructor(t,e){super(Fn(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:qu(t?.tool_choice)?t?.tool_choice:(()=>{let o=zs(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let i of o)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},s=s?.concat(i)??i;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:Mo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Gs(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:Mo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Wa(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(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:Mo({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=Ka(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(Dn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(cr(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Yo(n)){let o={};for(let[s,i]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=i);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Us(n)&&r.push(Vu(n));return r}};var zn=class Vd extends pr{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=Fn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Js(n),this.completions=n?.completions??new Ws(n)}_useResponsesApi(e){let r=e?.tools?.some(Dn),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(Us)||e?.tools?.some(cr);return this.useResponsesApi||r||n||o||Nu(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 Vd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ro=class extends tc{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??xe("OPENAI_API_KEY");this.organization=e?.configuration?.organization??xe("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Ni(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let i={model:this.model,input:s};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let i=e[s],{data:a}=n[s];for(let c=0;c<i.length;c+=1)o.push(a[c].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=tt({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=rt(n.defaultHeaders),this.client=new O(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw be(r)}})}};var _g=b.object({type:b.literal("screenshot")}),wg=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),bg=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Ag=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),xg=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),vg=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),Ig=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),Tg=b.object({type:b.literal("type"),text:b.string()}),Sg=b.object({type:b.literal("wait"),duration:b.number().optional()}),Cg=b.union([_g,wg,bg,Ag,xg,vg,Ig,Tg,Sg]),sK=b.object({action:Cg});var Eg=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),cK=b.union([Eg]);var mK=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var kg=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),Og=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),Pg=b.object({type:b.literal("delete_file"),path:b.string()}),yK=b.union([kg,Og,Pg]);var Zd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Va={default:"text-embedding-ada-002"},Ha=new Map,Zs=null,$g=()=>{let t=Jd.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},Qd=async t=>{let e=$g();Ha.size===0&&(Zs||(Zs=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>Ha.set(o.name,o))}catch(n){throw Zs=null,n}})()),await Zs);let r=Ha.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Ng=async(t="default")=>await Qd(Zd[t]),Yd=async(t="default")=>await Qd(Va[t]),qn=(t,e)=>e,Xd=(t,e)=>({...t,...e}),ep=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
|
|
69
69
|
|
|
70
70
|
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
71
71
|
|
|
@@ -73,11 +73,11 @@ ${r}`},tp=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedS
|
|
|
73
73
|
Title: {title}
|
|
74
74
|
Description: {description}`,lp=`Name: {name}
|
|
75
75
|
Alias: {alias}
|
|
76
|
-
Description: {description}`,cp=b.object({schemaVersion:b.literal(op),modified:b.number().int().nonnegative(),embeddings:b.object({modelProvider:b.literal(sp),model:b.literal(ip),dimensions:b.literal(Un),templates:b.object({layer:b.string().default(ap),field:b.string().default(lp)})}),layers:b.array(b.object({id:b.string().min(1),name:b.string().min(1),title:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(Un,{message:`Layer vector must be exactly ${Un} dimensions`}),fields:b.array(b.object({name:b.string().min(1),alias:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(Un,{message:`Field vector must be exactly ${Un} dimensions`})}))})).default([])});var up=(t,e)=>{let r=rs.fromTemplate(t);return ns.fromMessages([r,...e])},qg=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=up(e,o??[]),a=await Ja({modelTier:r,temperature:n,config:s});return i.pipe(a)},
|
|
77
|
-
Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Vg(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(mp(t))s=t;else if(Hg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),a;for(let c=s.length-1;c>=0;c-=1){let l=s[c];if(Be(l)){a=l;break}}if(a==null||!Be(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,e,t))??[])}if(!r.some(Ot))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Ot(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Kl(i))?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 j2=E.Root({llmInputMessages:E({reducer:(t,e)=>to([],e),default:()=>[]})});var No=(t,e)=>e??t,Ey=E.Root({...Ga(),intent:E({reducer:No}),vectorSearchLayerResults:E({reducer:No,default:()=>[]}),vectorSearchFieldResults:E({reducer:No}),navigationInternalState:E({reducer:No,default:()=>({toolCallMessage:void 0})})});async function ky(t,e){let r=
|
|
76
|
+
Description: {description}`,cp=b.object({schemaVersion:b.literal(op),modified:b.number().int().nonnegative(),embeddings:b.object({modelProvider:b.literal(sp),model:b.literal(ip),dimensions:b.literal(Un),templates:b.object({layer:b.string().default(ap),field:b.string().default(lp)})}),layers:b.array(b.object({id:b.string().min(1),name:b.string().min(1),title:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(Un,{message:`Layer vector must be exactly ${Un} dimensions`}),fields:b.array(b.object({name:b.string().min(1),alias:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(Un,{message:`Field vector must be exactly ${Un} dimensions`})}))})).default([])});var up=(t,e)=>{let r=rs.fromTemplate(t);return ns.fromMessages([r,...e])},qg=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=up(e,o??[]),a=await Ja({modelTier:r,temperature:n,config:s});return i.pipe(a)},Qs=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,config:i}=t,a=await(await qg({promptText:e,modelTier:r,temperature:n,messages:o,config:i})).invoke(s??{},i);if(typeof a=="string")return a;let c=a.content;return typeof c=="string"?c:JSON.stringify(c)},$o=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i,config:a}=t,c=up(e,o??[]),l=(await Ja({modelTier:r,temperature:n,config:a})).withStructuredOutput(i);return await c.pipe(l).invoke(s??{},a)};var Bg=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),zW=d.object({fields:d.array(Bg)});var UW=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var dp=async t=>{try{return await(await np()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var mp=t=>Array.isArray(t)&&t.every(Xn),Hg=t=>typeof t=="object"&&t!=null&&"messages"in t&&mp(t.messages),Vg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ot=class extends ac{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,i)=>this.run(s,i)}),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},i=await n.invoke(o,s);return Xn(i)&&i.getType()==="tool"||Ot(i)?i:new B({status:"success",name:n.name,content:typeof i=="string"?i:JSON.stringify(i),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||Yn(o))throw o;return new B({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(Vg(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(mp(t))s=t;else if(Hg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),a;for(let c=s.length-1;c>=0;c-=1){let l=s[c];if(Be(l)){a=l;break}}if(a==null||!Be(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,e,t))??[])}if(!r.some(Ot))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Ot(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Kl(i))?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 j2=E.Root({llmInputMessages:E({reducer:(t,e)=>to([],e),default:()=>[]})});var No=(t,e)=>e??t,Ey=E.Root({...Ga(),intent:E({reducer:No}),vectorSearchLayerResults:E({reducer:No,default:()=>[]}),vectorSearchFieldResults:E({reducer:No}),navigationInternalState:E({reducer:No,default:()=>({toolCallMessage:void 0})})});async function ky(t,e){let r=mr.getDefault().helperServices,n=r.geocode.find(u=>u.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Za.assetsPath?.endsWith("/")?Za.assetsPath:`${Za.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await Zg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!i?.extent||!i.location)throw new Error(`Could not find location for: ${t}`);let a=new Qg({url:s,width:24,height:24}),c=new Jg({geometry:i.location,symbol:a});e.graphics.removeAll(),e.graphics.add(c),await e.goTo(i.extent);let l={address:i.address??"",location:i.location?i.location.toJSON():null,extent:i.extent?i.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Oy=["mapView"];function ze(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Oy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Py({address:t},e){let{mapView:r}=ze(e);return await ky(t,r)}var My=d.object({address:d.string().describe("The full address or place name to locate.")}),Ry=L(Py,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:My});async function $y(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 Ny({bookmarkName:t},e){let{mapView:r}=ze(e);return await Promise.resolve($y(t,r))}var Ly=b.object({bookmarkName:b.string().describe("The name of the bookmark to navigate to.")}),Dy=L(Ny,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Ly});async function Fy(t,e,r){let n=r.map?.allLayers.find(i=>i.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:i,count:a}=await n.queryExtent(s);if(a===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(i)await r.goTo(i);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let c={layerId:t,layerTitle:n.title??t,where:o,count:a};return{text:`Successfully zoomed to ${a} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:c}}}}catch(i){return console.error("Error in goToFeatures:",i),{text:`Error: ${i instanceof Error?i.message:"Unknown error"}`,where:o}}}async function jy({layerId:t,where:e},r){let{mapView:n}=ze(r);return await Fy(t,e,n)}var zy=b.object({layerId:b.string().describe("The layerId of the layer to zoom to."),where:b.string().describe("The sql-92 where clause used to query features to zoom to")}),Uy=L(jy,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:zy});async function qy(t){let e=new Yg({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 By(t,e){let{mapView:r}=ze(e);return await qy(r)}var Ky=b.object({}),Wy=L(By,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Ky});async function Hy(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 Vy(t,e){let{mapView:r}=ze(e);return await Hy(r)}var Gy=d.object({}),Jy=L(Vy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:Gy});async function Zy(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 Qy({layerId:t},e){let{mapView:r}=ze(e);return await Zy(t,r)}var Yy=b.object({layerId:b.string().describe("The id of the layer to navigate to")}),Xy=L(Qy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Yy});async function e_(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function t_({scale:t},e){let{mapView:r}=ze(e);return await e_(t,r)}var r_=d.object({scale:d.number().describe("The map scale of the view to go to.")}),n_=L(t_,{name:"goToScale",description:"Go to the specified view scale.",schema:r_});async function o_(t,e,r){let n={target:new xp({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 s_({center:t,zoom:e,scale:r},n){let{mapView:o}=ze(n);return await o_(t,o,{zoom:e,scale:r})}var i_=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),a_=L(s_,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:i_});async function l_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function c_({zoom:t},e){let{mapView:r}=ze(e);return await l_(t,r)}var u_=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),d_=L(c_,{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:u_}),wp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./O4VO5GNH.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./U5FCUMGO.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./6ND2JXTN.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./MV7GEGP5.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./A2LPB576.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./EL3OIP52.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./TLIIJ2QC.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./PLXHBQBF.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./YPDXQEUA.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./U76GHEKJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./54TJQLYJ.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./6WPQPRJ5.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./VDZT4UXB.js").then(t=>t.default)});async function st(t){let e=Object.entries(wp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
78
78
|
Available prompts:
|
|
79
79
|
${Object.keys(wp).join(`
|
|
80
|
-
`)}`);return await e[1]()}var Wn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function p_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=ey({basemapTheme:await gp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=ty({basemapTheme:await gp(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(a=>({field:a,label:r.fields.find(c=>c.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:i}}async function m_(t){return await Xg(t)}async function f_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"chart-size":"chart",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=await p_(c),u=await m_(l);return a.renderer=u.renderer,a.visible=!0,`Chart renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var h_=["mapView"];function Oe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=h_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function g_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await f_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var y_=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),__=
|
|
80
|
+
`)}`);return await e[1]()}var Wn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function p_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=ey({basemapTheme:await gp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=ty({basemapTheme:await gp(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(a=>({field:a,label:r.fields.find(c=>c.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:i}}async function m_(t){return await Xg(t)}async function f_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"chart-size":"chart",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=await p_(c),u=await m_(l);return a.renderer=u.renderer,a.visible=!0,`Chart renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var h_=["mapView"];function Oe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=h_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function g_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await f_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var y_=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),__=L(g_,{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(wp).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:y_});function w_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,i=e[0],a;return s&&(a=il({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:i,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:a}}async function b_(t){return await ry(t)}async function
|
|
90
|
+
Fields: This style requires 2-8 number fields.`,schema:y_});function w_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,i=e[0],a;return s&&(a=il({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:i,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:a}}async function b_(t){return await ry(t)}async function A_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=w_(c),u=await b_(l);return a.renderer=u.renderer,a.visible=!0,`Color-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function x_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await A_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var v_=d.object({layerId:d.string().describe("The id of the layer to apply the color-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),I_=L(x_,{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:v_});function T_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,i=e[1],a=e[0],c;return o&&(c=il({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:a,normalizationField:i,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function S_(t){return await ny(t)}async function C_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=T_(c),u=await S_(l);return a.renderer=u.renderer,a.visible=!0,`Color renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function E_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await C_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var k_=d.object({layerId:d.string().describe("The id of the layer to apply the color renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),O_=
|
|
94
|
+
Fields: This style requires at least one field with a date type.`,schema:v_});function T_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,i=e[1],a=e[0],c;return o&&(c=il({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:a,normalizationField:i,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function S_(t){return await ny(t)}async function C_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=T_(c),u=await S_(l);return a.renderer=u.renderer,a.visible=!0,`Color renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function E_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await C_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var k_=d.object({layerId:d.string().describe("The id of the layer to apply the color renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),O_=L(E_,{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:k_});function P_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,i,a,c=e[0];return o&&(a=il({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:c,normalizationField:i,theme:s,colorOptions:{colorScheme:a}}}async function M_(t){return await oy(t)}async function R_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=P_(c),u=await M_(l);return a.renderer=u.renderer,a.visible=!0,`Color-size-univariate renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function $_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await R_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var N_=d.object({layerId:d.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:d.array(d.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),L_=
|
|
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:k_});function P_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,i,a,c=e[0];return o&&(a=il({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:c,normalizationField:i,theme:s,colorOptions:{colorScheme:a}}}async function M_(t){return await oy(t)}async function R_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=P_(c),u=await M_(l);return a.renderer=u.renderer,a.visible=!0,`Color-size-univariate renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function $_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await R_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var N_=d.object({layerId:d.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:d.array(d.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),L_=L($_,{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:N_});function D_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=iy({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(i=>({field:i,label:r.fields.find(a=>a.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function F_(t){return await sy(t)}async function j_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"dot-density",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=D_(a),l=await F_(c);return i.renderer=l.renderer,i.visible=!0,`Dot Density renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function z_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await j_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var U_=d.object({layerId:d.string().describe("The id of the layer to apply the dot density renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),q_=
|
|
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:N_});function D_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=iy({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(i=>({field:i,label:r.fields.find(a=>a.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function F_(t){return await sy(t)}async function j_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"dot-density",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=D_(a),l=await F_(c);return i.renderer=l.renderer,i.visible=!0,`Dot Density renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function z_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await j_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var U_=d.object({layerId:d.string().describe("The id of the layer to apply the dot density renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),q_=L(z_,{name:"dot-density",description:`Dot Density
|
|
103
103
|
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
104
104
|
**Use cases:**
|
|
105
105
|
- Population distribution visualization
|
|
@@ -110,11 +110,11 @@ ${Object.keys(wp).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:U_});function B_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i=e[0];return o&&(s=ly({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:i,heatmapScheme:s}}async function K_(t){return await ay(t)}async function W_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"heatmap",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=B_(a),l=await K_(c);return i.renderer=l.renderer,i.visible=!0,`Heatmap renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function H_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await W_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var V_=d.object({layerId:d.string().describe("The id of the layer to apply the heatmap renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),G_=
|
|
113
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:U_});function B_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i=e[0];return o&&(s=ly({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:i,heatmapScheme:s}}async function K_(t){return await ay(t)}async function W_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"heatmap",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=B_(a),l=await K_(c);return i.renderer=l.renderer,i.visible=!0,`Heatmap renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function H_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await W_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var V_=d.object({layerId:d.string().describe("The id of the layer to apply the heatmap renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),G_=L(H_,{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:V_});function J_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s&&(i=uy({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(a=>({name:a})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:i}}async function Z_(t){return await cy(t)}async function Q_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"predominance-size":"predominance",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=J_(c),u=await Z_(l);return a.renderer=u.renderer,a.visible=!0,`Predominance renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function Y_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await Q_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var X_=d.object({layerId:d.string().describe("The id of the layer to apply the predominance renderer to"),fields:d.array(d.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),ew=
|
|
117
|
+
Fields: This typically requires zero or one field of type number.`,schema:V_});function J_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s&&(i=uy({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(a=>({name:a})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:i}}async function Z_(t){return await cy(t)}async function Q_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"predominance-size":"predominance",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=J_(c),u=await Z_(l);return a.renderer=u.renderer,a.visible=!0,`Predominance renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function Y_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await Q_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var X_=d.object({layerId:d.string().describe("The id of the layer to apply the predominance renderer to"),fields:d.array(d.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),ew=L(Y_,{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:V_});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:X_});function tw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i={field:e[0]},a={field:e[1]};return o&&(s=py({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:i,field2:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function rw(t){return await dy(t)}async function nw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"relationship",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=tw(a),l=await rw(c);return i.renderer=l.renderer,i.visible=!0,`Relationship renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function ow({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await nw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var sw=d.object({layerId:d.string().describe("The id of the layer to apply the relationship renderer to"),fields:d.array(d.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),iw=
|
|
127
|
+
Fields: This style relies on 2-10 number fields.`,schema:X_});function tw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i={field:e[0]},a={field:e[1]};return o&&(s=py({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:i,field2:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function rw(t){return await dy(t)}async function nw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"relationship",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=tw(a),l=await rw(c);return i.renderer=l.renderer,i.visible=!0,`Relationship renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function ow({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await nw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var sw=d.object({layerId:d.string().describe("The id of the layer to apply the relationship renderer to"),fields:d.array(d.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),iw=L(ow,{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:sw});function aw(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 lw(t){return await my(t)}async function cw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=aw(c),u=await lw(l);return a.renderer=u.renderer,a.visible=!0,`Size-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function uw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await cw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var dw=d.object({layerId:d.string().describe("The id of the layer to apply the size-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),pw=
|
|
131
|
+
Fields: This style requires two number fields.`,schema:sw});function aw(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 lw(t){return await my(t)}async function cw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=aw(c),u=await lw(l);return a.renderer=u.renderer,a.visible=!0,`Size-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function uw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await cw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var dw=d.object({layerId:d.string().describe("The id of the layer to apply the size-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),pw=L(uw,{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:dw});function mw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],i=e[0];return{layer:r,view:n,field:i,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function fw(t){return await fy(t)}async function hw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=mw(c),u=await fw(l);return a.renderer=u.renderer,a.visible=!0,`Size renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function gw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await hw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var yw=d.object({layerId:d.string().describe("The id of the layer to apply the size renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),_w=
|
|
135
|
+
Fields: This style requires at least one field with a date type.`,schema:dw});function mw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],i=e[0];return{layer:r,view:n,field:i,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function fw(t){return await fy(t)}async function hw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=mw(c),u=await fw(l);return a.renderer=u.renderer,a.visible=!0,`Size renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function gw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await hw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var yw=d.object({layerId:d.string().describe("The id of the layer to apply the size renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),_w=L(gw,{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:V_});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:yw});function ww(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],i=e[1],a=e[2],c;return o&&(c=gy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:i,field3:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function bw(t){return await hy(t)}async function
|
|
145
|
+
Fields: This style requires a single field with a date type.`,schema:yw});function ww(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],i=e[1],a=e[2],c;return o&&(c=gy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:i,field3:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function bw(t){return await hy(t)}async function Aw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"type",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=ww(c),u=await bw(l);return a.renderer=u.renderer,a.visible=!0,`Type renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function xw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await Aw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var vw=d.object({layerId:d.string().describe("The id of the layer to apply the type renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),Iw=L(xw,{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:vw}),Tw=E.Root({...St(),vectorSearchLayerIds:E(),vectorSearchFieldResults:E(),layerFieldInfo:E(),selectedLayerId:E()}),Sw=E.Root({...St(),vectorSearchLayerIds:E(),vectorSearchFieldResults:E(),layerFieldInfo:E(),queryResponse:E(),dataExplorationMessages:E({reducer:to,default:()=>[]})}),Cw=["mapView"];function Ct(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=Cw.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var Ew=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."},kw=async(t,e)=>{let{mapView:r}=Ct(e);return Ew(r)},GH=N(kw,{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:d.object({})}),Ow=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."},Pw=async(t,e)=>{let{mapView:r}=Ct(e);return await Ow(r)},JH=N(Pw,{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:d.object({})}),bp=750;function ei(t){return"point"in t&&t.point!==void 0}function Lo(t){return"layerId"in t&&t.layerId!==void 0}var ni=async(t,e)=>{if(ei(t)){let{point:r}=t;return{geometry:new Ap({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Lo(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:bp+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>bp)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let i=s.features.map(c=>c.geometry).filter(c=>!!c);if(!i.length)return{error:"No valid geometries found for the matched geometry layer features."};let a=i.length===1?i[0]:Ip.executeMany(i);return a?(a.spatialReference||(a.spatialReference=e.spatialReference),{geometry:a}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},Mw=async(t,e,r,n,o,s)=>{let i=t.map?.allLayers.find(c=>c.id===e);if(!i)return{success:!1,error:`Layer '${e}' not found.`};let a=i.createQuery();a.where=r??"1=1",n&&(a.geometry=n,a.spatialRelationship="intersects",o&&(a.distance=o),s&&(a.units=s));try{let{extent:c,count:l}=await i.queryExtent(a);return!c||l===0?{success:!1,error:`No features found for filter (where: ${a.where}${n?", spatial filter used":""})`}:(await t.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},Rw=async(t,e,r,n,o,s)=>{let i=e.map?.allLayers.find(m=>m.id===t.layerId);if(!i)return`Could not find target layer with ID: ${t.layerId}`;let a;if(o){let m=await ni(o,e);if("error"in m)return m.error;a=m.geometry}if(i.featureEffect=null,i.featureEffect=new yy({filter:new vp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:a,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),i.visible=!0,s)return`Applied feature effects to "${i.title??t.layerId}" within current map extent.`;let c=t.objectIds?.length?`${i.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await Mw(e,t.layerId,c,a,o?.distance,o?.units),u=i.title??t.layerId;return l.success?`Applied feature effects to target layer "${i.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${u}" but no features matched. ${l.error}`},$w=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Et=d.enum($w),Nw=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:i}=Ct(s);return await Rw(t,i,n,o,e,r)},Lw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Et.optional().describe("The units for the distance buffer.")}),Dw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Et.optional().describe("The units for the distance buffer.")}),Fw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.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:d.union([Lw,Dw]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.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:d.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:d.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.")}),ZH=N(Nw,{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:Fw}),Ya=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},jw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,zw=t=>{if(typeof t=="string"&&t)return t;let e=Ya(t);return e?e.toISOString().slice(0,10):null};var Uw=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=zw(t);return s?_y(s,Qs("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return wy(t,Qs("long-time"));let s=Ya(t);return s?yp(s,{...Qs("long-time"),timeZone:"UTC"}):t}let o=Ya(t);return o?yp(o,{...Qs("short-date-short-time"),timeZone:jw(r)}):t},Sp=(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(i=>i.code===e);return s?s.name:null}}return null},qw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Bw=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},Kw=(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}},Ww=(t,e,r)=>{let n=Bw(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=qw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Cp=(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"?Kw(r,s):s?.type==="date-time"?Ww(r,s,o):Uw(r,n,o)},Hw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Sp(e,r,t)??r;return Ep(t,e,s,o?.type,n)},Vw=(t,e)=>Cp(t,e),kp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(i=>i.attributes[n]),s=e.features.map(i=>{let a=i.attributes,c={};return t.fields.forEach(l=>{if(!Object.hasOwn(a,l.name))return;let u=a[l.name];if(l.name===n){c[l.name]=u;return}let m=Sp(l.name,u,t)??u,f=Cp(t,l.name);c[f]=Ep(t,l.name,m,l.type,r)}),c});return{objectIds:o,attributes:s}},Gw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Jw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(u=>u.id===t),s=Gw(o,e,r.where),i=(await o.queryFeatures(s)).features[0],a=i?i.attributes[e]:null,c=Hw(o,e,a,n.timeZone),l=Vw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${c}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:c,where:r.where}}};async function Zw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Ct(n),s=await Jw(t,e,r,o);return JSON.stringify(s,null,2)}var Qw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Yw=N(Zw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Qw}),al=(t,e,r)=>r?t.hasAllFeaturesInView&&t.availableFields===e:t.hasAllFeatures&&t.availableFields===e;function ti(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Xw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:i}=t,a=o.map?.allLayers.find(g=>g.id===e.layerId);if(!a)throw new Error(`Layer '${e.layerId}' not found.`);let c=await o.whenLayerView(a),l=s.get(e.layerId)?.fieldRegistry.get(r),u=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(i){let g=await ni(i,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Lo(i)?new Error(`No features found matching: ${i.where}`):new Error("Failed to create geometry");if(Lo(i)){let v=o.map?.allLayers.find(S=>S.id===i.layerId);m={geometryLayerName:v?.title??v?.id,geometryLayerId:i.layerId,geometryWhere:i.where,distance:i.distance,units:i.units,applied:!0}}else ei(i)&&(m={point:i.point,distance:i.distance,units:i.units,applied:!0});f=new vp({geometry:g.geometry,distance:i.distance,units:i.units,spatialRelationship:"intersects"})}let h=al(c,[r],!1),w=null,x=null,I=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:a,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:ti(a.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await by(g);let v=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(v.includes(l.type)||S)&&(x=(await xy({layer:a,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:ti(a.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((L,z)=>z.count-L.count).slice(0,I)),x&&l.domain?.type==="coded-value"&&(x=x.map(L=>({...L,value:S?S.getName(L.value)??L.value:L.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:a.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:x,where:e.where,spatialFilterInfo:m}}};async function eb({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Wn(o,"layersAndFieldsRegistry"),{mapView:i}=Ct(o),a=await Xw({targetLayer:t,fieldName:e,statisticType:r,mapView:i,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(a,null,2)}var tb=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Et.optional().describe("The units for the distance buffer.")}),rb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Et.optional().describe("The units for the distance buffer.")}),nb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([tb,rb]).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:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),ob=N(eb,{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:vw}),Tw=E.Root({...St(),vectorSearchLayerIds:E(),vectorSearchFieldResults:E(),layerFieldInfo:E(),selectedLayerId:E()}),Sw=E.Root({...St(),vectorSearchLayerIds:E(),vectorSearchFieldResults:E(),layerFieldInfo:E(),queryResponse:E(),dataExplorationMessages:E({reducer:to,default:()=>[]})}),Cw=["mapView"];function Ct(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=Cw.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var Ew=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."},kw=async(t,e)=>{let{mapView:r}=Ct(e);return Ew(r)},GH=L(kw,{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:d.object({})}),Ow=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."},Pw=async(t,e)=>{let{mapView:r}=Ct(e);return await Ow(r)},JH=L(Pw,{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:d.object({})}),bp=750;function ti(t){return"point"in t&&t.point!==void 0}function Lo(t){return"layerId"in t&&t.layerId!==void 0}var oi=async(t,e)=>{if(ti(t)){let{point:r}=t;return{geometry:new xp({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Lo(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:bp+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>bp)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let i=s.features.map(c=>c.geometry).filter(c=>!!c);if(!i.length)return{error:"No valid geometries found for the matched geometry layer features."};let a=i.length===1?i[0]:Ip.executeMany(i);return a?(a.spatialReference||(a.spatialReference=e.spatialReference),{geometry:a}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},Mw=async(t,e,r,n,o,s)=>{let i=t.map?.allLayers.find(c=>c.id===e);if(!i)return{success:!1,error:`Layer '${e}' not found.`};let a=i.createQuery();a.where=r??"1=1",n&&(a.geometry=n,a.spatialRelationship="intersects",o&&(a.distance=o),s&&(a.units=s));try{let{extent:c,count:l}=await i.queryExtent(a);return!c||l===0?{success:!1,error:`No features found for filter (where: ${a.where}${n?", spatial filter used":""})`}:(await t.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},Rw=async(t,e,r,n,o,s)=>{let i=e.map?.allLayers.find(m=>m.id===t.layerId);if(!i)return`Could not find target layer with ID: ${t.layerId}`;let a;if(o){let m=await oi(o,e);if("error"in m)return m.error;a=m.geometry}if(i.featureEffect=null,i.featureEffect=new yy({filter:new vp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:a,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),i.visible=!0,s)return`Applied feature effects to "${i.title??t.layerId}" within current map extent.`;let c=t.objectIds?.length?`${i.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await Mw(e,t.layerId,c,a,o?.distance,o?.units),u=i.title??t.layerId;return l.success?`Applied feature effects to target layer "${i.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${u}" but no features matched. ${l.error}`},$w=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Et=d.enum($w),Nw=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:i}=Ct(s);return await Rw(t,i,n,o,e,r)},Lw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Et.optional().describe("The units for the distance buffer.")}),Dw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Et.optional().describe("The units for the distance buffer.")}),Fw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.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:d.union([Lw,Dw]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.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:d.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:d.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.")}),ZH=L(Nw,{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:Fw}),Ya=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},jw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,zw=t=>{if(typeof t=="string"&&t)return t;let e=Ya(t);return e?e.toISOString().slice(0,10):null};var Uw=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=zw(t);return s?_y(s,Ys("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return wy(t,Ys("long-time"));let s=Ya(t);return s?yp(s,{...Ys("long-time"),timeZone:"UTC"}):t}let o=Ya(t);return o?yp(o,{...Ys("short-date-short-time"),timeZone:jw(r)}):t},Sp=(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(i=>i.code===e);return s?s.name:null}}return null},qw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Bw=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},Kw=(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}},Ww=(t,e,r)=>{let n=Bw(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=qw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Cp=(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"?Kw(r,s):s?.type==="date-time"?Ww(r,s,o):Uw(r,n,o)},Hw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Sp(e,r,t)??r;return Ep(t,e,s,o?.type,n)},Vw=(t,e)=>Cp(t,e),kp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(i=>i.attributes[n]),s=e.features.map(i=>{let a=i.attributes,c={};return t.fields.forEach(l=>{if(!Object.hasOwn(a,l.name))return;let u=a[l.name];if(l.name===n){c[l.name]=u;return}let m=Sp(l.name,u,t)??u,f=Cp(t,l.name);c[f]=Ep(t,l.name,m,l.type,r)}),c});return{objectIds:o,attributes:s}},Gw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Jw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(u=>u.id===t),s=Gw(o,e,r.where),i=(await o.queryFeatures(s)).features[0],a=i?i.attributes[e]:null,c=Hw(o,e,a,n.timeZone),l=Vw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${c}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:c,where:r.where}}};async function Zw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Ct(n),s=await Jw(t,e,r,o);return JSON.stringify(s,null,2)}var Qw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Yw=L(Zw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Qw}),al=(t,e,r)=>r?t.hasAllFeaturesInView&&t.availableFields===e:t.hasAllFeatures&&t.availableFields===e;function ri(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Xw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:i}=t,a=o.map?.allLayers.find(g=>g.id===e.layerId);if(!a)throw new Error(`Layer '${e.layerId}' not found.`);let c=await o.whenLayerView(a),l=s.get(e.layerId)?.fieldRegistry.get(r),u=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(i){let g=await oi(i,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Lo(i)?new Error(`No features found matching: ${i.where}`):new Error("Failed to create geometry");if(Lo(i)){let v=o.map?.allLayers.find(S=>S.id===i.layerId);m={geometryLayerName:v?.title??v?.id,geometryLayerId:i.layerId,geometryWhere:i.where,distance:i.distance,units:i.units,applied:!0}}else ti(i)&&(m={point:i.point,distance:i.distance,units:i.units,applied:!0});f=new vp({geometry:g.geometry,distance:i.distance,units:i.units,spatialRelationship:"intersects"})}let h=al(c,[r],!1),w=null,A=null,I=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:a,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:ri(a.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await by(g);let v=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(v.includes(l.type)||S)&&(A=(await Ay({layer:a,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:ri(a.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort(($,z)=>z.count-$.count).slice(0,I)),A&&l.domain?.type==="coded-value"&&(A=A.map($=>({...$,value:S?S.getName($.value)??$.value:$.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:a.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:A,where:e.where,spatialFilterInfo:m}}};async function eb({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Wn(o,"layersAndFieldsRegistry"),{mapView:i}=Ct(o),a=await Xw({targetLayer:t,fieldName:e,statisticType:r,mapView:i,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(a,null,2)}var tb=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Et.optional().describe("The units for the distance buffer.")}),rb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Et.optional().describe("The units for the distance buffer.")}),nb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([tb,rb]).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:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),ob=L(eb,{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:nb}),sb=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),i=await r.whenLayerView(s),a=s.title??t.layerId,c;if(n){let f=await
|
|
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:nb}),sb=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),i=await r.whenLayerView(s),a=s.title??t.layerId,c;if(n){let f=await oi(n,r);if("error"in f)return{tool:"getTopFeatures",layerName:a,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:a,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};c=f.geometry}else o&&(c=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,u=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])];try{let f;if(l){let A=new xy({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new vy({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(A)}else{let A=s.createQuery();A.where=ri(s.definitionExpression,t.where||"1=1"),A.outFields=m.length?m:["*"],A.orderByFields=e.orderByFields,A.num=e.topCount,c&&(A.geometry=c,A.spatialRelationship="intersects"),n?.distance&&(A.distance=n.distance),n?.units&&(A.units=n.units),A.outSpatialReference=r.spatialReference;let I=al(i,t.outFields,o??!1);try{f=I?await i.queryFeatures(A):await s.queryFeatures(A)}catch(g){console.warn("Client-side query failed, falling back to server:",g),f=await s.queryFeatures(A)}}let h=f.features.map(A=>A.attributes[u]),{attributes:w}=kp(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:a,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:h,objectIdField:u,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:a,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},ib=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Ct(o),i=await sb(t,e,s,r,n);return JSON.stringify(i,null,2)},ab=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Et.optional().describe("The units for the distance buffer.")}),lb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Et.optional().describe("The units for the distance buffer.")}),cb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.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:d.union([ab,lb]).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:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:d.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).")}),ub=L(ib,{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:cb}),Qa=25,db=async(t,e,r,n)=>{let o=e.map?.allLayers.find(A=>A.id===t.layerId),s=await e.whenLayerView(o),i=o.title??t.layerId,a;if(r){let A=await oi(r,e);if("error"in A){let I={error:A.error};if(Lo(r)){let g=e.map?.allLayers.find(v=>v.id===r.layerId);I.geometryLayerName=g?.title??g?.id,I.geometryLayerId=r.layerId,I.geometryWhere=r.where}else ti(r)&&(I.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"Geometry lookup failed",details:I}}if(!A.geometry){let I={};if(Lo(r)){let g=e.map?.allLayers.find(v=>v.id===r.layerId);I.error=`No features found matching: ${r.where}`,I.geometryLayerName=g?.title??g?.id,I.geometryLayerId=r.layerId,I.geometryWhere=r.where}else ti(r)&&(I.error="Failed to create point geometry",I.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"No features found for geometry filter",details:I}}a=A.geometry}else n&&(a=e.extent.clone());let c=al(s,t.outFields,n??!1),l=o.objectIdField,u=o.createQuery();u.where=ri(o.definitionExpression,t.where||"1=1"),u.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,l])],u.orderByFields=t.orderByFields,a&&(u.geometry=a,u.spatialRelationship="intersects"),r?.distance&&(u.distance=r.distance),r?.units&&(u.units=r.units),u.outSpatialReference=e.spatialReference;let m,f;try{m=c?await s.queryFeatureCount(u):await o.queryFeatureCount(u),m>0&&m<=Qa&&(f=c?await s.queryFeatures(u):await o.queryFeatures(u))}catch(A){console.warn("Client-side query failed, falling back to server:",A),m=await o.queryFeatureCount(u),m>0&&m<=Qa&&(f=await o.queryFeatures(u))}let{objectIds:h,attributes:w}=f?kp(o,f,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:i,summary:`${m} features found`,details:{totalCount:m,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...h&&{objectIds:h,objectIdField:l},...w&&{attributes:w},...m>Qa&&{note:`${m} features found.`}}}};async function pb({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Ct(n),s=await db(t,o,e,r);return JSON.stringify(s,null,2)}var mb=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Et.optional().describe("The units for the distance buffer.")}),fb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.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:d.number().optional().describe("Optional buffer distance around the point."),units:Et.optional().describe("The units for the distance buffer.")}),hb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.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:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.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:d.union([mb,fb]).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:d.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).")}),gb=L(pb,{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
|
|
@@ -170,23 +170,23 @@ USE THIS TOOL FOR:
|
|
|
170
170
|
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:hb}),Op=[Yw,ob,ub,gb];var QH=new ot(Op,{handleToolErrors:!1});var yb=E.Root({...St(),helpInternalState:E({reducer:No,default:()=>({toolCallMessage:void 0})})}),_b=(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(i=>i.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}`},wb=async({layerTitle:t},e)=>{let r=Wn(e,"layersAndFieldsRegistry");return _b(r,t)},bb=
|
|
174
|
-
Relationship Types: ${n}.`}},Do=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=Ib(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Tb(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}},el=class extends Do{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Do.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},vb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Ib=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Tb(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
|
|
173
|
+
${o}`},wb=async({layerTitle:t},e)=>{let r=Wn(e,"layersAndFieldsRegistry");return _b(r,t)},bb=L(wb,{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:d.object({layerTitle:d.string().describe("The title or partial title of the layer to list fields for.")})}),Ab=E.Root({...St(),intent:E({reducer:(t,e)=>e}),arcgisKnowledgeMessages:E({reducer:to,default:()=>[]}),arcgisKnowledgeToolResult:E({reducer:(t,e)=>e,default:()=>null})});function Pp(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 Hn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function si(t){!t||Hn(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Fo(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)&&Pp(r),{view:r}}async function Vn(t){let e=t?.configurable?.context;if(xb(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 _p(n)}}else{Pp(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 _p(n)}}}}function xb(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 Xa=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ni.fromDataModel(e)}},ni=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(Do.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(el.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:vb(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}.`}},Do=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=Ib(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Tb(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}},el=class extends Do{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Do.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},vb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Ib=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Tb(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 ii(t){return t?.signal}async function Sb(t,e){let r=await st("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 Cb(t,e,r,n){let{graphQuery:o,explanation:s}=await ll(t,e,r,n);return{graphQuery:o,explanation:s}}async function ll(t,e,r,n,o){let s={message:await Sb(t,o),context:new Xa(e)},i=
|
|
181
|
+
${e.failedGraphQuery}`:`${t} ${r}`}async function Cb(t,e,r,n){let{graphQuery:o,explanation:s}=await ll(t,e,r,n);return{graphQuery:o,explanation:s}}async function ll(t,e,r,n,o){let s={message:await Sb(t,o),context:new Xa(e)},i=ii(n);await J({text:"Attempting to generate a cypher query from your prompt..."},n);let a=await hp(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:fp.findCredential(mr.getDefault().url)?.token??""},signal:i});if(a.httpStatus!==200)throw new Error(`Graph query service returned an error: ${a.httpStatus}`,{cause:a.data});let c=!1,l=Date.now(),u=a.data.sequenceNumber,m="",f="",h=1;for(;!c;){await new Promise(A=>setTimeout(A,1e3)),await J({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,h)}`},n),h=h%3+1;let w=await hp(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:a.data.conversationId,inquiryId:a.data.inquiryId,ackSequenceNumber:u}),headers:{"Content-Type":"application/json",token:fp.findCredential(mr.getDefault().url)?.token??""},signal:i});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||"",c=!0}else if(!w.data.hasMore)c=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");u=w.data.sequenceNumber}return{graphQuery:m,explanation:f}}function Eb(t,e){Bn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Bn(t,e){if(!(!t||typeof t!="object")){if(Ob(t))for(let r of t.path)Bn(r,e);else if(kb(t))e(t);else if(Array.isArray(t))for(let r of t)Bn(r,e);else if(Pb(t))for(let r of Object.values(t.properties??{}))Bn(r,e)}}function kb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Ob(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Pb(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Mb(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,i]of o)for(let a of s){let c=t.getMemberIdsByType(a.name);i.push(...c)}return{entityIds:r,relationshipIds:n}}function Rb(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(a=>a.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]],i=!0;for(let[a,c]of s)for(let l of a){let u=o.namedTypeDefinitions.get(l.name);if(!u){i=!1,n.push(l.name);continue}if(!u.useAllData){i=!1,n.push(l.name);for(let[m]of u.members||[])c.push(m)}}return{allNamedTypesFullyDynamic:i,bindParameters:r,nonDynamicTypes:n}}var Kn=3;function Mp(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 Gn(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 $b=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:i})=>{let a=null,c=r,l=new AbortController,u=o?.signal,m=()=>{l.abort(u?.reason)};u&&(u.aborted?l.abort(u.reason):u.addEventListener("abort",m,{once:!0}));try{let f=await Ty(t,e,o);a=f.resultHeader;let h=f.resultRowsStream.getReader(),w=0,A=Date.now(),I=!1;for(;;){let{done:g,value:v}=await h.read();if(g)break;if(!I&&i&&Date.now()-A>i)return l.abort(),{type:"timeout"};for(let S of v){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:a,processedResult:c};c=n(c,S)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Gn(f),error:f}}finally{u?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:a,processedResult:c}};async function Rp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c,config:l}){let u;for(let m=1;m<=Kn;m++){let f;try{f=await ll(t,r.dataModel,n,l,u)}catch(A){return{type:"generation-error",errorMessage:Gn(A),error:A}}await J({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let h=await $b({kg:r,queryParams:new Tp({openCypherQuery:f.graphQuery,bindParameters:e}),targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c}),w=h.type==="aborted"?"Query execution was aborted.":h.type==="timeout"?"Query execution timed out.":h.type==="error"?`Query failed with error: ${h.errorMessage}`:"";if(h.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:h.rowLimitReached,resultHeader:h.resultHeader,processedResult:h.processedResult};if(h.type==="aborted")return{type:"aborted",errorMessage:w,graphQuery:f.graphQuery,explanation:f.explanation};if(m>=Kn)return h.type==="timeout"?{type:"timeout",errorMessage:w,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:w,error:h.error,graphQuery:f.graphQuery,explanation:f.explanation};u={failedGraphQuery:f.graphQuery,executionError:w,attemptCount:m},await J({text:`Attempt ${m} failed with error: ${w}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Kn} attempts.`)}var Nb=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let i=[],a=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(a=["entity","relationship"]);let c=o??1/0;try{for(let l of a){let u=c-i.length;if(u<=0)break;let m=(await Sy(t,new Cy({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:u}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:h,value:w}=await m.read();if(h){f=!0;break}for(let A of w)for(let I of A)i.push(I)}}}catch(l){let u=Gn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:u,error:l}:{type:"error",errorMessage:u,error:l}}return{type:"success",results:i}},$p="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Np({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push($p),!Hn(e)){let u=await st("arcgis_knowledge_current_lc_context"),m=Mb(e.map,r);return o.push(u),{enhancedPrompt:o.join(`
|
|
182
182
|
|
|
183
183
|
`),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:i,bindParameters:a,nonDynamicTypes:c}=Rb(s,r);if(i)return{enhancedPrompt:o.join(`
|
|
184
184
|
|
|
185
185
|
`),bindParameters:a,allNamedTypesFullyDynamic:!0};let l=(await st("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(c));return o.push(l),{enhancedPrompt:o.join(`
|
|
186
186
|
|
|
187
|
-
`),bindParameters:a,allNamedTypesFullyDynamic:i}}async function Lb(t,e,r,n,o,s){let{view:i}=o,a=await Rp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,h)=>{for(let w of h)Eb(w,f);return f},requestOptions:{signal:
|
|
187
|
+
`),bindParameters:a,allNamedTypesFullyDynamic:i}}async function Lb(t,e,r,n,o,s){let{view:i}=o,a=await Rp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,h)=>{for(let w of h)Eb(w,f);return f},requestOptions:{signal:ii(s),timeout:s?.timeout},config:s});if(a.type!=="success"){let f=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:c,explanation:l,processedResult:u}=a,m=Array.from(u.values());return await J({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Hn(i)&&i?.map?(await i.map.addRecords(m),await si(i),{generatedQuery:c,explanation:l,addedIdTypePairs:m}):(await i?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:c,explanation:l,addedIdTypePairs:m})}var Xs="addRecords",Db=d.object({prompt:d.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.")}),Fb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Vn(e),n=Fo(e),{view:o}=n,s=mr.getDefault().helperServices,{enhancedPrompt:i,bindParameters:a,allNamedTypesFullyDynamic:c}=await Np({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(c)return{toolName:Xs,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:u,addedIdTypePairs:m}=await Lb(i,a,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Xs,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
|
|
188
188
|
|
|
189
|
-
Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:u,addedIdTypePairs:m}}}catch(l){let u=Gn(l);return{toolName:
|
|
189
|
+
Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:u,addedIdTypePairs:m}}}catch(l){let u=Gn(l);return{toolName:Xs,status:"error",errorMessage:`Failed to add records to the link chart. ${u}`,error:l}}},jb=L(Fb,{name:Xs,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:u,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:Db});async function zb(t,e){return await e.map?.applyLayout(t),await
|
|
199
|
+
`,schema:Db});async function zb(t,e){return await e.map?.applyLayout(t),await si(e),{appliedLayout:t}}var tl="applyLayout",Ub=d.object({layout:d.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")}),qb=async({layout:t},e)=>{let{view:r}=Fo(e);if(Hn(r))return{toolName:tl,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await zb(t,r);return{toolName:tl,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},Bb=L(qb,{name:tl,description:"Apply a diagram layout to the link chart",schema:Ub});async function Kb(t,e){return e.map?.changeNonspatialDataDisplay(t),await si(e),{appliedNonspatialDataDisplayMode:t}}var rl="changeNonspatialVisibility",Wb=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Hb=async({setting:t},e)=>{let{view:r}=Fo(e);if(Hn(r))return{toolName:rl,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await Kb(t,r);return{toolName:rl,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},Vb=L(Hb,{name:rl,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Wb});async function Gb(t,e,r,n,o){let s,i="";for(let a=1;a<=Kn;a++){let{graphQuery:c,explanation:l}=await ll(t,e.dataModel,r,o,s);try{await J({text:`Attempting to create link chart from derived query: ${c}`},o);let u=await Iy.fromCypherQuery(e,new Tp({openCypherQuery:c}));await J({text:"Link chart created successfully, loading..."},o),await u.load();let m=n.map;return n.map=u,await n.when(),await Ap.whenOnce(()=>!n.updating),u.entityCount===0&&u.relationshipCount===0?(n.map===u&&(n.map=m),u.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
|
|
200
200
|
${c}
|
|
201
201
|
|
|
202
|
-
Explanation: ${l}`}):(await
|
|
202
|
+
Explanation: ${l}`}):(await si(n),{type:"success",graphQuery:c,explanation:l})}catch(u){let m=Gn(u);if(a>=Kn){i=m;break}s={failedGraphQuery:c,executionError:m,attemptCount:a},await J({text:`Attempt ${a} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Kn} attempts. Last error: ${i}`}}var ei="createLinkChart",Jb=d.object({prompt:d.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.")}),Zb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Vn(e),{view:n}=Fo(e);if(Hn(n))return{toolName:ei,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=mr.getDefault().helperServices,s=await Gb(`${t}
|
|
203
203
|
|
|
204
|
-
${$p}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:
|
|
204
|
+
${$p}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:ei,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:i,explanation:a}=s;return{toolName:ei,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
|
|
205
205
|
${i}
|
|
206
206
|
|
|
207
|
-
Explanation: ${a}`,details:{generatedQuery:i,explanation:a}}}},Qb=
|
|
207
|
+
Explanation: ${a}`,details:{generatedQuery:i,explanation:a}}}},Qb=L(Zb,{name:ei,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:Jb}),nl="queryGraphData",Yb=d.object({prompt:d.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.")}),Xb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Vn(e),n=mr.getDefault().helperServices,o=t,s=null,i=null;try{({view:i}=Fo(e))}catch{}i&&({enhancedPrompt:o,bindParameters:s}=await Np({prompt:t,view:i,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let a=await Rp({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(A,I)=>(A.push(I),A),requestOptions:{signal:ii(e),timeout:e?.timeout},config:e});if(a.type!=="success"){let A=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;return{toolName:nl,status:"error",errorMessage:`Failed to query the knowledge graph. ${A}`,error:"error"in a?a.error:null}}let{graphQuery:c,explanation:l,processedResult:u,resultHeader:m}=a,f=m.headerKeys;for(let A of u)for(let I of A)Bn(I,g=>Mp(g));let h=50,w=u.slice(0,h).map(A=>JSON.stringify(A));return{toolName:nl,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
208
208
|
|
|
209
209
|
\`\`\`cypher
|
|
210
210
|
${c}
|
|
@@ -221,16 +221,16 @@ ${w.length>h?`Showing top ${h} results:
|
|
|
221
221
|
|
|
222
222
|
`}${w.join(`
|
|
223
223
|
`)}
|
|
224
|
-
`,details:{generatedQuery:c,explanation:l,resultHeader:m,queryResults:u}}},
|
|
224
|
+
`,details:{generatedQuery:c,explanation:l,resultHeader:m,queryResults:u}}},eA=L(Xb,{name:nl,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:Yb}),ol="generateCypher",tA=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),rA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Vn(e),n=mr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await Cb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:ol,status:"success",summary:`Generated Graph Query:
|
|
225
225
|
${o}
|
|
226
226
|
|
|
227
|
-
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Gn(o);return{toolName:ol,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},
|
|
227
|
+
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Gn(o);return{toolName:ol,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},nA=L(rA,{name:ol,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:tA}),oA=t=>{let e=t.dataModel,r=new Map;for(let a of e.searchIndexes)if(a.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[c,l]of a.searchProperties.entries()){let u=r.get(c)??new Set;l.propertyNames.forEach(m=>u.add(m)),r.set(c,u)}let n=e.entityTypes.filter(a=>r.has(a.name)),o=e.relationshipTypes.filter(a=>r.has(a.name)),s=`Entity Types:
|
|
228
228
|
${n.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
|
|
229
229
|
`)}`,i=`Relationship Types:
|
|
230
230
|
${o.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
|
|
231
231
|
`)}`;return`${s}
|
|
232
232
|
|
|
233
|
-
${i}`};async function
|
|
233
|
+
${i}`};async function sA(t,e,r){let n=await st("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:oA(e)},s=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),i=d.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."),a=d.array(d.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),c=d.object({query:d.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:a.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:i});return await $o({promptText:n,inputVariables:o,schema:c,config:r})}var sl="searchGraphData",iA=d.object({prompt:d.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.")}),aA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Vn(e);await J({text:"Generating search query for the user inquiry"},e);let n=await sA(t,r,e);await J({text:"Executing graph search with generated search query"},e);let o=await Nb({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:ii(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:sl,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let a of o.results)Bn(a,c=>Mp(c));let s=10,i=o.results.slice(0,s);return{toolName:sl,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 @@ ${i}`};async function sx(t,e,r){let n=await st("arcgis_knowledge_lucene_generati
|
|
|
241
241
|
${o.results.length>s?`Showing top ${s} results:
|
|
242
242
|
|
|
243
243
|
`:""}${i.map(a=>JSON.stringify(a)).join(`
|
|
244
|
-
`)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},
|
|
244
|
+
`)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},lA=L(aA,{name:sl,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 @@ ${i}`};async function sx(t,e,r){let n=await st("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:iA});var fV=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:
|
|
@@ -334,26 +334,26 @@ _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
|
|
338
|
-
`)}var Uo=(function(t){
|
|
337
|
+
_example: "What is the average age of all people who work for Esri?"_`;var dA=(t,e)=>{if(t.length!==e.length)throw new Error("Vectors must be the same length");let r=0,n=0,o=0;for(let a=0;a<t.length;++a){let c=t[a],l=e[a];r+=c*l,n+=c*c,o+=l*l}let s=Math.sqrt(n*o);if(s===0)return 0;let i=r/s;return Math.max(-1,Math.min(1,i))},Lp=Qs,kt=$o;var Pe=J,Dp=dp,Fp=dA;var li=()=>St();var ul={};El(ul,{JsonPatchError:()=>V,_areEquals:()=>qo,applyOperation:()=>fr,applyPatch:()=>Zn,applyReducer:()=>gA,deepClone:()=>fA,getValueByPointer:()=>mi,validate:()=>zp,validator:()=>fi});var pA=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),mA=Object.prototype.hasOwnProperty;function ui(t,e){return mA.call(t,e)}function di(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var o in t)ui(t,o)&&n.push(o);return n}function ce(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function pi(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function Ue(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function zo(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ci(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(ci(t[e]))return!0}else if(typeof t=="object"){for(var n=di(t),o=n.length,s=0;s<o;s++)if(ci(t[n[s]]))return!0}}return!1}function jp(t,e){var r=[t];for(var n in e){var o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(n+": "+o)}return r.join(`
|
|
338
|
+
`)}var Uo=(function(t){pA(e,t);function e(r,n,o,s,i){var a=this.constructor,c=t.call(this,jp(r,{name:n,index:o,operation:s,tree:i}))||this;return c.name=n,c.index=o,c.operation=s,c.tree=i,Object.setPrototypeOf(c,a.prototype),c.message=jp(r,{name:n,index:o,operation:s,tree:i}),c}return e})(Error);var V=Uo,fA=ce,Jn={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=mi(r,this.path);n&&(n=ce(n));var o=fr(r,{op:"remove",path:this.from}).removed;return fr(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=mi(r,this.from);return fr(r,{op:"add",path:this.path,value:ce(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:qo(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},hA={add:function(t,e,r){return pi(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Jn.move,copy:Jn.copy,test:Jn.test,_get:Jn._get};function mi(t,e){if(e=="")return t;var r={op:"_get",path:e};return fr(t,r),r.value}function fr(t,e,r,n,o,s){if(r===void 0&&(r=!1),n===void 0&&(n=!0),o===void 0&&(o=!0),s===void 0&&(s=0),r&&(typeof r=="function"?r(e,0,t,e.path):fi(e,0)),e.path===""){var i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=mi(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=qo(t,e.value),i.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new V("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=ce(t));var a=e.path||"",c=a.split("/"),l=t,u=1,m=c.length,f=void 0,h=void 0,w=void 0;for(typeof r=="function"?w=r:w=fi;;){if(h=c[u],h&&h.indexOf("~")!=-1&&(h=zo(h)),o&&(h=="__proto__"||h=="prototype"&&u>0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&f===void 0&&(l[h]===void 0?f=c.slice(0,u).join("/"):u==m-1&&(f=e.path),f!==void 0&&w(e,0,t,f)),u++,Array.isArray(l)){if(h==="-")h=l.length;else{if(r&&!pi(h))throw new V("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);pi(h)&&(h=~~h)}if(u>=m){if(r&&e.op==="add"&&h>l.length)throw new V("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var i=hA[e.op].call(e,l,h,t);if(i.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(u>=m){var i=Jn[e.op].call(e,l,h,t);if(i.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(l=l[h],r&&u<m&&(!l||typeof l!="object"))throw new V("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Zn(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new V("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=ce(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=fr(t,e[i],r,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function gA(t,e,r){var n=fr(t,e);if(n.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function fi(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new V("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Jn[t.op]){if(typeof t.path!="string")throw new V("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new V('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new V("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new V("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&ci(t.value))throw new V("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,s=n.split("/").length;if(o!==s+1&&o!==s)throw new V("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new V("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},a=zp([i],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new V("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new V("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function zp(t,e,r){try{if(!Array.isArray(t))throw new V("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Zn(ce(e),ce(t),r||!0);else{r=r||fi;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(o){if(o instanceof V)return o;throw o}}function qo(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),o,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!qo(t[o],e[o]))return!1;return!0}if(r!=n)return!1;var a=Object.keys(t);if(s=a.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=s;o--!==0;)if(i=a[o],!qo(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var fl={};El(fl,{compare:()=>IA,generate:()=>dl,observe:()=>vA,unobserve:()=>xA});var pl=new WeakMap,yA=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),_A=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function wA(t){return pl.get(t)}function bA(t,e){return t.observers.get(e)}function AA(t,e){t.observers.delete(e.callback)}function xA(t,e){e.unobserve()}function vA(t,e){var r=[],n,o=wA(t);if(!o)o=new yA(t),pl.set(t,o);else{var s=bA(o,e);n=s&&s.observer}if(n)return n;if(n={},o.value=ce(t),e){n.callback=e,n.next=null;var i=function(){dl(n)},a=function(){clearTimeout(n.next),n.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return n.patches=r,n.object=t,n.unobserve=function(){dl(n),clearTimeout(n.next),AA(o,n),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new _A(e,n)),n}function dl(t,e){e===void 0&&(e=!1);var r=pl.get(t.object);ml(r.value,t.object,t.patches,"",e),t.patches.length&&Zn(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function ml(t,e,r,n,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=di(e),i=di(t),a=!1,c=!1,l=i.length-1;l>=0;l--){var u=i[l],m=t[u];if(ui(e,u)&&!(e[u]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof m=="object"&&m!=null&&typeof f=="object"&&f!=null&&Array.isArray(m)===Array.isArray(f)?ml(m,f,r,n+"/"+Ue(u),o):m!==f&&(a=!0,o&&r.push({op:"test",path:n+"/"+Ue(u),value:ce(m)}),r.push({op:"replace",path:n+"/"+Ue(u),value:ce(f)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+Ue(u),value:ce(m)}),r.push({op:"remove",path:n+"/"+Ue(u)}),c=!0):(o&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),a=!0)}if(!(!c&&s.length==i.length))for(var l=0;l<s.length;l++){var u=s[l];!ui(t,u)&&e[u]!==void 0&&r.push({op:"add",path:n+"/"+Ue(u),value:ce(e[u])})}}}function IA(t,e,r){r===void 0&&(r=!1);var n=[];return ml(t,e,n,"",r),n}var xJ=Object.assign({},ul,fl,{JsonPatchError:Uo,deepClone:ce,escapePathComponent:Ue,unescapePathComponent:zo});var qp={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},CA={default:"text-embedding-ada-002"},hl=new Map,hi=null,EA=()=>{let t=Up.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},kA=async t=>{let e=EA();hl.size===0&&(hi||(hi=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>hl.set(o.name,o))}catch(n){throw hi=null,n}})()),await hi);let r=hl.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},OA=async(t="default")=>await kA(qp[t]);var gl=(t,e)=>e,PA=(t,e)=>({...t,...e}),MA=(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(`
|
|
339
339
|
|
|
340
340
|
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
341
341
|
|
|
342
|
-
${r}`},
|
|
342
|
+
${r}`},RA=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}});var zJ=E.Root({agentExecutionContext:E({default:RA,reducer:PA}),currentIntent:E({default:()=>"none",reducer:gl}),lastExecutedAgent:E({default:()=>"",reducer:gl}),requiresFollowUp:E({default:()=>!0,reducer:gl}),stepCount:E({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:E({default:()=>"",reducer:MA})});var $A=t=>async(e,r)=>{let n=new Headers(r?.headers);return n.delete("Authorization"),n.delete("api-key"),t&&t.length>0&&(n.set("X-Esri-Authorization",`Bearer ${t}`),n.set("X-Esri-Request-Source","MapsSDK")),await fetch(e,{...r,headers:n})},NA=async(t="default",e=0)=>{let r=Up.getDefault(),n=await TA.getCredential(`${r.url}/sharing`),o=qp[t],s=await OA(t);return new zn({modelName:o,apiKey:"dummy-key",...t!=="default"&&{temperature:e},configuration:{baseURL:s,fetch:$A(n.token)}})};var LA=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(LA);var DA="0.1",Bo=1536,FA="openai",jA=CA.default,zA=`Name: {name}
|
|
343
343
|
Title: {title}
|
|
344
|
-
Description: {description}`,
|
|
344
|
+
Description: {description}`,UA=`Name: {name}
|
|
345
345
|
Alias: {alias}
|
|
346
|
-
Description: {description}`,UJ=b.object({schemaVersion:b.literal(
|
|
346
|
+
Description: {description}`,UJ=b.object({schemaVersion:b.literal(DA),modified:b.number().int().nonnegative(),embeddings:b.object({modelProvider:b.literal(FA),model:b.literal(jA),dimensions:b.literal(Bo),templates:b.object({layer:b.string().default(zA),field:b.string().default(UA)})}),layers:b.array(b.object({id:b.string().min(1),name:b.string().min(1),title:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(Bo,{message:`Layer vector must be exactly ${Bo} dimensions`}),fields:b.array(b.object({name:b.string().min(1),alias:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(Bo,{message:`Field vector must be exactly ${Bo} dimensions`})}))})).default([])});var qA=(t,e)=>{let r=rs.fromTemplate(t);return ns.fromMessages([r,...e])};var Bp=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i}=t,a=qA(e,o??[]),c=(await NA(r,n)).withStructuredOutput(i);return await a.pipe(c).invoke(s??{})};var BA=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),qJ=d.object({fields:d.array(BA)});var BJ=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var HA=kl`:host{display:block;height:100%}.margin-lg{margin:var(--calcite-spacing-lg)}.display-flex-row{display:flex;flex-direction:row}.assistant-split-container{display:flex;width:100%;height:calc(100vh - 78px);overflow:hidden;border-radius:10px}.assistant-panel{display:flex;flex-direction:column;height:100%;border:1px solid var(--calcite-color-surface-3);background-color:var(--calcite-color-surface-2);overflow:hidden}.chat-panel{min-width:320px}.builder-panel{min-width:320px;max-width:100%;border-left:1px solid var(--calcite-color-surface-3)}.panel-actions{display:flex;gap:8px;padding:6px;align-items:center}.builder-header,.builder-footer{padding:10px;background:var(--calcite-color-surface-1);border-bottom:1px solid var(--calcite-color-surface-3)}.builder-content{flex:1;overflow:auto;padding:12px}.builder-content pre{white-space:pre-wrap;word-wrap:break-word;max-height:100%;overflow:auto}.builder-actions{display:flex;gap:6px;align-items:center}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-surface-4);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-surface-1);border-radius:10px;padding:10px}.chat-panel{--calcite-color-focus: var(--calcite-color-brand);--calcite-panel-border-color: var(--calcite-color-border-2);--calcite-internal-panel-header-vertical-padding: 0px;--calcite-panel-header-content-space: 0px;border:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);height:100%}.header-content{display:flex;align-items:center;gap:var(--calcite-spacing-sm);height:65px;box-sizing:border-box;padding-inline-start:var(--calcite-space-2xl)}@media(resolution:1.25dppx),(resolution:1.75dppx){.chat-panel{margin-top:.5px}}.header-title{font-size:var(--calcite-font-size-md);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-text-1)}.beta-chip{--calcite-chip-corner-radius: var(--calcite-corner-radius-half)}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button,.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-surface-1, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-surface-3);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-surface-4);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-surface-4)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;align-items:center;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-surface-1)}#closeAssistantButton{--calcite-action-text-color: var(--calcite-color-text-1)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-surface-1)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;async function Ae(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
|
|
347
347
|
Available prompts:
|
|
348
348
|
${Object.keys(t).join(`
|
|
349
|
-
`)}`);return await r[1]()}function wi(t){return t?.configurable?.context?.translations}function Hp(t){if(typeof window>"u"||t.length<=1)return;let e=t.map(n=>n.solution.id),r=t.map(n=>n.solution.title);window.dispatchEvent(new CustomEvent("searchTermSet",{detail:{scope:"all-solutions",searchTerm:""}})),window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant",{detail:{solutionIds:e,solutionTitles:r},bubbles:!0,composed:!0})),window.dispatchEvent(new CustomEvent("navTabSelected",{detail:{tabType:"all-solutions"}}))}function Vp(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var Vx=b.object({needsContext:b.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:b.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),Kp=t=>t?.signal?.aborted??!1,Gp=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./AS6VINEU.js").then(t=>t.default),"./prompts/transformQuery.md":()=>import("./MFVXFKKM.js").then(t=>t.default)});function Gx(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">[$1]</a></sup>')}function Jx(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function Zx(t,e){let r=[];return(e?.configurable?.context?.configContext.allCards??[]).forEach(n=>{let o=n.title;if(!o)return;let s=new RegExp(`(?<![\\p{L}\\p{N}])${o}(?![\\p{L}\\p{N}])`,"giu"),i=!1;t=t.replace(s,(a,c,l)=>{let u=l.slice(0,c);return/<img[^>]*alt\s*=\s*["'][^"']*$/i.test(u)?a:(i=!0,`<a href="" target="solutionId:${n.deployCommonId}">${o}</a>`)}),i&&r.push({solution:{title:n.title,id:n.deployCommonId,snippet:n.snippet,description:n.description},score:100})}),{source:t,allMatches:r}}function Qx(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function Jp(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function wl(t,e,r){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",token:r},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status} calling ${e}`);return n.json()}var Yx=t=>new Promise(e=>setTimeout(e,t));async function Xx(t,e){let r=t.agentExecutionContext.userRequest,n=e?.configurable?.context?.lastTurnAgent,o=t.agentExecutionContext.messages??[];if(!n||o.length<=1||n==="explorer")return r;try{let s=await xe(Gp,"transformQuery"),i=await kt({promptText:s,modelTier:"advanced",temperature:0,schema:Vx,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return console.debug(`Rephrased query from "${r}" to "${i.rewrittenQuery.trim()}"`),i.rewrittenQuery.trim()}catch{}return r}var eA=E.Root({...ai(),solutionResponse:E({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:E({reducer:(t,e)=>e??null,default:()=>null}),conversationId:E({reducer:(t,e)=>e??t,default:()=>null})}),tA=()=>new fe(eA).addNode("initializeAgent",nA).addNode("askSolutionsQuestions",rA).addEdge(me,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",K),Zp=async(t,e,r,n)=>{if(!t)return;let o=Jp(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:r,use_llm:!1}}}}};n&&(s.conversationId=n),wl(s,o,e??"")},rA=async(t,e)=>{if(Kp(e))return{};let r=wi(e),n=t.documentSkillUrl,o=[],s=await Xx(t,e);await Pe({text:r.agentProgress.explorerAgentSearching},e);let i=await wl({message:s,conversationId:e?.configurable?.context?.convoId??void 0,context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:e?.configurable?.context?.configContext.locale??"en",use_llm:!1}}}}},n,e?.configurable?.context?.token??"");i.conversationId&&e?.configurable?.context?.setConversationId&&e.configurable.context.setConversationId(i.conversationId);let a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},c="",l=async u=>{let m=u.context?.results?.[0]?.reply??"";if(m!==""){let h=Gx(m),w=Jx(h),x=Zx(w,e);c=x.source,o=[...o,...x.allMatches.filter(I=>!o.some(g=>g.solution.id===I.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let h="";f===1?h=r.agentProgress.explorerAgentReading:f===2?h=r.agentProgress.explorerAgentReviewing:f===3&&(h=r.agentProgress.explorerAgentPreparing),await Pe({text:h},e)}};for(await l(i);a.hasMore;){if(Kp(e))return{};await Yx(500),i=await wl({conversationId:a.conversationId,ackSequenceNumber:a.ackSequenceNumber,inquiryId:a.inquiryId},n,e?.configurable?.context?.token??""),a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},await l(i)}return Jp(e?.configurable?.context.portal)&&Zp(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?Vp(o[0].solution.id):Hp(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},nA=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=Qx(e.configurable.context.portal)),{documentSkillUrl:r}};await xe(Gp,"solutions_explorer_description");var Qp=t=>{if(t&&Array.isArray(t.id)&&t.id.length>0)return t.id[t.id.length-1].replace("Message","").toLowerCase();if(t&&typeof t._getType=="function")try{return t._getType()}catch{return"human"}return"human"},oA=t=>{let e=Qp(t);if(t&&t.kwargs)return{role:e,...t.kwargs};if(t&&typeof t=="object"){let r={role:e,content:typeof t.content=="string"?t.content:String(t.content||"")};return t.id&&(r.id=t.id),t.name&&(r.name=t.name),t.additional_kwargs&&(r.additional_kwargs=t.additional_kwargs),t.response_metadata&&(r.response_metadata=t.response_metadata),r}return{role:"human",content:String(t)}},sA=t=>Qp(t)==="human",iA=(t,e=3)=>t.filter(r=>sA(r)).slice(-e).map(oA),aA=(t,e=" ")=>iA(t).map(r=>r.content).join(e).trim(),lA={understandingRequest:"Understanding your request...",selectTemplatePrompt:"This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.",searchingExistingSolutions:"Searching for existing solutions...",existingSolutionMatch:"I found one or more existing solutions that match your use case. These are ready-to-use solutions that may already meet your needs and can be deployed now. Do you want to continue building your own solution?",continueBuildingYes:"Yes, I want to build a new solution",continueBuildingNo:"No, I\u2019ll review existing solutions",continueBuildingDeclined:"Sounds good. We can focus on existing solutions. Let me know if I can help answer any questions or provide more details.",creatingDesign:"Generating solution design...",updatingDesign:"Updating solution design...",applyChangeFailed:"I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.",createDesignFailed:"I wasn't able to create a solution design from that request. Please try rephrasing and try again.",discardMessage:"Are you sure you want to discard your solution?",discardForNewSolution:"I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?"},cA={builderMessages:lA},_i=class t{constructor(e,r,n=!0){this.isValid=!0,this.issues=[],this.fieldNameRegistry=null,this.response=e,this.template=r,this.newDesign=n,this.validate()}static{this.INVALID_NAME_CHARS=/[><~`$^+=|]/gu}static{this.NAME_MAX_LENGTH=250}static{this.DESCRIPTION_MAX_LENGTH=2048}static{this.FIELD_NAME_MAX_LENGTH=31}validate(){this.compareModels(),this.validateResponse()}compareModels(){this._compareStrings(),this._compareItems(),this._compareFeatureLayers()}validateResponse(){this._validateSolutionProps(),this._validateItems(),this._validateFeatureLayer()}_compareStrings(){let e=new Set(this.response.solution.strings.map(n=>n.key)),r=new Map(this.template.solution.strings.map(n=>[n.key,n]));[...r.keys()].every(n=>e.has(n))||(this.newDesign?this._reconcileStringKeys():this._logIssue("String keys in llm response do not match the template."));for(let n of this.response.solution.strings){if(n.value)continue;let o=r.get(n.key)?.value;this.newDesign&&o?(n.value=o,this._logAutoFix(`String key '${n.key}' had no value. Auto-fixed by restoring the template value.`)):this._logIssue(`String key '${n.key}' has no value in the design. It must be populated.`)}}_reconcileStringKeys(){let e=new Set(this.response.solution.strings.map(r=>r.key));for(let r of this.template.solution.strings)e.has(r.key)||(this.response.solution.strings.push({...r}),this._logAutoFix(`String key '${r.key}' was missing from the design. Auto-fixed by re-adding it from the template.`))}_compareItems(){let e=new Set(this.template.items.map(n=>n.id)),r=new Set(this.response.items.map(n=>n.id));e.size===r.size&&[...e].every(n=>r.has(n))||(this.newDesign?this._reconcileItems():this._logIssue("Item IDs in design do not match the template."))}_reconcileItems(){let e=new Set(this.template.items.map(i=>i.id)),r=new Set(this.response.items.map(i=>i.id)),n=[...r].filter(i=>!e.has(i)),o=[...e].filter(i=>!r.has(i));if(e.size===r.size&&n.length===1&&o.length===1){let i=n[0],a=o[0],c=this.response.items.find(l=>l.id===i);if(c){c.id=a,this._logAutoFix(`Item id '${i}' did not match the template id '${a}'. Auto-fixed in place.`);return}}n.length&&(this.response.items=this.response.items.filter(i=>e.has(i.id)),this._logAutoFix(`Removed items not present in the template: ${n.join(", ")}.`));let s=this.template.items.filter(i=>!r.has(i.id));if(s.length){this.response.items=[...s.map(i=>({...i})),...this.response.items];for(let i of s)this._logAutoFix(`Item '${i.id}' was missing from the design. Auto-fixed by adding it from the template.`)}}_compareFeatureLayers(){let e=this.template.featureLayer,r=this.response.featureLayer;if(e.itemId!==r.itemId){let n=r.itemId;r.itemId=e.itemId,this._logAutoFix(`Feature Layer itemId '${n}' did not match the template. Auto-fixed to '${e.itemId}'.`)}if(!e.addLayers){let n=new Set(e.layers.map(s=>s.id)),o=new Set(r.layers.map(s=>s.id));if(!(n.size===o.size&&[...n].every(s=>o.has(s))))this._logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`);else for(let s of e.layers){if(s.type){let a=r.layers.find(c=>c.id===s.id);if(a&&a.type!==s.type)if(this.newDesign){let c=a.type;a.type=s.type,this._logAutoFix(`Layer '${s.id}' type '${c}' is immutable. Auto-fixed back to template type '${s.type}'.`)}else this._logIssue(`Layer '${s.id}' type '${a.type}' does not match template type '${s.type}'. This layer type is immutable.`)}let i=r.layers.find(a=>a.id===s.id);i&&this._validateRequiredFields(i,s)}}}_validateRequiredFields(e,r){let n=new Map(e.requiredFields.map(o=>[o.name.toLowerCase(),o]));for(let o of r.requiredFields){let s=n.get(o.name.toLowerCase());if(!s){this.newDesign?(e.requiredFields.push({...o}),this._logAutoFix(`Layer '${e.name}' was missing required field '${o.name}'. Auto-fixed by re-adding it from the template.`)):this._logIssue(`Layer '${e.name}' is missing required field '${o.name}'.`);continue}this._enforceRequiredFieldImmutability(e,s,o)}}_enforceRequiredFieldImmutability(e,r,n){let o=[];if(r.type!==n.type&&o.push("type"),(r.length??null)!==(n.length??null)&&o.push("length"),this._choiceListsEqual(r.choiceList,n.choiceList)||o.push("choiceList"),!o.length)return;let s=o.length===1?"property":"properties";this.newDesign?(r.type=n.type,r.length=n.length,r.choiceList=Array.isArray(n.choiceList)?[...n.choiceList]:n.choiceList??null,this._logAutoFix(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). Auto-fixed by reverting to the template.`)):this._logIssue(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). These cannot be modified.`)}_choiceListsEqual(e,r){let n=Array.isArray(e)?e:null,o=Array.isArray(r)?r:null;if(n===null&&o===null)return!0;if(n===null||o===null)return!1;let s=new Set(n),i=new Set(o);return s.size===i.size&&[...s].every(a=>i.has(a))}_validateSolutionProps(){let e=this.response.solution.title??"",r=this.response.solution.description,n=/[/\\]/u.test(e),o=this.newDesign?e.replace(/[/\\]/gu,""):e;this.newDesign&&o!==e?(this.response.solution.title=o,this._logAutoFix("Solution title contained forward or back slashes. Auto-fixed by removing them.")):!this.newDesign&&n&&this._logIssue("Solution title contains forbidden forward or back slashes.");let s=is(o);if(s.isValid||this._tryFixName(s.errorType,o,i=>{this.response.solution.title=i},"Solution title","Solution Title")||this._logIssue(`Solution title is invalid (${s.errorType}).`),r){let i=as(r,t.DESCRIPTION_MAX_LENGTH,!0);i.isValid||this._tryFixDescription(r,a=>{this.response.solution.description=a},"Solution description")||this._logIssue(`Solution description is invalid (${i.errorType}).`)}}_validateItems(){for(let e of this.response.items){let r=is(e.title??"");if(r.isValid||this._tryFixName(r.errorType,e.title??"",n=>{e.title=n},`Item '${e.id}' title`,"Item Title")||this._logIssue(`Item '${e.id}' title is invalid (${r.errorType}).`),e.description){let n=as(e.description,t.DESCRIPTION_MAX_LENGTH,!0);n.isValid||this._tryFixDescription(e.description,o=>{e.description=o},`Item '${e.id}' description`)||this._logIssue(`Item '${e.id}' description is invalid (${n.errorType}).`)}}}_validateFeatureLayer(){this.response.featureLayer.layers.length||this._logIssue("Feature layer item must contain at least one layer.");let e=this.response.featureLayer.layers.map(r=>r.name.toLowerCase());e.length!==new Set(e).size&&(this.newDesign?this._dedupeLayerNames(this.response.featureLayer.layers):this._logIssue(`Layer names must be unique (case-insensitive). Layer names in design: ${e}.`));for(let r of this.response.featureLayer.layers)this._validateLayer(r,this.response.featureLayer.addLayers)}_dedupeLayerNames(e){let r=new Set;for(let n of e){let o=(n.name??"").toLowerCase();if(r.has(o)){let s=n.name;n.name=this._makeUniqueName(n.name??"Layer",r),this._logAutoFix(`Duplicate layer name '${s}'. Auto-fixed to '${n.name}'.`)}r.add(n.name.toLowerCase())}}_validateLayer(e,r){!r&&e.typeMutable===!0&&e.type==="Table"&&(this.newDesign?(e.type="Point",this._logAutoFix(`Layer '${e.name}' cannot be a Table. Auto-fixed to 'Point'.`)):this._logIssue(`Layer '${e.name}' cannot be a Table. It may be a Point, Line, or Polygon.`));let n=is(e.name??"");if(n.isValid||this._tryFixName(n.errorType,e.name??"",o=>{e.name=o},`Layer '${e.name}' name`,"Layer Title")||this._logIssue(`Layer '${e.name}' name is invalid (${n.errorType}).`),e.description){let o=as(e.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(e.description,s=>{e.description=s},`Layer '${e.name}' description`)||this._logIssue(`Layer '${e.name}' description is invalid (${o.errorType}).`)}this._validateLayerFields(e)}_validateLayerFields(e){let r=e.systemFields??[];this.fieldNameRegistry=new Set([...e.customFields,...e.requiredFields,...r].map(s=>s.name.toLowerCase()));for(let s of[...e.customFields,...e.requiredFields])this._validateField(s);this.fieldNameRegistry=null;let n=new Set(e.requiredFields.map(s=>s.name.toLowerCase())),o=new Set(n);for(let s of e.customFields){let i=s.name.toLowerCase();if(o.has(i)){let a=n.has(i)?"a required field name":"another field with the same name";if(this.newDesign){let c=s.name;s.name=this._makeUniqueName(s.name,o),this._logAutoFix(`Layer '${e.name}' field '${c}' collided with ${a}. Auto-fixed to '${s.name}'.`)}else this._logIssue(`Layer '${e.name}' field '${s.name}' collides with ${a}.`)}o.add(s.name.toLowerCase())}}_validateField(e){let r=/^\p{L}/u,n=/^.[\p{L}\p{M}\p{N}_]*$/u;e.alias||(this.newDesign?(e.alias=e.name,this._logAutoFix(`Field '${e.name}' had no display name (alias). Auto-fixed to '${e.alias}'.`)):this._logIssue(`Field '${e.name}' has no display name (alias).`));let o=r.test(e.name),s=n.test(e.name);if(!o||!s)if(this.newDesign){let i=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' had an invalid name. Auto-fixed to '${e.name}'.`)}else o||this._logIssue(`Field '${e.name}' does not start with a letter.`),s||this._logIssue(`Field '${e.name}' contains invalid characters (only letters from any writing system, numbers, and underscores are allowed; emojis and punctuation are not allowed).`);if(e.name.length>t.FIELD_NAME_MAX_LENGTH)if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters.`);if(lc.has(e.name.toLowerCase()))if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(i,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(cc.has(e.name.toLowerCase()))if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(i,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' is a reserved system field name. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a reserved system field name.`);if(Array.isArray(e.choiceList)&&e.type!=="string"&&(this.newDesign?e.choiceList.length?(e.type="string",this._logAutoFix(`Field '${e.name}' had a domain but was not of type 'string'. Auto-fixed by setting the type to 'string'.`)):(e.choiceList=null,this._logAutoFix(`Field '${e.name}' had an empty domain but is not of type 'string'. Auto-fixed by removing the domain.`)):this._logIssue(`Field '${e.name}' must be of type 'string' to have a domain.`)),e.type==="string"&&this._validateStringFieldLength(e),Array.isArray(e.choiceList)&&(this.newDesign?this._autoFixChoiceList(e):this._logChoiceListIssues(e)),Array.isArray(e.choiceList)&&e.length!=null){let i=Math.max(...e.choiceList.map(a=>a.length));i>e.length&&(this.newDesign?(this._logAutoFix(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${i} characters. Auto-fixing to ${i}.`),e.length=i):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${i} characters.`))}}_autoFixChoiceList(e){let r=e.choiceList,n=r.filter(s=>s?.trim());n.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had blank domain values. Auto-fixed by removing them.`),r=n,e.choiceList=r);let o=[...new Set(r)];o.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had duplicate domain values. Auto-fixed by removing duplicates.`),r=o,e.choiceList=r),r.length||(this._logAutoFix(`Field '${e.name}' had an empty domain. Auto-fixed by removing the domain.`),e.choiceList=null)}_logChoiceListIssues(e){if(Array.isArray(e.choiceList)){if(!e.choiceList.length){this._logIssue(`Field '${e.name}' has an empty domain. At least one value is required.`);return}e.choiceList.some(r=>!r?.trim())&&this._logIssue(`A blank domain value was added to Field '${e.name}'.`),e.choiceList.length!==new Set(e.choiceList).size&&this._logIssue(`Field '${e.name}' has duplicate domain values.`)}}_validateStringFieldLength(e){if(this.newDesign&&e.length===255&&(e.length=256),typeof e.length!="number"||Number.isNaN(e.length)){this._handleInvalidStringFieldLength(e,256);return}let r=e.length;if(!dc(r).isValid){let n=r>4e3?4e3:256;this._handleInvalidStringFieldLength(e,n)}}_handleInvalidStringFieldLength(e,r){this.newDesign?(this._logAutoFix(`Field '${e.name}' has an invalid length. Auto-fixing to ${r}.`),e.length=r):this._logIssue(`Field '${e.name}' length is invalid (must be a number between 1 and 4000).`)}_makeUniqueName(e,r){let n=e,o=1;for(;r.has(n.toLowerCase());)n=`${e}_${o}`,o+=1;return n}_getUniqueTruncatedFieldName(e,r){let n=t.FIELD_NAME_MAX_LENGTH,o=e.slice(0,n),s=o,i=1;for(;r.has(s.toLowerCase());){let a=`_${i}`,c=Math.max(1,n-a.length);s=`${o.slice(0,c)}${a}`,i+=1}return s}_sanitizeItemName(e,r=t.NAME_MAX_LENGTH){let n=(e??"").replace(new RegExp(uc.source,"gu"),"").replace(t.INVALID_NAME_CHARS,"").replace(/\s+/gu," ").trim();return n.length>r&&(n=n.slice(0,r).trim()),n}_sanitizeDescription(e,r=t.DESCRIPTION_MAX_LENGTH){let n=(e??"").replace(/[<>]/gu,"");return n.length>r&&(n=n.slice(0,r)),n}_sanitizeFieldName(e){let r=(e??"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"");return r.length===0?r="field":/^\p{L}/u.test(r)||(r=`f_${r}`),r}_tryFixName(e,r,n,o,s){if(!this.newDesign)return!1;if(e==="empty")return n(s),this._logAutoFix(`${o} was empty. Auto-fixed to '${s}'.`),!0;let i=this._sanitizeItemName(r)||s;return n(i),this._logAutoFix(`${o} was invalid (${e}). Auto-fixed to '${i}'.`),!0}_tryFixDescription(e,r,n){if(!this.newDesign)return!1;let o=this._sanitizeDescription(e);return r(o),this._logAutoFix(`${n} was invalid. Auto-fixed to a sanitized value.`),!0}_logAutoFix(e){console.debug(e)}_logIssue(e){console.debug(e),this.issues.push(e),this.isValid=!1}},uA=d.object({key:d.string().describe("Stable key identifier for the string."),value:d.string().describe("Display value for the string."),description:d.string().describe("Explanation of where/how the string is used.")}),dA=d.object({id:d.string().describe("ArcGIS item id (32 hex characters)."),title:d.string().describe("Item title."),description:d.string().describe("Item description."),type:d.enum(["Feature Layer (hosted)","Feature Layer (hosted, view)","Web Map","Instant App","Dashboard","Web Experience","Form","Table (hosted)","Table (hosted, view)","Hub Site Application","Hub Page","CSV","Data Pipeline","Desktop Application Template","Group","Notebook","QuickCapture Project"]).describe("ArcGIS item type.")}),Wp=d.object({name:d.string().describe("Field name."),type:d.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:d.string().describe("Field alias for display."),description:d.string().describe("Field description."),choiceList:d.array(d.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:d.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),pA=d.object({id:d.number().int().describe("Layer/table id within the feature service."),type:d.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),typeMutable:d.boolean().describe("Indicates whether the layer type can be changed."),name:d.string().describe("Layer/table name."),description:d.string().describe("Layer/table description."),customFields:d.array(Wp).describe("User/business fields specific to the solution."),requiredFields:d.array(Wp).describe("Fields required for solution functionality (e.g., relationship keys).")}),mA=d.object({itemId:d.string().describe("ArcGIS item id for the feature layer."),addLayers:d.boolean().describe("Indicates whether new layers can be added during solution design."),layers:d.array(pA)}),xl=d.object({response:d.string().describe("Conversational response to the user's query."),solution:d.object({itemId:d.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),title:d.string().describe("Title of the solution."),description:d.string().describe("Description of the solution."),tags:d.array(d.string()).describe("Keywords/tags associated with the solution."),strings:d.array(uA).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:d.array(dA).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:mA.describe("Primary feature layer item and its schema/layers/tables details.")}),fA=d.object({op:d.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:d.string().describe("RFC 6901 JSON Pointer to the target location."),value:d.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null \u2014 not an empty string \u2014 for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),from:d.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null \u2014 not an empty string \u2014 for all other operations.")}),hA=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(fA).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),gA=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),yA=d.object({assistantResponse:d.string().describe("Natural-language response for the user."),isValidUpdate:d.boolean().describe("True only when the request is in scope for supported design updates.")}),_A=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),wA=d.object({templateId:d.string().min(1).describe("Template id from the available template list."),confidence:d.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:d.string().min(1).describe("Short action\u2011oriented description of the template in the user's use case/workflow, starting with a verb.")}),bA=d.object({assistantResponse:d.string().nullable().describe("Natural-language response for the user."),isValidUseCase:d.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:d.array(wA).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),xA=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
|
|
350
|
-
`):"No validation errors were provided.",
|
|
349
|
+
`)}`);return await r[1]()}function bi(t){return t?.configurable?.context?.translations}function Hp(t){if(typeof window>"u"||t.length<=1)return;let e=t.map(n=>n.solution.id),r=t.map(n=>n.solution.title);window.dispatchEvent(new CustomEvent("searchTermSet",{detail:{scope:"all-solutions",searchTerm:""}})),window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant",{detail:{solutionIds:e,solutionTitles:r},bubbles:!0,composed:!0})),window.dispatchEvent(new CustomEvent("navTabSelected",{detail:{tabType:"all-solutions"}}))}function Vp(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var VA=b.object({needsContext:b.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:b.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),Kp=t=>t?.signal?.aborted??!1,Gp=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./AS6VINEU.js").then(t=>t.default),"./prompts/transformQuery.md":()=>import("./MFVXFKKM.js").then(t=>t.default)});function GA(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">[$1]</a></sup>')}function JA(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function ZA(t,e){let r=[];return(e?.configurable?.context?.configContext.allCards??[]).forEach(n=>{let o=n.title;if(!o)return;let s=new RegExp(`(?<![\\p{L}\\p{N}])${o}(?![\\p{L}\\p{N}])`,"giu"),i=!1;t=t.replace(s,(a,c,l)=>{let u=l.slice(0,c);return/<img[^>]*alt\s*=\s*["'][^"']*$/i.test(u)?a:(i=!0,`<a href="" target="solutionId:${n.deployCommonId}">${o}</a>`)}),i&&r.push({solution:{title:n.title,id:n.deployCommonId,snippet:n.snippet,description:n.description},score:100})}),{source:t,allMatches:r}}function QA(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function Jp(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function wl(t,e,r){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",token:r},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status} calling ${e}`);return n.json()}var YA=t=>new Promise(e=>setTimeout(e,t));async function XA(t,e){let r=t.agentExecutionContext.userRequest,n=e?.configurable?.context?.lastTurnAgent,o=t.agentExecutionContext.messages??[];if(!n||o.length<=1||n==="explorer")return r;try{let s=await Ae(Gp,"transformQuery"),i=await kt({promptText:s,modelTier:"advanced",temperature:0,schema:VA,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return console.debug(`Rephrased query from "${r}" to "${i.rewrittenQuery.trim()}"`),i.rewrittenQuery.trim()}catch{}return r}var ex=E.Root({...li(),solutionResponse:E({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:E({reducer:(t,e)=>e??null,default:()=>null}),conversationId:E({reducer:(t,e)=>e??t,default:()=>null})}),tx=()=>new fe(ex).addNode("initializeAgent",nx).addNode("askSolutionsQuestions",rx).addEdge(me,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",K),Zp=async(t,e,r,n)=>{if(!t)return;let o=Jp(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:r,use_llm:!1}}}}};n&&(s.conversationId=n),wl(s,o,e??"")},rx=async(t,e)=>{if(Kp(e))return{};let r=bi(e),n=t.documentSkillUrl,o=[],s=await XA(t,e);await Pe({text:r.agentProgress.explorerAgentSearching},e);let i=await wl({message:s,conversationId:e?.configurable?.context?.convoId??void 0,context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:e?.configurable?.context?.configContext.locale??"en",use_llm:!1}}}}},n,e?.configurable?.context?.token??"");i.conversationId&&e?.configurable?.context?.setConversationId&&e.configurable.context.setConversationId(i.conversationId);let a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},c="",l=async u=>{let m=u.context?.results?.[0]?.reply??"";if(m!==""){let h=GA(m),w=JA(h),A=ZA(w,e);c=A.source,o=[...o,...A.allMatches.filter(I=>!o.some(g=>g.solution.id===I.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let h="";f===1?h=r.agentProgress.explorerAgentReading:f===2?h=r.agentProgress.explorerAgentReviewing:f===3&&(h=r.agentProgress.explorerAgentPreparing),await Pe({text:h},e)}};for(await l(i);a.hasMore;){if(Kp(e))return{};await YA(500),i=await wl({conversationId:a.conversationId,ackSequenceNumber:a.ackSequenceNumber,inquiryId:a.inquiryId},n,e?.configurable?.context?.token??""),a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},await l(i)}return Jp(e?.configurable?.context.portal)&&Zp(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?Vp(o[0].solution.id):Hp(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},nx=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=QA(e.configurable.context.portal)),{documentSkillUrl:r}};await Ae(Gp,"solutions_explorer_description");var Qp=t=>{if(t&&Array.isArray(t.id)&&t.id.length>0)return t.id[t.id.length-1].replace("Message","").toLowerCase();if(t&&typeof t._getType=="function")try{return t._getType()}catch{return"human"}return"human"},ox=t=>{let e=Qp(t);if(t&&t.kwargs)return{role:e,...t.kwargs};if(t&&typeof t=="object"){let r={role:e,content:typeof t.content=="string"?t.content:String(t.content||"")};return t.id&&(r.id=t.id),t.name&&(r.name=t.name),t.additional_kwargs&&(r.additional_kwargs=t.additional_kwargs),t.response_metadata&&(r.response_metadata=t.response_metadata),r}return{role:"human",content:String(t)}},sx=t=>Qp(t)==="human",ix=(t,e=3)=>t.filter(r=>sx(r)).slice(-e).map(ox),ax=(t,e=" ")=>ix(t).map(r=>r.content).join(e).trim(),lx={understandingRequest:"Understanding your request...",selectTemplatePrompt:"This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.",searchingExistingSolutions:"Searching for existing solutions...",existingSolutionMatch:"I found one or more existing solutions that match your use case. These are ready-to-use solutions that may already meet your needs and can be deployed now. Do you want to continue building your own solution?",continueBuildingYes:"Yes, I want to build a new solution",continueBuildingNo:"No, I\u2019ll review existing solutions",continueBuildingDeclined:"Sounds good. We can focus on existing solutions. Let me know if I can help answer any questions or provide more details.",creatingDesign:"Generating solution design...",updatingDesign:"Updating solution design...",applyChangeFailed:"I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.",createDesignFailed:"I wasn't able to create a solution design from that request. Please try rephrasing and try again.",discardMessage:"Are you sure you want to discard your solution?",discardForNewSolution:"I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?"},cx={builderMessages:lx},wi=class t{constructor(e,r,n=!0){this.isValid=!0,this.issues=[],this.fieldNameRegistry=null,this.response=e,this.template=r,this.newDesign=n,this.validate()}static{this.INVALID_NAME_CHARS=/[><~`$^+=|]/gu}static{this.NAME_MAX_LENGTH=250}static{this.DESCRIPTION_MAX_LENGTH=2048}static{this.FIELD_NAME_MAX_LENGTH=31}static{this.ALLOWED_FIELD_TYPES=new Set(["string","integer","double","date","guid"])}validate(){this.compareModels(),this.validateResponse()}compareModels(){this._compareStrings(),this._compareItems(),this._compareFeatureLayers()}validateResponse(){this._validateSolutionProps(),this._validateItems(),this._validateFeatureLayer()}_compareStrings(){let e=new Set(this.response.solution.strings.map(n=>n.key)),r=new Map(this.template.solution.strings.map(n=>[n.key,n]));[...r.keys()].every(n=>e.has(n))||(this.newDesign?this._reconcileStringKeys():this._logIssue("String keys in llm response do not match the template."));for(let n of this.response.solution.strings){if(n.value)continue;let o=r.get(n.key)?.value;this.newDesign&&o?(n.value=o,this._logAutoFix(`String key '${n.key}' had no value. Auto-fixed by restoring the template value.`)):this._logIssue(`String key '${n.key}' has no value in the design. It must be populated.`)}}_reconcileStringKeys(){let e=new Set(this.response.solution.strings.map(r=>r.key));for(let r of this.template.solution.strings)e.has(r.key)||(this.response.solution.strings.push({...r}),this._logAutoFix(`String key '${r.key}' was missing from the design. Auto-fixed by re-adding it from the template.`))}_compareItems(){let e=new Set(this.template.items.map(n=>n.id)),r=new Set(this.response.items.map(n=>n.id));e.size===r.size&&[...e].every(n=>r.has(n))||(this.newDesign?this._reconcileItems():this._logIssue("Item IDs in design do not match the template."))}_reconcileItems(){let e=new Set(this.template.items.map(i=>i.id)),r=new Set(this.response.items.map(i=>i.id)),n=[...r].filter(i=>!e.has(i)),o=[...e].filter(i=>!r.has(i));if(e.size===r.size&&n.length===1&&o.length===1){let i=n[0],a=o[0],c=this.response.items.find(l=>l.id===i);if(c){c.id=a,this._logAutoFix(`Item id '${i}' did not match the template id '${a}'. Auto-fixed in place.`);return}}n.length&&(this.response.items=this.response.items.filter(i=>e.has(i.id)),this._logAutoFix(`Removed items not present in the template: ${n.join(", ")}.`));let s=this.template.items.filter(i=>!r.has(i.id));if(s.length){this.response.items=[...s.map(i=>({...i})),...this.response.items];for(let i of s)this._logAutoFix(`Item '${i.id}' was missing from the design. Auto-fixed by adding it from the template.`)}}_compareFeatureLayers(){let e=this.template.featureLayer,r=this.response.featureLayer;if(e.itemId!==r.itemId){let n=r.itemId;r.itemId=e.itemId,this._logAutoFix(`Feature Layer itemId '${n}' did not match the template. Auto-fixed to '${e.itemId}'.`)}if(!e.addLayers){let n=new Set(e.layers.map(s=>s.id)),o=new Set(r.layers.map(s=>s.id));if(!(n.size===o.size&&[...n].every(s=>o.has(s))))this._logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`);else for(let s of e.layers){if(s.type){let a=r.layers.find(c=>c.id===s.id);if(a&&a.type!==s.type)if(this.newDesign){let c=a.type;a.type=s.type,this._logAutoFix(`Layer '${s.id}' type '${c}' is immutable. Auto-fixed back to template type '${s.type}'.`)}else this._logIssue(`Layer '${s.id}' type '${a.type}' does not match template type '${s.type}'. This layer type is immutable.`)}let i=r.layers.find(a=>a.id===s.id);i&&this._validateRequiredFields(i,s)}}}_validateRequiredFields(e,r){let n=new Map(e.requiredFields.map(o=>[o.name.toLowerCase(),o]));for(let o of r.requiredFields){let s=n.get(o.name.toLowerCase());if(!s){this.newDesign?(e.requiredFields.push({...o}),this._logAutoFix(`Layer '${e.name}' was missing required field '${o.name}'. Auto-fixed by re-adding it from the template.`)):this._logIssue(`Layer '${e.name}' is missing required field '${o.name}'.`);continue}this._enforceRequiredFieldImmutability(e,s,o)}}_enforceRequiredFieldImmutability(e,r,n){let o=[];if(r.type!==n.type&&o.push("type"),(r.length??null)!==(n.length??null)&&o.push("length"),this._choiceListsEqual(r.choiceList,n.choiceList)||o.push("choiceList"),!o.length)return;let s=o.length===1?"property":"properties";this.newDesign?(r.type=n.type,r.length=n.length,r.choiceList=Array.isArray(n.choiceList)?[...n.choiceList]:n.choiceList??null,this._logAutoFix(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). Auto-fixed by reverting to the template.`)):this._logIssue(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). These cannot be modified.`)}_choiceListsEqual(e,r){let n=Array.isArray(e)?e:null,o=Array.isArray(r)?r:null;if(n===null&&o===null)return!0;if(n===null||o===null)return!1;let s=new Set(n),i=new Set(o);return s.size===i.size&&[...s].every(a=>i.has(a))}_validateSolutionProps(){let e=this.response.solution.title??"",r=this.response.solution.description,n=/[/\\]/u.test(e),o=this.newDesign?e.replace(/[/\\]/gu,""):e;this.newDesign&&o!==e?(this.response.solution.title=o,this._logAutoFix("Solution title contained forward or back slashes. Auto-fixed by removing them.")):!this.newDesign&&n&&this._logIssue("Solution title contains forbidden forward or back slashes.");let s=is(o);if(s.isValid||this._tryFixName(s.errorType,o,i=>{this.response.solution.title=i},"Solution title","Solution Title")||this._logIssue(`Solution title is invalid (${s.errorType}).`),r){let i=as(r,t.DESCRIPTION_MAX_LENGTH,!0);i.isValid||this._tryFixDescription(r,a=>{this.response.solution.description=a},"Solution description")||this._logIssue(`Solution description is invalid (${i.errorType}).`)}}_validateItems(){for(let e of this.response.items){let r=is(e.title??"");if(r.isValid||this._tryFixName(r.errorType,e.title??"",n=>{e.title=n},`Item '${e.id}' title`,"Item Title")||this._logIssue(`Item '${e.id}' title is invalid (${r.errorType}).`),e.description){let n=as(e.description,t.DESCRIPTION_MAX_LENGTH,!0);n.isValid||this._tryFixDescription(e.description,o=>{e.description=o},`Item '${e.id}' description`)||this._logIssue(`Item '${e.id}' description is invalid (${n.errorType}).`)}}}_validateFeatureLayer(){this.response.featureLayer.layers.length||this._logIssue("Feature layer item must contain at least one layer.");let e=this.response.featureLayer.layers.map(r=>r.name.toLowerCase());e.length!==new Set(e).size&&(this.newDesign?this._dedupeLayerNames(this.response.featureLayer.layers):this._logIssue(`Layer names must be unique (case-insensitive). Layer names in design: ${e}.`));for(let r of this.response.featureLayer.layers)this._validateLayer(r,this.response.featureLayer.addLayers)}_dedupeLayerNames(e){let r=new Set;for(let n of e){let o=(n.name??"").toLowerCase();if(r.has(o)){let s=n.name;n.name=this._makeUniqueName(n.name??"Layer",r),this._logAutoFix(`Duplicate layer name '${s}'. Auto-fixed to '${n.name}'.`)}r.add(n.name.toLowerCase())}}_validateLayer(e,r){!r&&e.typeMutable===!0&&e.type==="Table"&&(this.newDesign?(e.type="Point",this._logAutoFix(`Layer '${e.name}' cannot be a Table. Auto-fixed to 'Point'.`)):this._logIssue(`Layer '${e.name}' cannot be a Table. It may be a Point, Line, or Polygon.`));let n=is(e.name??"");if(n.isValid||this._tryFixName(n.errorType,e.name??"",o=>{e.name=o},`Layer '${e.name}' name`,"Layer Title")||this._logIssue(`Layer '${e.name}' name is invalid (${n.errorType}).`),e.description){let o=as(e.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(e.description,s=>{e.description=s},`Layer '${e.name}' description`)||this._logIssue(`Layer '${e.name}' description is invalid (${o.errorType}).`)}this._validateLayerFields(e)}_validateLayerFields(e){let r=e.systemFields??[];this.fieldNameRegistry=new Set([...e.customFields,...e.requiredFields,...r].map(s=>s.name.toLowerCase()));for(let s of[...e.customFields,...e.requiredFields])this._validateField(s);this.fieldNameRegistry=null;let n=new Set(e.requiredFields.map(s=>s.name.toLowerCase())),o=new Set(n);for(let s of e.customFields){let i=s.name.toLowerCase();if(o.has(i)){let a=n.has(i)?"a required field name":"another field with the same name";if(this.newDesign){let c=s.name;s.name=this._makeUniqueName(s.name,o),this._logAutoFix(`Layer '${e.name}' field '${c}' collided with ${a}. Auto-fixed to '${s.name}'.`)}else this._logIssue(`Layer '${e.name}' field '${s.name}' collides with ${a}.`)}o.add(s.name.toLowerCase())}}_validateField(e){let r=/^\p{L}/u,n=/^.[\p{L}\p{M}\p{N}_]*$/u;e.alias?.trim()||(this.newDesign?(e.alias=e.name,this._logAutoFix(`Field '${e.name}' had no display name (alias). Auto-fixed to '${e.alias}'.`)):this._logIssue(`Field '${e.name}' has no display name (alias).`));let o=r.test(e.name),s=n.test(e.name);if(!o||!s)if(this.newDesign){let c=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' had an invalid name. Auto-fixed to '${e.name}'.`)}else o||this._logIssue(`Field '${e.name}' does not start with a letter.`),s||this._logIssue(`Field '${e.name}' contains invalid characters (only letters from any writing system, numbers, and underscores are allowed; emojis and punctuation are not allowed).`);if(e.name.length>t.FIELD_NAME_MAX_LENGTH)if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters.`);if(lc.has(e.name.toLowerCase()))if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(c,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(cc.has(e.name.toLowerCase()))if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(c,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' is a reserved system field name. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a reserved system field name.`);let i=e.type??"",a=i.toLowerCase();if(i!==a&&(e.type=a),!t.ALLOWED_FIELD_TYPES.has(a))if(this.newDesign){let c=e.type;a==="globalid"?e.type="guid":a==="oid"?e.type="integer":e.type="string",this._logAutoFix(`Field '${e.name}' had unsupported type '${c}'. Auto-fixed to '${e.type}'.`)}else this._logIssue(`Field '${e.name}' has unsupported type '${e.type}'. Allowed types are: string, integer, double, date.`);if(Array.isArray(e.choiceList)&&e.type!=="string"&&(this.newDesign?e.choiceList.length?(e.type="string",this._logAutoFix(`Field '${e.name}' had a domain but was not of type 'string'. Auto-fixed by setting the type to 'string'.`)):(e.choiceList=null,this._logAutoFix(`Field '${e.name}' had an empty domain but is not of type 'string'. Auto-fixed by removing the domain.`)):this._logIssue(`Field '${e.name}' must be of type 'string' to have a domain.`)),e.type==="string"&&this._validateStringFieldLength(e),Array.isArray(e.choiceList)&&(this.newDesign?this._autoFixChoiceList(e):this._logChoiceListIssues(e)),Array.isArray(e.choiceList)&&e.length!=null){let c=Math.max(...e.choiceList.map(l=>l.length));c>e.length&&(this.newDesign?(this._logAutoFix(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${c} characters. Auto-fixing to ${c}.`),e.length=c):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${c} characters.`))}}_autoFixChoiceList(e){let r=e.choiceList,n=r.filter(s=>s?.trim());n.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had blank domain values. Auto-fixed by removing them.`),r=n,e.choiceList=r);let o=[...new Set(r)];o.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had duplicate domain values. Auto-fixed by removing duplicates.`),r=o,e.choiceList=r),r.length||(this._logAutoFix(`Field '${e.name}' had an empty domain. Auto-fixed by removing the domain.`),e.choiceList=null)}_logChoiceListIssues(e){if(Array.isArray(e.choiceList)){if(!e.choiceList.length){this._logIssue(`Field '${e.name}' has an empty domain. At least one value is required.`);return}e.choiceList.some(r=>!r?.trim())&&this._logIssue(`A blank domain value was added to Field '${e.name}'.`),e.choiceList.length!==new Set(e.choiceList).size&&this._logIssue(`Field '${e.name}' has duplicate domain values.`)}}_validateStringFieldLength(e){if(this.newDesign&&e.length===255&&(e.length=256),typeof e.length!="number"||Number.isNaN(e.length)){this._handleInvalidStringFieldLength(e,256);return}let r=e.length;if(!dc(r).isValid){let n=r>4e3?4e3:256;this._handleInvalidStringFieldLength(e,n)}}_handleInvalidStringFieldLength(e,r){this.newDesign?(this._logAutoFix(`Field '${e.name}' has an invalid length. Auto-fixing to ${r}.`),e.length=r):this._logIssue(`Field '${e.name}' length is invalid (must be a number between 1 and 4000).`)}_makeUniqueName(e,r){let n=e,o=1;for(;r.has(n.toLowerCase());)n=`${e}_${o}`,o+=1;return n}_getUniqueTruncatedFieldName(e,r){let n=t.FIELD_NAME_MAX_LENGTH,o=e.slice(0,n),s=o,i=1;for(;r.has(s.toLowerCase());){let a=`_${i}`,c=Math.max(1,n-a.length);s=`${o.slice(0,c)}${a}`,i+=1}return s}_sanitizeItemName(e,r=t.NAME_MAX_LENGTH){let n=(e??"").replace(new RegExp(uc.source,"gu"),"").replace(t.INVALID_NAME_CHARS,"").replace(/\s+/gu," ").trim();return n.length>r&&(n=n.slice(0,r).trim()),n}_sanitizeDescription(e,r=t.DESCRIPTION_MAX_LENGTH){let n=(e??"").replace(/[<>]/gu,"");return n.length>r&&(n=n.slice(0,r)),n}_sanitizeFieldName(e){let r=(e??"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"");return r.length===0?r="field":/^\p{L}/u.test(r)||(r=`f_${r}`),r}_tryFixName(e,r,n,o,s){if(!this.newDesign)return!1;if(e==="empty")return n(s),this._logAutoFix(`${o} was empty. Auto-fixed to '${s}'.`),!0;let i=this._sanitizeItemName(r)||s;return n(i),this._logAutoFix(`${o} was invalid (${e}). Auto-fixed to '${i}'.`),!0}_tryFixDescription(e,r,n){if(!this.newDesign)return!1;let o=this._sanitizeDescription(e);return r(o),this._logAutoFix(`${n} was invalid. Auto-fixed to a sanitized value.`),!0}_logAutoFix(e){console.debug(e)}_logIssue(e){console.debug(e),this.issues.push(e),this.isValid=!1}},ux=d.object({key:d.string().describe("Stable key identifier for the string."),value:d.string().describe("Display value for the string."),description:d.string().describe("Explanation of where/how the string is used.")}),dx=d.object({id:d.string().describe("ArcGIS item id (32 hex characters)."),title:d.string().describe("Item title."),description:d.string().describe("Item description."),type:d.enum(["Feature Layer (hosted)","Feature Layer (hosted, view)","Web Map","Instant App","Dashboard","Web Experience","Form","Table (hosted)","Table (hosted, view)","Hub Site Application","Hub Page","CSV","Data Pipeline","Desktop Application Template","Group","Notebook","QuickCapture Project"]).describe("ArcGIS item type.")}),Wp=d.object({name:d.string().describe("Field name."),type:d.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:d.string().describe("Field alias for display."),description:d.string().describe("Field description."),choiceList:d.array(d.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:d.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),px=d.object({id:d.number().int().describe("Layer/table id within the feature service."),type:d.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),typeMutable:d.boolean().describe("Indicates whether the layer type can be changed."),name:d.string().describe("Layer/table name."),description:d.string().describe("Layer/table description."),customFields:d.array(Wp).describe("User/business fields specific to the solution."),requiredFields:d.array(Wp).describe("Fields required for solution functionality (e.g., relationship keys).")}),mx=d.object({itemId:d.string().describe("ArcGIS item id for the feature layer."),addLayers:d.boolean().describe("Indicates whether new layers can be added during solution design."),layers:d.array(px)}),Al=d.object({response:d.string().describe("Conversational response to the user's query."),solution:d.object({itemId:d.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),title:d.string().describe("Title of the solution."),description:d.string().describe("Description of the solution."),tags:d.array(d.string()).describe("Keywords/tags associated with the solution."),strings:d.array(ux).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:d.array(dx).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:mx.describe("Primary feature layer item and its schema/layers/tables details.")}),fx=d.object({op:d.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:d.string().describe("RFC 6901 JSON Pointer to the target location."),value:d.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null \u2014 not an empty string \u2014 for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),from:d.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null \u2014 not an empty string \u2014 for all other operations.")}),hx=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(fx).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),gx=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),yx=d.object({assistantResponse:d.string().describe("Natural-language response for the user."),isValidUpdate:d.boolean().describe("True only when the request is in scope for supported design updates.")}),_x=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),wx=d.object({templateId:d.string().min(1).describe("Template id from the available template list."),confidence:d.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:d.string().min(1).describe("Short action\u2011oriented description of the template in the user's use case/workflow, starting with a verb.")}),bx=d.object({assistantResponse:d.string().nullable().describe("Natural-language response for the user."),isValidUseCase:d.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:d.array(wx).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),Ax=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
|
|
350
|
+
`):"No validation errors were provided.",xx=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await Bp({promptText:await Ae(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:gx,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:Ax(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},xl=t=>t in wr,vx=5,Ix=.8,Tx=.5,Sx="Web Mapping Application",Cx="Embeddings",gi=null,_l=null,yi=null,_i=null,Ex="Build",hr=Object.assign({"./prompts/assessBuildRequest.md":()=>import("./S26SZJC7.js").then(t=>t.default),"./prompts/assessUpdateRequest.md":()=>import("./7X2SPNNK.js").then(t=>t.default),"./prompts/description.md":()=>import("./E25ZWVBK.js").then(t=>t.default),"./prompts/designSolution.md":()=>import("./SNA7NRRQ.js").then(t=>t.default),"./prompts/explainValidationFailure.md":()=>import("./I5E3PM26.js").then(t=>t.default),"./prompts/findExistingSolution.md":()=>import("./LPFG5XTA.js").then(t=>t.default),"./prompts/updateDesign.md":()=>import("./MBT2S4J5.js").then(t=>t.default)}),kx=cx.builderMessages,G=t=>t?.signal?.aborted??!1,re=(t,e,r)=>bi(e)?.builderMessages?.[t]??kx[t],Yp=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},Ox=async(t,e,r)=>{if(!t)return null;let n=`type:"${Sx}" AND typekeywords:${Cx} AND group:${t}`;return(await Ci({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function Px(t,e,r,n){try{let o=await Ox(t,e,r);if(!o||G(n))return null;let s=new WA({id:o.id});return await s.load(),G(n)?null:await s.fetchData("json")}catch{return null}}var Mx=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${Ex} AND group:${t}`;return(await Ci({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},Rx=async(t,e,r)=>{try{let n=await ql(t,{params:e?{token:e}:void 0,portal:r}),o=n?.buildSolution;if(!o)return null;let s=n?.params,i=s&&typeof s=="object"&&!Array.isArray(s)?s:null;return{buildSolution:o,params:i}}catch{return null}},gr=(t,e={})=>{let r=t;return"itemId"in e&&(r={...r,solution:{...r.solution,itemId:e.itemId??null}}),e.sourceBuildSolution!=null&&(r={...r,sourceBuildSolution:e.sourceBuildSolution}),"params"in e&&(r={...r,params:e.params??null}),"templateId"in e&&(r={...r,templateId:e.templateId??null}),r},Xp=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Di({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},vl=async t=>{if(_l){Object.entries(_l).forEach(([i,a])=>{wr[i]&&(wr[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=tm(t),n=rm(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await Mx(r,e,n),s={};G(t)||(await Promise.all(o.map(async i=>{let a=i.properties?.templateInfo;if(!a||typeof a!="object")return;let c=a.id;if(typeof c!="string"||s[c])return;let l=await Rx(i.id,e,n);if(!l||G(t))return;let{buildSolution:u,params:m}=l;if(typeof u=="object"&&u!==null&&"solution"in u){let h=u.solution;h.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,h.item=i}let f={...a,buildSolution:u};s[c]=gr(new Di(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(u),params:m?structuredClone(m):null}),wr[c]={...a,initialTemplate:s[c]}})),_l=s)},em=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},tm=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},rm=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},$x=async t=>{await Promise.all([om(t),vl(t)])},nm=async t=>{let e=em(t);(!yi||e&&e!==_i)&&(_i=e??_i,yi=$x(t).catch(r=>{throw yi=null,_i=null,r})),await yi};async function om(t){if(gi)return gi;let e=tm(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=rm(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new KA(n?{url:n}:void 0).load(),G(t))return null;let o=em(t)??void 0,s=await Px(e,o,r,t);return G(t)?null:s?(gi=s.items,gi):null}var Nx=()=>Object.entries(wr).map(([t,e])=>`ID: ${t}
|
|
351
351
|
Label: ${e.label}
|
|
352
352
|
Description: ${e.description}`).join(`
|
|
353
353
|
|
|
354
|
-
`),
|
|
354
|
+
`),Lx=t=>{let e=t?.configurable?.context?.solutionDesignJson;if(typeof e!="string"||!e.trim())return null;try{let r=JSON.parse(e),n=gr({response:"",...r},{itemId:r?.solution?.itemId??null}),o=Al.safeParse(n);if(!o.success)return null;let{response:s,...i}=o.data,a=r.templateId,c=typeof a=="string"&&xl(a)?a:null;return gr(i,{sourceBuildSolution:r.sourceBuildSolution,templateId:c,params:r.params??null})}catch{return null}},Dx=E.Root({...li(),templateDescription:E({reducer:(t,e)=>typeof e=="string"||e===null?e:t??null,default:()=>null}),currentDesign:E({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),assessment:E({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),selectedTemplate:E({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),updateAssessment:E({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),existingMatches:E({reducer:(t=[],e)=>e===void 0?t:e??[],default:()=>[]}),continueBuilding:E({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null})}),Fx=(t,e)=>{if(G(e))return{};let r=Lx(e),n=r?.templateId??null,o={};return JSON.stringify(t.currentDesign)!==JSON.stringify(r)&&(o.currentDesign=r),n&&t.selectedTemplate!==n&&(o.selectedTemplate=n),o},jx=async(t,e)=>{if(G(e))return{};await Pe({text:re("understandingRequest",e)},e),await nm(e);let r=t.agentExecutionContext.userRequest,n=Nx(),o=t.agentExecutionContext.messages.slice(-11),s=await kt({promptText:await Ae(hr,"assessBuildRequest"),modelTier:"advanced",temperature:0,schema:bx,messages:o,inputVariables:{query:r,availableTemplates:n}}),i=s.matchedTemplates.filter(m=>xl(m.templateId)),a={...s,matchedTemplates:i},[c,l]=i,u=c&&c.confidence>=Ix&&(l===void 0||c.confidence-l.confidence>=Tx)?c.templateId:null;return{assessment:a,selectedTemplate:u,existingMatches:[],continueBuilding:null}},zx=t=>{let e=t.assessment?.assistantResponse??"";return{outputMessage:e,summary:e,status:"success"}},Ux=async(t,e)=>{if(G(e))return{};let{currentDesign:r}=t;if(!r)return{updateAssessment:{assistantResponse:"",isValidUpdate:!0}};await Pe({text:re("understandingRequest",e)},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);return{updateAssessment:await kt({promptText:await Ae(hr,"assessUpdateRequest"),modelTier:"advanced",temperature:0,schema:yx,messages:o,inputVariables:{currentDesign:JSON.stringify(ji(r)),query:n}})}},qx=(t,e)=>{let r=t.updateAssessment?.assistantResponse??re("applyChangeFailed",e);return{outputMessage:r,summary:r,status:"success"}},Bx=(t,e)=>{if(G(e))return{};let{hitlResponse:r}=e.configurable,n="selectTemplate",o=t.assessment?.matchedTemplates.filter(c=>xl(c.templateId))??[],s=o.map(c=>`${c.templateDescription}`);if(r?.agentId!=="solutionBuilder"||r.id!==n){let c={agentId:"solutionBuilder",id:n,kind:"singleSelection",message:re("selectTemplatePrompt",e),metadata:[...s]};throw new Ko(c)}let i=String(r.payload??""),a=s.findIndex(c=>c===i);return{selectedTemplate:(a>=0?o[a]:void 0)?.templateId??o[0]?.templateId??null}},Kx=async(t,e)=>{if(G(e))return{};await Pe({text:re("searchingExistingSolutions",e)},e);let r=t.agentExecutionContext.userRequest,n=ax(t.agentExecutionContext.messages)||r,o=await om(e);if(G(e))return{};if(!o)return console.warn("Solutions Search: failed to load solution embeddings cache; skipping search."),{existingMatches:[]};if(!o.length)return{existingMatches:[]};let[s]=await Dp([n]);if(G(e))return{};let i=o.map(u=>({solution:u,score:Fp(s,u.embedding)}));i.sort((u,m)=>m.score-u.score);let a=i.slice(0,vx);if(!a.length)return{existingMatches:[]};let c=a.map(({solution:u})=>`${u.title}
|
|
355
355
|
Snippet: ${u.snippet}
|
|
356
356
|
Description: ${u.description}`).join(`
|
|
357
357
|
|
|
358
|
-
`),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await kt({promptText:await
|
|
359
|
-
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+q.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(U)}catch{return O}}},l=[...a.map(O=>({op:O.op,path:O.path.replace(/\/+$/,""),...O.value!=null&&O.value!==""?{value:c(O.value)}:{},...O.from!=null&&O.from!==""?{from:O.from}:{}}))].sort((O,U)=>O.op!=="remove"||U.op!=="remove"?0:U.path.localeCompare(O.path,void 0,{numeric:!0})),u=structuredClone(Di(r));try{Zn(u,l,!0)}catch(O){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:O,llmResponse:s,patches:l,patchTarget:u});let U=re("applyChangeFailed",e);return{outputMessage:U,summary:U,status:"success"}}let m=hr({response:"",...u},{itemId:r.solution?.itemId??null}),f=xl.safeParse(m);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:m});let O=re("applyChangeFailed",e);return{outputMessage:O,summary:O,status:"success"}}let{response:h,featureLayer:w,...x}=f.data,I=ji(w,r.featureLayer),g=hr({...x,featureLayer:I},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),v=ro(t.selectedTemplate);if(v?.initialTemplate||(await vl(e),v=ro(t.selectedTemplate)),G(e))return{};if(!v?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let S=new _i(g,v.initialTemplate,!1);if(!S.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:S.issues,llmResponse:s,patchedDesign:g});let O=await AA({query:n,validationIssues:S.issues,recentMessages:o,fallbackMessage:re("applyChangeFailed",e),promptModules:fr});return{outputMessage:O,summary:O,status:"success"}}let L=g.sourceBuildSolution,z=Xp(g,L);if(!z.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:z.error,llmResponse:s,design:g});let O=re("applyChangeFailed",e);return{outputMessage:O,summary:O,status:"success"}}return G(e)?{}:(Yp(g),{outputMessage:i,summary:i,status:"success",currentDesign:g})},GA=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",JA=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",ZA=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",QA=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",YA=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",XA=()=>new fe(DA).addNode("syncCurrentDesignFromContext",FA).addNode("assessBuildRequest",jA).addNode("assessUpdateRequest",UA).addNode("invalidBuildExit",zA).addNode("invalidUpdateExit",qA).addNode("selectTemplateHIL",BA).addNode("findExistingSolutions",KA).addNode("confirmContinueBuildingHIL",WA).addNode("declineContinueBuildingExit",HA).addNode("designSolution",sm).addNode("updateDesign",VA).addEdge(me,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",GA,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",JA,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",ZA,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",K).addEdge("invalidUpdateExit",K).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",QA,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",YA,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",K).addEdge("designSolution",K).addEdge("updateDesign",K);await xe(fr,"description");var ev=b.object({tool:b.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:b.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:b.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),bi=t=>t?.signal?.aborted??!1,Il=Object.assign({"./prompts/assistantResponse.md":()=>import("./4L7TJNAM.js").then(t=>t.default),"./prompts/classifyIntent.md":()=>import("./LWJF6EXD.js").then(t=>t.default),"./prompts/description.md":()=>import("./ENLFOYSI.js").then(t=>t.default)}),tv=t=>{let e=t?.configurable?.context?.solutionDesignJson,r=t?.configurable?.context?.lastTurnAgent,n=r==="assistant"?"other":r,o=!1;if(typeof e=="string"&&e.trim())try{o=JSON.parse(e).solution!=null}catch{o=!1}return{activeSolutionDesign:o,lastTool:n}},Tl=(t,e)=>{let r=t?.configurable?.context?.setLastTurnAgent;typeof r=="function"&&r(e);let n=new CustomEvent("assistantProcessing",{detail:{finished:!0,agent:e}});window.dispatchEvent(n)},im=E.Root({...ai(),selectedTool:E({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:E({reducer:(t,e)=>e??null,default:()=>null})}),rv=async(t,e)=>{if(bi(e))return{};let r=wi(e);await Pe({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=tv(e),a=await xe(Il,"classifyIntent"),c=await kt({promptText:a,modelTier:"advanced",temperature:0,schema:ev,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},nv=async(t,e)=>{if(bi(e))return{};let r=await tA().compile().invoke(t,e);return Tl(e,"explorer"),r},ov=async(t,e)=>{if(bi(e))return{};let r=await XA().compile().invoke(t,e);return Tl(e,"builder"),r},sv=async(t,e)=>{if(bi(e))return{};let r=wi(e),n=t.agentExecutionContext.userRequest;await Pe({text:r?.executingSolutionsAssistantAgent},e);let o=await xe(Il,"assistantResponse"),s=t.agentExecutionContext.messages.slice(-11),i=await Lp({promptText:o,modelTier:"advanced",temperature:0,messages:s,inputVariables:{query:n}});return Tl(e,"assistant"),{outputMessage:i,summary:i,status:"success"}},iv=t=>t.selectedTool??"other",av=()=>new fe(im).addNode("classifyIntent",rv).addNode("routeToExplorer",nv).addNode("routeToBuilder",ov).addNode("assistantResponse",sv).addEdge(me,"classifyIntent").addConditionalEdges("classifyIntent",iv,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",K).addEdge("routeToBuilder",K).addEdge("assistantResponse",K),lv=await xe(Il,"description"),cv={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:lv,createGraph:av,workspace:im},uv="https://links.esri.com/solutions/agol-organizational-account",dv="https://links.esri.com/solutions/configure-assistants",bl=class extends Dl{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=jl({name:"arcgis-solutions-assistant",blocking:!0}),this._builderWidth=48,this._solutionDesignJson='{ "solution": null }',this._isAssistantBusy=!1,this._isBuilderBusy=!1,this._preChatCheck=!1,this._showNewChatConfirm=!1,this._assistantRef=Nl(),this._configContextConsumer=Ti({context:zl,subscribe:!0,callback:e=>{e?.portalURL&&(yl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Ti({context:Ul,subscribe:!0,callback:e=>{e?.design&&(this._solutionDesignJson=JSON.stringify(e.design,null,2))}}),this._handleResize=()=>{this._isMobile=window.innerWidth<=800},this._chatStartTime=null,this._responseMetadata=new Map,this._pendingResponseAgent=void 0,this._handleAssistantProcessingFinished=e=>{let r=e;if(r.detail?.finished&&this._chatStartTime!==null){let n=r.detail.agent;this._lastResponseAgent=n,this._pendingResponseAgent=n;let o=Bl(this._chatStartTime);this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"Chat",dimensions:[n],metrics:[o]}),this._chatStartTime=null}},this.closeAssistant=vi(),this.assistantProcessing=vi(),this._handleAssistantLinkClick=e=>{let r=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(r?.href)if(e.preventDefault(),r.target.indexOf("solutionId:")>-1){let n=r.target.split("solutionId:")[1];this._emitItemIdFromAI(n)}else window.open(r.href,"_blank","noopener,noreferrer")},this._onSolutionDesignUpdate=e=>{let r=e.detail;this._solutionDesignJson=r?JSON.stringify(r,null,2):'{ "solution": null }'},this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open},this.listenOn(window,"arcgisFeedback",e=>{let r=e.detail,{agentPicked:n,taskAssigned:o,userMessage:s}=this._parseAgentPickedAndTask(r),i=this._responseMetadata.get(r.id),a=i?.agent??n??"",c=i?.userMessage??i?.userMessage??s??o??"";this._sendFeedback(r.content,c,r.feedback?.positive?"Good":r.feedback?.positive===!1?"Bad":"N/A",a)}),this.listenOn(window,"clearAssistantConversation",()=>{this._clearConversation()})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_lastTurnAgent:16,_lastResponseAgent:16,_orgSettings:16,_suggestedPrompts:16,_hasInteracted:16,_isMobile:16,_translations:16,_builderWidth:16,_solutionDesignJson:16,_isAssistantBusy:16,_isBuilderBusy:16,_preChatCheck:16,_showNewChatConfirm:16}}static{this.styles=Hx}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}connectedCallback(){super.connectedCallback(),window.addEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.addEventListener("click",this._handleAssistantLinkClick),window.addEventListener("resize",this._handleResize),window.addEventListener("assistantProcessing",this._handleAssistantProcessingFinished),this._builderDesignContextConsumer}disconnectedCallback(){window.removeEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.removeEventListener("click",this._handleAssistantLinkClick),window.removeEventListener("resize",this._handleResize),window.removeEventListener("assistantProcessing",this._handleAssistantProcessingFinished),super.disconnectedCallback()}loaded(){this._checkURLOpenParameter()}load(){yl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(yl.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(e){this._loadUserFirstName()}willUpdate(e){e.has("open")&&this.open&&window.dispatchEvent(new CustomEvent("openAssistant")),this._configContextConsumer.value?.authentication&&this._configContextConsumer.value?.userSession?.token&&(this._preChatCheck||(Zp(this._configContextConsumer.value?.authentication.Portal,this._configContextConsumer.value?.userSession?.token,this._configContextConsumer.value?.locale??"en"),this._preChatCheck=!0)),this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return it`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??Ii} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return it`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${pc(this._translations.noPermissionMessage.replace("{{orgUrl}}",uv).replace("{{configAI}}",dv))}</div></calcite-notice>`}render(){let e=this._suggestedPrompts.length>0?this._suggestedPrompts:this._hasInteracted?[]:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length>0?e=this._suggestedPrompts:this._hasInteracted||(e=[...Object.values(this._translations.defaultFollowUpQuestions)]),it`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?it`${!this._isMobile&&it`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.builder} text-enabled .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${()=>{this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"Toggle Builder Panel",dimensions:[this.builderVisible?"Close":"Open"]}),window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"))}} scale=m slot=header-actions-end></calcite-action>`||""}${!this._isMobile&&it`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.solutionBuilder}</span></calcite-tooltip>`||""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage??Ii} .suggestedPrompts=${e} @arcgisSubmit=${()=>{this._suggestedPrompts=[],e=[],this._hasInteracted=!0,this._chatStartTime=Date.now(),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail&&console.log("arcgis feedback: ",r.detail)}} @arcgisResponse=${()=>{let r=this._pendingResponseAgent??this._lastResponseAgent;if(r){let n=o=>{if(this._captureResponseMetadata(r)){this._pendingResponseAgent=void 0;return}o<3&&requestAnimationFrame(()=>n(o+1))};requestAnimationFrame(()=>n(1))}this.assistantProcessing.emit(!1)}} ${Ll(this._assistantRef)}><calcite-button appearance=transparent id=newChatButton icon-start=speech-bubble-plus kind=neutral .label=${this._translations.tooltips.newChat} @click=${()=>{this.hasActiveBuilderDesign?this._showNewChatConfirm=!0:(this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"New Chat",dimensions:["No Active Design"]}),this._clearConversation())}} round scale=m slot=entry-actions-start>${this._translations.tooltips.newChat}</calcite-button><arcgis-assistant-agent .agent=${cv} .context=${{token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,translations:this._translations,solutionDesignJson:this._solutionDesignJson,lastTurnAgent:this._lastTurnAgent,setConversationId:r=>{this._conversationId=r},setLastTurnAgent:r=>{this._lastTurnAgent=r},clearSuggestedPrompts:()=>{this._suggestedPrompts=[]}}}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=solid kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>`:this._renderNoPermission():this._renderNoSign()}${this._showNewChatConfirm&&it`<calcite-dialog close-disabled escape-disabled .heading=${this._translations.newConversationConfirmTitle} modal open outside-close-disabled>${this._translations.builderMessages.discardMessage}<calcite-button appearance=outline @click=${()=>{this._showNewChatConfirm=!1}} slot=footer-end>${this._translations.cancel}</calcite-button><calcite-button appearance=solid kind=danger @click=${()=>{this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"New Chat",dimensions:["With Design Discard"]}),this._showNewChatConfirm=!1,window.dispatchEvent(new CustomEvent("requestBuilderDiscard"))}} slot=footer-end>${this._translations.discard}</calcite-button></calcite-dialog>`||""}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${()=>{this.closeAssistant.emit(!0)}} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`}_clearConversation(){this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._pendingResponseAgent=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._responseMetadata.clear(),this._assistantRef.value?.clearChatHistory()}_sendFeedback(e,r,n,o){let s=`https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(r)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({agent:o}))}&field:version=${encodeURIComponent("v2")}`;window.open(s,"_blank")}async _loadUserFirstName(){try{let e=await this._configContextConsumer.value?.userSession?.getUser();if(e?.fullName){let r=e.fullName.split(" ")[0];this.userFirstName=r}}catch{}}_captureResponseMetadata(e){let r=Array.from(this._assistantRef.value?.messages||[]);for(let n=r.length-1;n>=0;n--){let o=r[n];if(o.role==="assistant"&&!this._responseMetadata.has(o.id)){let s;for(let i=n-1;i>=0;i--){let a=r[i];if(a.role==="user"){s=a.content;break}}return this._responseMetadata.set(o.id,{agent:e,userMessage:s}),!0}}return!1}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],o=[...r].sort((u,m)=>m.id-u.id).find(u=>u.role==="user"&&u.id<=e.id)?.content||null,s=n.find(u=>typeof u=="string"&&u.includes("Agent picked:"))??null;if(!s)return{agentPicked:null,taskAssigned:null,userMessage:o};let i=/Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i,a=s.match(i);if(!a)return{agentPicked:null,taskAssigned:null,userMessage:o};let c=a[1].trim(),l=a[2].trim();return{agentPicked:c,taskAssigned:l,userMessage:o}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};Fl("arcgis-solutions-assistant",bl);return bl},"config","identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","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","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,c)
|
|
358
|
+
`),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await kt({promptText:await Ae(hr,"findExistingSolution"),modelTier:"fast",temperature:0,schema:_x,messages:l,inputVariables:{query:r,candidates:c}})).matchedTitles.map(u=>a.find(({solution:m})=>m.title===u)).filter(u=>u!==void 0)}},Wx=(t,e)=>{if(G(e))return{};let{existingMatches:r}=t,{hitlResponse:n}=e.configurable,o=`confirmExistingSolution:${r[0].solution.id}`;if(n?.agentId!=="solutionBuilder"||n.id!==o){r.length===1?Vp(r[0].solution.id):Hp(r);let a=re("existingSolutionMatch",e),c=[re("continueBuildingYes",e),re("continueBuildingNo",e)],l={agentId:"solutionBuilder",id:o,kind:"singleSelection",message:a,metadata:c};throw new Ko(l)}let s=String(n.payload??"").trim(),i=re("continueBuildingNo",e);return{continueBuilding:s!==i}},Hx=(t,e)=>{let r=re("continueBuildingDeclined",e);return{outputMessage:r,summary:r,status:"success"}},sm=async(t,e)=>{if(G(e))return{};if(await nm(e),G(e))return{};let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await Pe({text:re("creatingDesign",e)},e);let o=ro(t.selectedTemplate);if(o?.initialTemplate||(await vl(e),o=ro(t.selectedTemplate)),G(e))return{};if(!o?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let s=gr(r??o.initialTemplate,{itemId:(r??o.initialTemplate)?.solution?.itemId??null,sourceBuildSolution:r?.sourceBuildSolution??o.initialTemplate.sourceBuildSolution,params:r?.params??o.initialTemplate.params??null}),i=t.agentExecutionContext.messages.slice(-11),a=await kt({promptText:await Ae(hr,"designSolution"),modelTier:"advanced",temperature:0,schema:Al,messages:i,inputVariables:{currentDesign:JSON.stringify(Fi(s)),templateInstructions:o.instructions,query:n}});if(await Pe({text:" of design solution 1"},e),G(e))return{};let{response:c,featureLayer:l,...u}=a,m=zi(l,s.featureLayer),f=gr({...u,featureLayer:m},{itemId:s?.solution?.itemId,sourceBuildSolution:s.sourceBuildSolution,templateId:t.selectedTemplate??null,params:s.params??null}),h=new wi(f,o.initialTemplate);if(!h.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:h.issues,llmResponse:a}),{outputMessage:re("createDesignFailed",e)};let w=f.sourceBuildSolution,A=Xp(f,w);if(!A.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:A.error,llmResponse:a,design:f});let I=re("createDesignFailed",e);return{outputMessage:I,summary:I,status:"success"}}return G(e)?{}:(Yp(f),{outputMessage:c,summary:c,status:"success",currentDesign:f})},Vx=async(t,e)=>{if(G(e))return{};let{currentDesign:r}=t;if(!r)return sm(t,e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);await Pe({text:re("updatingDesign",e)},e);let s;try{s=await kt({promptText:await Ae(hr,"updateDesign"),modelTier:"advanced",temperature:0,schema:hx,messages:o,inputVariables:{currentDesign:JSON.stringify(ji(r)),query:n}})}catch(P){console.warn("[SolutionBuilder] updateDesign structured prompt failed:",P);let U=re("applyChangeFailed",e);return{outputMessage:U,summary:U,status:"success"}}let{response:i,patches:a}=s;if(!a||a.length===0)return{outputMessage:i,summary:i,status:"success"};let c=P=>{try{return JSON.parse(P)}catch{let U=P.replace(/[\u0000-\u001F]/g,q=>{switch(q){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
359
|
+
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+q.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(U)}catch{return P}}},l=[...a.map(P=>({op:P.op,path:P.path.replace(/\/+$/,""),...P.value!=null&&P.value!==""?{value:c(P.value)}:{},...P.from!=null&&P.from!==""?{from:P.from}:{}}))].sort((P,U)=>P.op!=="remove"||U.op!=="remove"?0:U.path.localeCompare(P.path,void 0,{numeric:!0})),u=structuredClone(Fi(r));try{Zn(u,l,!0)}catch(P){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:P,llmResponse:s,patches:l,patchTarget:u});let U=re("applyChangeFailed",e);return{outputMessage:U,summary:U,status:"success"}}let m=gr({response:"",...u},{itemId:r.solution?.itemId??null}),f=Al.safeParse(m);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:m});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}let{response:h,featureLayer:w,...A}=f.data,I=zi(w,r.featureLayer),g=gr({...A,featureLayer:I},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),v=ro(t.selectedTemplate);if(v?.initialTemplate||(await vl(e),v=ro(t.selectedTemplate)),G(e))return{};if(!v?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let S=new wi(g,v.initialTemplate,!1);if(!S.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:S.issues,llmResponse:s,patchedDesign:g});let P=await xx({query:n,validationIssues:S.issues,recentMessages:o,fallbackMessage:re("applyChangeFailed",e),promptModules:hr});return{outputMessage:P,summary:P,status:"success"}}let $=g.sourceBuildSolution,z=Xp(g,$);if(!z.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:z.error,llmResponse:s,design:g});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}return G(e)?{}:(Yp(g),{outputMessage:i,summary:i,status:"success",currentDesign:g})},Gx=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",Jx=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",Zx=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",Qx=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",Yx=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",Xx=()=>new fe(Dx).addNode("syncCurrentDesignFromContext",Fx).addNode("assessBuildRequest",jx).addNode("assessUpdateRequest",Ux).addNode("invalidBuildExit",zx).addNode("invalidUpdateExit",qx).addNode("selectTemplateHIL",Bx).addNode("findExistingSolutions",Kx).addNode("confirmContinueBuildingHIL",Wx).addNode("declineContinueBuildingExit",Hx).addNode("designSolution",sm).addNode("updateDesign",Vx).addEdge(me,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",Gx,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",Jx,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",Zx,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",K).addEdge("invalidUpdateExit",K).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Qx,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",Yx,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",K).addEdge("designSolution",K).addEdge("updateDesign",K);await Ae(hr,"description");var ev=b.object({tool:b.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:b.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:b.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),Ai=t=>t?.signal?.aborted??!1,Il=Object.assign({"./prompts/assistantResponse.md":()=>import("./4L7TJNAM.js").then(t=>t.default),"./prompts/classifyIntent.md":()=>import("./LWJF6EXD.js").then(t=>t.default),"./prompts/description.md":()=>import("./ENLFOYSI.js").then(t=>t.default)}),tv=t=>{let e=t?.configurable?.context?.solutionDesignJson,r=t?.configurable?.context?.lastTurnAgent,n=r==="assistant"?"other":r,o=!1;if(typeof e=="string"&&e.trim())try{o=JSON.parse(e).solution!=null}catch{o=!1}return{activeSolutionDesign:o,lastTool:n}},Tl=(t,e)=>{let r=t?.configurable?.context?.setLastTurnAgent;typeof r=="function"&&r(e);let n=new CustomEvent("assistantProcessing",{detail:{finished:!0,agent:e}});window.dispatchEvent(n)},im=E.Root({...li(),selectedTool:E({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:E({reducer:(t,e)=>e??null,default:()=>null})}),rv=async(t,e)=>{if(Ai(e))return{};let r=bi(e);await Pe({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=tv(e),a=await Ae(Il,"classifyIntent"),c=await kt({promptText:a,modelTier:"advanced",temperature:0,schema:ev,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},nv=async(t,e)=>{if(Ai(e))return{};let r=await tx().compile().invoke(t,e);return Tl(e,"explorer"),r},ov=async(t,e)=>{if(Ai(e))return{};let r=await Xx().compile().invoke(t,e);return Tl(e,"builder"),r},sv=async(t,e)=>{if(Ai(e))return{};let r=bi(e),n=t.agentExecutionContext.userRequest;await Pe({text:r?.executingSolutionsAssistantAgent},e);let o=await Ae(Il,"assistantResponse"),s=t.agentExecutionContext.messages.slice(-11),i=await Lp({promptText:o,modelTier:"advanced",temperature:0,messages:s,inputVariables:{query:n}});return Tl(e,"assistant"),{outputMessage:i,summary:i,status:"success"}},iv=t=>t.selectedTool??"other",av=()=>new fe(im).addNode("classifyIntent",rv).addNode("routeToExplorer",nv).addNode("routeToBuilder",ov).addNode("assistantResponse",sv).addEdge(me,"classifyIntent").addConditionalEdges("classifyIntent",iv,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",K).addEdge("routeToBuilder",K).addEdge("assistantResponse",K),lv=await Ae(Il,"description"),cv={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:lv,createGraph:av,workspace:im},uv="https://links.esri.com/solutions/agol-organizational-account",dv="https://links.esri.com/solutions/configure-assistants",bl=class extends Dl{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=jl({name:"arcgis-solutions-assistant",blocking:!0}),this._builderWidth=48,this._solutionDesignJson='{ "solution": null }',this._isAssistantBusy=!1,this._isBuilderBusy=!1,this._preChatCheck=!1,this._showNewChatConfirm=!1,this._assistantRef=Nl(),this._configContextConsumer=Si({context:zl,subscribe:!0,callback:e=>{e?.portalURL&&(yl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Si({context:Ul,subscribe:!0,callback:e=>{e?.design&&(this._solutionDesignJson=JSON.stringify(e.design,null,2))}}),this._handleResize=()=>{this._isMobile=window.innerWidth<=800},this._chatStartTime=null,this._responseMetadata=new Map,this._pendingResponseAgent=void 0,this._handleAssistantProcessingFinished=e=>{let r=e;if(r.detail?.finished&&this._chatStartTime!==null){let n=r.detail.agent;this._lastResponseAgent=n,this._pendingResponseAgent=n;let o=Bl(this._chatStartTime);this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"Chat",dimensions:[n],metrics:[o]}),this._chatStartTime=null}},this.closeAssistant=Ii(),this.assistantProcessing=Ii(),this._handleAssistantLinkClick=e=>{let r=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(r?.href)if(e.preventDefault(),r.target.indexOf("solutionId:")>-1){let n=r.target.split("solutionId:")[1];this._emitItemIdFromAI(n)}else window.open(r.href,"_blank","noopener,noreferrer")},this._onSolutionDesignUpdate=e=>{let r=e.detail;this._solutionDesignJson=r?JSON.stringify(r,null,2):'{ "solution": null }'},this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open},this.listenOn(window,"arcgisFeedback",e=>{let r=e.detail,{agentPicked:n,taskAssigned:o,userMessage:s}=this._parseAgentPickedAndTask(r),i=this._responseMetadata.get(r.id),a=i?.agent??n??"",c=i?.userMessage??i?.userMessage??s??o??"";this._sendFeedback(r.content,c,r.feedback?.positive?"Good":r.feedback?.positive===!1?"Bad":"N/A",a)}),this.listenOn(window,"clearAssistantConversation",()=>{this._clearConversation()})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_lastTurnAgent:16,_lastResponseAgent:16,_orgSettings:16,_suggestedPrompts:16,_hasInteracted:16,_isMobile:16,_translations:16,_builderWidth:16,_solutionDesignJson:16,_isAssistantBusy:16,_isBuilderBusy:16,_preChatCheck:16,_showNewChatConfirm:16}}static{this.styles=HA}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}connectedCallback(){super.connectedCallback(),window.addEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.addEventListener("click",this._handleAssistantLinkClick),window.addEventListener("resize",this._handleResize),window.addEventListener("assistantProcessing",this._handleAssistantProcessingFinished),this._builderDesignContextConsumer}disconnectedCallback(){window.removeEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.removeEventListener("click",this._handleAssistantLinkClick),window.removeEventListener("resize",this._handleResize),window.removeEventListener("assistantProcessing",this._handleAssistantProcessingFinished),super.disconnectedCallback()}loaded(){this._checkURLOpenParameter()}load(){yl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(yl.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(e){this._loadUserFirstName()}willUpdate(e){e.has("open")&&this.open&&window.dispatchEvent(new CustomEvent("openAssistant")),this._configContextConsumer.value?.authentication&&this._configContextConsumer.value?.userSession?.token&&(this._preChatCheck||(Zp(this._configContextConsumer.value?.authentication.Portal,this._configContextConsumer.value?.userSession?.token,this._configContextConsumer.value?.locale??"en"),this._preChatCheck=!0)),this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return it`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??Ti} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return it`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${pc(this._translations.noPermissionMessage.replace("{{orgUrl}}",uv).replace("{{configAI}}",dv))}</div></calcite-notice>`}render(){let e=this._suggestedPrompts.length>0?this._suggestedPrompts:this._hasInteracted?[]:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length>0?e=this._suggestedPrompts:this._hasInteracted||(e=[...Object.values(this._translations.defaultFollowUpQuestions)]),it`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?it`${!this._isMobile&&it`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.builder} text-enabled .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${()=>{this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"Toggle Builder Panel",dimensions:[this.builderVisible?"Close":"Open"]}),window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"))}} scale=m slot=header-actions-end></calcite-action>`||""}${!this._isMobile&&it`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.solutionBuilder}</span></calcite-tooltip>`||""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage??Ti} .suggestedPrompts=${e} @arcgisSubmit=${()=>{this._suggestedPrompts=[],e=[],this._hasInteracted=!0,this._chatStartTime=Date.now(),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail&&console.log("arcgis feedback: ",r.detail)}} @arcgisResponse=${()=>{let r=this._pendingResponseAgent??this._lastResponseAgent;if(r){let n=o=>{if(this._captureResponseMetadata(r)){this._pendingResponseAgent=void 0;return}o<3&&requestAnimationFrame(()=>n(o+1))};requestAnimationFrame(()=>n(1))}this.assistantProcessing.emit(!1)}} ${Ll(this._assistantRef)}><calcite-button appearance=transparent id=newChatButton icon-start=speech-bubble-plus kind=neutral .label=${this._translations.tooltips.newChat} @click=${()=>{this.hasActiveBuilderDesign?this._showNewChatConfirm=!0:(this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"New Chat",dimensions:["No Active Design"]}),this._clearConversation())}} round scale=m slot=entry-actions-start>${this._translations.tooltips.newChat}</calcite-button><arcgis-assistant-agent .agent=${cv} .context=${{token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,translations:this._translations,solutionDesignJson:this._solutionDesignJson,lastTurnAgent:this._lastTurnAgent,setConversationId:r=>{this._conversationId=r},setLastTurnAgent:r=>{this._lastTurnAgent=r},clearSuggestedPrompts:()=>{this._suggestedPrompts=[]}}}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=solid kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>`:this._renderNoPermission():this._renderNoSign()}${this._showNewChatConfirm&&it`<calcite-dialog close-disabled escape-disabled .heading=${this._translations.newConversationConfirmTitle} modal open outside-close-disabled>${this._translations.builderMessages.discardMessage}<calcite-button appearance=outline @click=${()=>{this._showNewChatConfirm=!1}} slot=footer-end>${this._translations.cancel}</calcite-button><calcite-button appearance=solid kind=danger @click=${()=>{this._telemetry?.logEvent({category:Qn.ASSISTANT,action:"New Chat",dimensions:["With Design Discard"]}),this._showNewChatConfirm=!1,window.dispatchEvent(new CustomEvent("requestBuilderDiscard"))}} slot=footer-end>${this._translations.discard}</calcite-button></calcite-dialog>`||""}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${()=>{this.closeAssistant.emit(!0)}} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`}_clearConversation(){this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._pendingResponseAgent=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._responseMetadata.clear(),this._assistantRef.value?.clearChatHistory()}_sendFeedback(e,r,n,o){let s=`https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(r)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({agent:o}))}&field:version=${encodeURIComponent("v2")}`;window.open(s,"_blank")}async _loadUserFirstName(){try{let e=await this._configContextConsumer.value?.userSession?.getUser();if(e?.fullName){let r=e.fullName.split(" ")[0];this.userFirstName=r}}catch{}}_captureResponseMetadata(e){let r=Array.from(this._assistantRef.value?.messages||[]);for(let n=r.length-1;n>=0;n--){let o=r[n];if(o.role==="assistant"&&!this._responseMetadata.has(o.id)){let s;for(let i=n-1;i>=0;i--){let a=r[i];if(a.role==="user"){s=a.content;break}}return this._responseMetadata.set(o.id,{agent:e,userMessage:s}),!0}}return!1}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],o=[...r].sort((u,m)=>m.id-u.id).find(u=>u.role==="user"&&u.id<=e.id)?.content||null,s=n.find(u=>typeof u=="string"&&u.includes("Agent picked:"))??null;if(!s)return{agentPicked:null,taskAssigned:null,userMessage:o};let i=/Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i,a=s.match(i);if(!a)return{agentPicked:null,taskAssigned:null,userMessage:o};let c=a[1].trim(),l=a[2].trim();return{agentPicked:c,taskAssigned:l,userMessage:o}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};Fl("arcgis-solutions-assistant",bl);return bl},"config","identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","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","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,c)
|