@esri/solutions-components 5.1.2 → 5.1.3
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/{7EJXZVSX.js → 2CCKYJSY.js} +1 -1
- package/dist/cdn/{3KYCZII7.js → 2DCSGUOX.js} +1 -1
- package/dist/cdn/{LSMP2ZCO.js → 2EUQOQY3.js} +1 -1
- package/dist/cdn/{FSFVH74N.js → 2GHTA5PV.js} +1 -1
- package/dist/cdn/{3DNEBMT3.js → 2GJEHDZJ.js} +1 -1
- package/dist/cdn/{LRGW6G5E.js → 2XTZLJ5F.js} +1 -1
- package/dist/cdn/{CKPQTIAF.js → 37CMWBMW.js} +1 -1
- package/dist/cdn/{SD3DV4KO.js → 37XAYW3Z.js} +1 -1
- package/dist/cdn/{LQFA6HOT.js → 3DFMPPUD.js} +1 -1
- package/dist/cdn/{LXJI7FYN.js → 3MN7XFQ2.js} +1 -1
- package/dist/cdn/{EHIUCEAX.js → 3N2AUH5S.js} +1 -1
- package/dist/cdn/{OPWMEQVM.js → 3TO6KC3G.js} +2 -2
- package/dist/cdn/{OVAQRVFG.js → 3XOKCST3.js} +1 -1
- package/dist/cdn/{GZZMHIFA.js → 43MZA66W.js} +1 -1
- package/dist/cdn/{T7O4WZGU.js → 45JNINYV.js} +1 -1
- package/dist/cdn/{RQVXDCWL.js → 4PDKVX4T.js} +1 -1
- package/dist/cdn/{DEVAXAP7.js → 56PIVLPU.js} +1 -1
- package/dist/cdn/{ZB5UCRCG.js → 5BJO5ABV.js} +1 -1
- package/dist/cdn/{QVD3AXIP.js → 5EYRW6FE.js} +1 -1
- package/dist/cdn/{L6XSVTY3.js → 5L7HZJBG.js} +1 -1
- package/dist/cdn/{4RH7N22O.js → 5LM5R34X.js} +1 -1
- package/dist/cdn/{JF2ASXUT.js → 6AVCTQ6J.js} +1 -1
- package/dist/cdn/{PSM4UX7K.js → 6AWTIASQ.js} +1 -1
- package/dist/cdn/{NIUKLQOT.js → 6FPVZV4K.js} +1 -1
- package/dist/cdn/{WVCL5OUK.js → 6SHN7V3N.js} +1 -1
- package/dist/cdn/{IVMHEGLY.js → 6UVMG6O6.js} +1 -1
- package/dist/cdn/{RPL5Q7IL.js → 7IKNLW73.js} +1 -1
- package/dist/cdn/{5IO4VX4R.js → AHC3CH4P.js} +1 -1
- package/dist/cdn/{74Z5A6E2.js → AKXVDLK3.js} +1 -1
- package/dist/cdn/AO7XKW2U.js +4 -0
- package/dist/cdn/{BZWJ3KFS.js → ATEM3GJU.js} +104 -104
- package/dist/cdn/{3NI2BJYO.js → AULN2QXN.js} +1 -1
- package/dist/cdn/{GRVDJVOF.js → AX2U2PGS.js} +1 -1
- package/dist/cdn/{YBJ6AHAG.js → B57TWGXS.js} +1 -1
- package/dist/cdn/{EX4K4RKP.js → B7YYMYZB.js} +1 -1
- package/dist/cdn/{SQEPSAKG.js → BACWGZE4.js} +1 -1
- package/dist/cdn/{BWNEUQZZ.js → BDAY2SRY.js} +1 -1
- package/dist/cdn/{O6IGMQN7.js → BOQUQFNT.js} +1 -1
- package/dist/cdn/{LKVPVQIC.js → BTOTDVAS.js} +1 -1
- package/dist/cdn/{6L6JOGWD.js → BWFET22E.js} +1 -1
- package/dist/cdn/{DXI5HEQM.js → C7YLT2V6.js} +1 -1
- package/dist/cdn/{V24CDHGH.js → CAXEJ55N.js} +1 -1
- package/dist/cdn/{LCDURBN6.js → CYKO5XJY.js} +1 -1
- package/dist/cdn/{HOSSEVH5.js → DDUV67TU.js} +1 -1
- package/dist/cdn/{UDWEFNJE.js → DRZ2MEHM.js} +1 -1
- package/dist/cdn/DTTQLI5W.js +2 -0
- package/dist/cdn/{5FW45CM6.js → EJK7PYN5.js} +1 -1
- package/dist/cdn/{C2GWD5VP.js → ENJC4SNG.js} +1 -1
- package/dist/cdn/{WNYAZ4ME.js → ESH7SFXX.js} +1 -1
- package/dist/cdn/{B7CVHLVL.js → F46RK2J3.js} +1 -1
- package/dist/cdn/{MZ5XI2CY.js → F6H43GFC.js} +1 -1
- package/dist/cdn/{ECUD4NU6.js → FAHLQLKD.js} +1 -1
- package/dist/cdn/{QMQAQSIA.js → FKQHOE2A.js} +1 -1
- package/dist/cdn/{7AHZBLTM.js → FL4YRGDB.js} +1 -1
- package/dist/cdn/{KPEPW4QL.js → FPBZRT3J.js} +1 -1
- package/dist/cdn/{UILBHLN7.js → FWRNU7AK.js} +1 -1
- package/dist/cdn/{BFFHQBDI.js → G63VTGNV.js} +1 -1
- package/dist/cdn/{QODVIACF.js → GCDVJH5S.js} +1 -1
- package/dist/cdn/{EBDDUQNC.js → GCLCH6NX.js} +1 -1
- package/dist/cdn/{MVXK7UGO.js → GLD7SDA5.js} +1 -1
- package/dist/cdn/{KB7CXY4N.js → GVREVCUB.js} +1 -1
- package/dist/cdn/{ZHVO477V.js → HCY3VGST.js} +1 -1
- package/dist/cdn/{65I4AUS4.js → HKURBCD6.js} +1 -1
- package/dist/cdn/{XA6ZDTKA.js → HSZJX2Q4.js} +1 -1
- package/dist/cdn/{GSLDFLWZ.js → HXCNKN3S.js} +1 -1
- package/dist/cdn/{JB5XLSNA.js → IK3L2OC3.js} +1 -1
- package/dist/cdn/{O6HS2AMH.js → IKA3ESQ5.js} +1 -1
- package/dist/cdn/{Y7Z6LFBH.js → IXSDSBUI.js} +1 -1
- package/dist/cdn/{XXRBPKMI.js → J5Q7IGCO.js} +1 -1
- package/dist/cdn/{KMY4AVEA.js → J6PFJWXU.js} +1 -1
- package/dist/cdn/{QTCXH2O3.js → JBBUAR3W.js} +1 -1
- package/dist/cdn/{3CSSTWYC.js → JCPQ7OOS.js} +1 -1
- package/dist/cdn/{BSIPKI63.js → JNQB7T54.js} +1 -1
- package/dist/cdn/{J7DTCWOP.js → JX7BWUKD.js} +1 -1
- package/dist/cdn/{CC7JGR5Q.js → KGL266WS.js} +1 -1
- package/dist/cdn/{MXPZF4RB.js → KGXEY5HR.js} +1 -1
- package/dist/cdn/{EJRV6YWD.js → KN5XFC7O.js} +1 -1
- package/dist/cdn/{FDNEF4QD.js → KU2QSXAD.js} +1 -1
- package/dist/cdn/{65OXHGCN.js → KX4F4INQ.js} +1 -1
- package/dist/cdn/{7XPOQHB4.js → KZBPVSUW.js} +1 -1
- package/dist/cdn/{VSRNGZ43.js → LABCYKSC.js} +1 -1
- package/dist/cdn/{WRMREY3V.js → LI3GKZ35.js} +1 -1
- package/dist/cdn/{7NQYBMRX.js → MIKSQTTI.js} +1 -1
- package/dist/cdn/{CVKCFLNY.js → MOHSZVTU.js} +1 -1
- package/dist/cdn/{LFIP5DV3.js → MWTTZLRQ.js} +1 -1
- package/dist/cdn/{GHVPHEOH.js → MXNYBLUV.js} +1 -1
- package/dist/cdn/{AS7PVOU3.js → MZ63UWGX.js} +1 -1
- package/dist/cdn/N4MCHYQT.js +2 -0
- package/dist/cdn/{MVSQRD5M.js → NAZXHTIH.js} +1 -1
- package/dist/cdn/{GSI62QHB.js → NBWMZOGE.js} +1 -1
- package/dist/cdn/{NJSQ3NUT.js → NGAS7OCN.js} +1 -1
- package/dist/cdn/{6RQBPR56.js → O7LSXSBD.js} +1 -1
- package/dist/cdn/{DF2U7HIU.js → OLN76PG4.js} +1 -1
- package/dist/cdn/PIRHBQVO.js +351 -0
- package/dist/cdn/{LSDYUCCZ.js → PLELSLAV.js} +1 -1
- package/dist/cdn/{6KBY56R4.js → PPLHKHZ3.js} +1 -1
- package/dist/cdn/{HQFL3NGM.js → PWGCOGC7.js} +1 -1
- package/dist/cdn/{DLV7AZZ6.js → QEITYICZ.js} +1 -1
- package/dist/cdn/{KLZWOBGK.js → QVDDWNQD.js} +1 -1
- package/dist/cdn/{ZXGNDW3R.js → QWUJHEPY.js} +1 -1
- package/dist/cdn/R437P4KQ.js +2 -0
- package/dist/cdn/{ZSATEDPE.js → RKVNFHFD.js} +1 -1
- package/dist/cdn/{CVNW2AU2.js → RM6HYEWM.js} +1 -1
- package/dist/cdn/{GWIC6C6P.js → RNMVOUE3.js} +1 -1
- package/dist/cdn/{C3SIGIJC.js → RQQWTDQG.js} +1 -1
- package/dist/cdn/{XIUYVZYL.js → S3CBTGXW.js} +1 -1
- package/dist/cdn/{XYAVR2MM.js → SGWJLKO4.js} +1 -1
- package/dist/cdn/{BKIKLE4Z.js → SI2EHJJ5.js} +1 -1
- package/dist/cdn/{Z6CZ7GFZ.js → SY3D5J7W.js} +1 -1
- package/dist/cdn/{3FIRDPVD.js → TBXAQ6YS.js} +1 -1
- package/dist/cdn/{Q5N7I65T.js → TFWTXEN7.js} +1 -1
- package/dist/cdn/{YHF3Q7QB.js → TKIL55TV.js} +1 -1
- package/dist/cdn/{NVNB4L52.js → TSLAML4I.js} +1 -1
- package/dist/cdn/{5Q64VY2E.js → UCHXRVI7.js} +1 -1
- package/dist/cdn/{PQVA7SKB.js → UE2HAEBW.js} +1 -1
- package/dist/cdn/{E3O6DPAL.js → UEC5OGAS.js} +1 -1
- package/dist/cdn/{DE7GSGUB.js → UKAP3ALW.js} +1 -1
- package/dist/cdn/{CRTJERAB.js → UNKENPV5.js} +1 -1
- package/dist/cdn/{5F6WBFDO.js → V4OFLP6D.js} +1 -1
- package/dist/cdn/{LK6WQCXQ.js → VBZL2GZD.js} +1 -1
- package/dist/cdn/{RNNEZRGA.js → VLP6VQEG.js} +1 -1
- package/dist/cdn/{INFZEU32.js → VZY472CH.js} +1 -1
- package/dist/cdn/{P2FSR5OV.js → WEADUP3Y.js} +1 -1
- package/dist/cdn/{Y2KRCLNN.js → WKTMPKVR.js} +1 -1
- package/dist/cdn/{E5YZOOW3.js → WXFKH5GM.js} +1 -1
- package/dist/cdn/{RAL6IXW5.js → X52CK3FZ.js} +1 -1
- package/dist/cdn/{4MAH5ULJ.js → X7GGOH2R.js} +1 -1
- package/dist/cdn/{RJLEYL7O.js → XEON6B7Z.js} +1 -1
- package/dist/cdn/{SAVDBHDE.js → XL66TA6C.js} +1 -1
- package/dist/cdn/{KPKJ2OVD.js → XN5455P6.js} +1 -1
- package/dist/cdn/{DQJ36YEL.js → XOCNSPTC.js} +1 -1
- package/dist/cdn/{TK5EXRZL.js → XOPNEAS5.js} +1 -1
- package/dist/cdn/{YVNBCXBJ.js → XR3PT7FP.js} +1 -1
- package/dist/cdn/{LOSU3FPH.js → XSJOQTEM.js} +1 -1
- package/dist/cdn/{6OKLCUSH.js → Y2DDFGCN.js} +1 -1
- package/dist/cdn/{6F6YFDOY.js → YWO5HXXP.js} +1 -1
- package/dist/cdn/{NWOPIQFN.js → ZIIHIUUV.js} +1 -1
- package/dist/cdn/{Q6CXYCV6.js → ZOGD4MGP.js} +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/runtime.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 +1 -1
- package/dist/cdn/A4KEZALJ.js +0 -2
- package/dist/cdn/CGQALCTZ.js +0 -4
- package/dist/cdn/CXTHIJOC.js +0 -351
- package/dist/cdn/GPIIJWNM.js +0 -2
- package/dist/cdn/IGY23J7D.js +0 -2
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import{d as xr,e as ro,f as Di,g as Fi,h as ji}from"./NQH7ZZWD.js";import{a as Li}from"./MHMM4RFR.js";import{a as ac,b as lc,c as cc,f as os,g as ss,j as uc}from"./JNQB7T54.js";import b from"./XOCNSPTC.js";import a from"./XOPNEAS5.js";import{b as Dl,c as Fl}from"./2B4SGB3I.js";import{b as Ti}from"./RLSY4VUQ.js";import"./AO7XKW2U.js";import{a as Ll}from"./LABCYKSC.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as Hl,Aa as nc,Ba as es,Ca as ts,Da as oc,Db as rs,Ea as sc,Eb as ns,Fa as Ar,Fb as ge,Ga as I,Ha as L,Ia as $i,J as ql,Ja as Ni,K as Te,L as Bl,M as Wo,N as Ci,O as ki,P as Ho,Q as Xn,R as K,S as Ei,T as U,Ta as O,U as ct,V as ut,W as Vo,X as Kl,Y as Wl,Z as Oi,_ as Go,a as he,aa as Vl,b as W,ba as eo,ca as Jo,da as Gl,ea as Jl,fa as Zl,g as Ul,ga as Zo,ha as Ql,ia as Rt,j as We,ja as Pi,k as Mt,ka as Qo,la as N,ma as v,mb as ic,na as $t,oa as dt,pa as Yl,qa as Yo,ra as Xl,s as Bo,sa as ec,ta as Xo,ua as Mi,va as br,wa as Ri,xa as tc,y as Ko,ya as rc,zb as to}from"./ATEM3GJU.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 jl,v as Si}from"./3TAQSXLA.js";import"./PY6RTQDR.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as Nl}from"./5BJO5ABV.js";import{F as Ml,G as Rl,H as $l,L as Ii,h as Sl,i as lt,k as Cl,l as xi,q as vi,t as kl,w as El,x as Ol,y as Pl}from"./T3EPRHTT.js";import{c as Tl}from"./EXBEKVP5.js";export default $arcgis.t(([fl,B2,W2,Xd,zg,Ug,Yg,Q2,X2,aJ,wA,_p,gr,Ja,Tp,,wp,ry,{addressToLocations:ny},oy,sy,Sp,{createRenderer:iy},{getSchemesByTag:ay,getSchemes:ly},{getBackgroundColorTheme:bp},{createAgeRenderer:cy,createContinuousRenderer:uy},{getSchemesByTag:sl},{createContinuousRenderer:dy},{createRenderer:py},{getSchemesByTag:my},{createRenderer:fy},{getSchemesByTag:hy},{createRenderer:gy},{getSchemesByTag:yy},{createRenderer:_y},{getSchemesByTag:wy},{createAgeRenderer:by,createContinuousRenderer:Ay},{createRenderer:xy},{getSchemesByTag:vy},Iy,Cp,kp,{formatDateOnly:Ty,convertDateFormatToIntlOptions:Ys,formatTimeOnly:Sy,formatDate:Ap},Cy,ky,Ey,Oy,Py,Ep,,{fetchKnowledgeGraph:xp,executeQueryStreaming:My,executeSearchStreaming:Ry},$y,,,,,,,,,,,,,,,,,,,,,,,,,lG,uG,,,,,,,,,,,,,$A,NA,{r:zl},{r:Yn}])=>{var no=class extends Pl{constructor(e){if(super(e),this.it=xi,e.type!==El.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===xi||e==null)return this._t=void 0,this.it=e;if(e===Cl)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 dc=Ol(no);var d=I;async function zi(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
|
+
|
|
4
|
+
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
5
|
+
|
|
6
|
+
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
7
|
+
|`,`
|
|
8
|
+
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
9
|
+
`].join(" "));let n=await Vl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var Z=async(t,e)=>{await zi("trace_message",t,e)},ye=async(t,e)=>{await zi("graph_ux_suggestion",t,e)};var dm={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"}},vv=Object.keys(dm);var Bi=Symbol.for("langgraph-zod");Bi in globalThis||(globalThis[Bi]=new WeakSet);function fc(t){let e=globalThis[Bi];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return ns(r,{jsonSchemaExtra:n})},reducer(n,o){return ns(r,{default:Qo(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{fc(v.ZodType.prototype),fc(I.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 hc=class extends Jl{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)}},hm=new hc(rs);var Pm=v.function().args(v.custom()).returns(v.union([v.boolean(),v.promise(v.boolean())])),Mm=v.function().args(v.custom(),v.custom(),v.custom()).returns(v.union([v.string(),v.promise(v.string())])),Rm=["approve","edit","reject"],$m=v.enum(Rm),Nm=v.object({allowedDecisions:v.array($m),description:v.union([v.string(),Mm]).optional(),argsSchema:v.record(v.any()).optional(),when:Pm.optional()}),MS=v.object({interruptOn:v.record(v.union([v.boolean(),Nm])).optional(),descriptionPrefix:v.string().default("Tool execution requires approval")});var Fm=`<role>
|
|
10
|
+
Context Extraction Assistant
|
|
11
|
+
</role>
|
|
12
|
+
|
|
13
|
+
<primary_objective>
|
|
14
|
+
Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
|
|
15
|
+
</primary_objective>
|
|
16
|
+
|
|
17
|
+
<objective_information>
|
|
18
|
+
You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
|
|
19
|
+
This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
|
|
20
|
+
</objective_information>
|
|
21
|
+
|
|
22
|
+
<instructions>
|
|
23
|
+
The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
|
|
24
|
+
You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
|
|
25
|
+
</instructions>
|
|
26
|
+
|
|
27
|
+
The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
|
|
28
|
+
|
|
29
|
+
With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
|
|
30
|
+
Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
|
|
31
|
+
|
|
32
|
+
<messages>
|
|
33
|
+
Messages to summarize:
|
|
34
|
+
{messages}
|
|
35
|
+
</messages>`;var jm=v.function().args(v.array(v.custom())).returns(v.union([v.number(),v.promise(v.number())])),Ji=v.object({fraction:v.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:v.number().positive("Tokens must be greater than 0").optional(),messages:v.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"}),Ic=v.object({fraction:v.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:v.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:v.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"}),ZS=v.object({model:v.custom(),trigger:v.union([Ji,v.array(Ji)]).optional(),keep:Ic.optional(),tokenCounter:jm.optional(),summaryPrompt:v.string().default(Fm),trimTokensToSummarize:v.number().optional(),summaryPrefix:v.string().optional(),maxTokensBeforeSummary:v.number().optional(),messagesToKeep:v.number().optional()});var aC=v.object({model:v.string().or(v.instanceof(Xl)).optional(),systemPrompt:v.string().optional(),maxTools:v.number().optional(),alwaysInclude:v.array(v.string()).optional()});var fC=v.object({applyToInput:v.boolean().optional(),applyToOutput:v.boolean().optional(),applyToToolResults:v.boolean().optional()});var wC=v.object({rules:v.record(v.string(),v.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var zm=["continue","error","end"],Um="continue";var qm=v.enum(zm).default(Um);v.object({toolName:v.string().optional(),threadLimit:v.number().optional(),runLimit:v.number().optional(),exitBehavior:qm});var OC=v.object({threadToolCallCount:v.record(v.string(),v.number()).default({}),runToolCallCount:v.record(v.string(),v.number()).default({})});var Bm=v.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Km=v.object({content:v.string().describe("Content of the todo item"),status:Bm}),FC=v.object({todos:v.array(Km).default([])});var BC=v.object({threadLimit:v.number().optional(),runLimit:v.number().optional(),exitBehavior:v.enum(["error","end"]).optional()}),KC=v.object({threadModelCallCount:v.number().default(0),runModelCallCount:v.number().default(0)});var is=v.object({maxRetries:v.number().min(0).default(2),retryOn:v.union([v.function().args(v.instanceof(Error)).returns(v.boolean()),v.array(v.custom())]).default(()=>()=>!0),backoffFactor:v.number().min(0).default(2),initialDelayMs:v.number().min(0).default(1e3),maxDelayMs:v.number().min(0).default(6e4),jitter:v.boolean().default(!0)});var ok=v.object({onFailure:v.union([v.literal("error"),v.literal("continue"),v.function().args(v.instanceof(Error)).returns(v.string())]).default("continue")}).merge(is);var pk=v.object({tools:v.array(v.union([v.custom(),v.custom(),v.string()])).optional(),onFailure:v.union([v.literal("error"),v.literal("continue"),v.literal("raise"),v.literal("return_message"),v.function().args(v.instanceof(Error)).returns(v.string())]).default("continue")}).merge(is);var Ck=v.object({enableCaching:v.boolean().optional(),ttl:v.enum(["5m","1h"]).optional(),minMessagesToCache:v.number().optional(),unsupportedModelBehavior:v.enum(["ignore","warn","raise"]).optional()});var Pk=v.object({enableCaching:v.boolean().optional(),ttl:v.enum(["5m","1h"]).optional(),minMessagesToCache:v.number().optional(),unsupportedModelBehavior:v.enum(["ignore","warn","raise"]).optional()});function oo(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
36
|
+
|
|
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 w(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{},H=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 mt({message:n,cause:io(r)});let s=r?.error;return e===400?new Ir(e,s,n,o):e===401?new Tr(e,s,n,o):e===403?new Sr(e,s,n,o):e===404?new Cr(e,s,n,o):e===409?new kr(e,s,n,o):e===422?new Er(e,s,n,o):e===429?new Or(e,s,n,o):e>=500?new Pr(e,s,n,o):new t(e,s,n,o)}},V=class extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},mt=class extends H{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ne=class extends mt{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ir=class extends H{},Tr=class extends H{},Sr=class extends H{},Cr=class extends H{},kr=class extends H{},Er=class extends H{},Or=class extends H{},Pr=class extends H{},Mr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Rr=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Le=class extends Error{constructor(e){super(e)}},Lt=class extends H{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 ef=/^[a-z][a-z0-9+.-]*:/i,Tc=t=>ef.test(t),de=t=>(de=Array.isArray,de(t)),Qi=de;function as(t){return typeof t!="object"?{}:t??{}}function Yi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Sc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function lo(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Cc=(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 kc=t=>{try{return JSON.parse(t)}catch{return}};var De=t=>new Promise(e=>setTimeout(e,t));var ft="6.45.0";var Mc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function tf(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var rf=()=>{let t=tf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"X-Stainless-OS":Oc(Deno.build.os),"X-Stainless-Arch":Ec(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":ft,"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":ft,"X-Stainless-OS":Oc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ec(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=nf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ft,"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":ft,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function nf(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let 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 Ec=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Oc=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"),Pc,Rc=()=>Pc??(Pc=rf());function ls(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function 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 cs(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 Nc=({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},Lc="RFC1738";var us=(t,e)=>(us=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),us(t,e)),Fe=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var sa=1024,Dc=(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 p=c.charCodeAt(u);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===Lc&&(p===40||p===41)){l[l.length]=c.charAt(u);continue}if(p<128){l[l.length]=Fe[p];continue}if(p<2048){l[l.length]=Fe[192|p>>6]+Fe[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Fe[224|p>>12]+Fe[128|p>>6&63]+Fe[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Fe[240|p>>18]+Fe[128|p>>12&63]+Fe[128|p>>6&63]+Fe[128|p&63]}i+=l.join("")}return i};function Fc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ia(t,e){if(de(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var zc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Uc=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},jc,te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Dc,encodeValuesOnly:!1,format:ra,formatter:na,indices:!1,serializeDate(t){return(jc??(jc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function sf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var aa={};function qc(t,e,r,n,o,s,i,a,c,l,u,p,f,y,b,A,_,h){let x=t,S=h,E=0,q=!1;for(;(S=S.get(aa))!==void 0&&!q;){let Y=S.get(t);if(E+=1,typeof Y<"u"){if(Y===E)throw new RangeError("Cyclic object value");q=!0}typeof S.get(aa)>"u"&&(E=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&de(x)&&(x=ia(x,function(Y){return Y instanceof Date?f?.(Y):Y})),x===null){if(s)return c&&!A?c(e,te.encoder,_,"key",y):e;x=""}if(sf(x)||Fc(x)){if(c){let Y=A?e:c(e,te.encoder,_,"key",y);return[b?.(Y)+"="+b?.(c(x,te.encoder,_,"value",y))]}return[b?.(e)+"="+b?.(String(x))]}let M=[];if(typeof x>"u")return M;let z;if(r==="comma"&&de(x))A&&c&&(x=ia(x,c)),z=[{value:x.length>0?x.join(",")||null:void 0}];else if(de(l))z=l;else{let Y=Object.keys(x);z=u?Y.sort(u):Y}let B=a?String(e).replace(/\./g,"%2E"):String(e),ue=n&&de(x)&&x.length===1?B+"[]":B;if(o&&de(x)&&x.length===0)return ue+"[]";for(let Y=0;Y<z.length;++Y){let ee=z[Y],vl=typeof ee=="object"&&typeof ee.value<"u"?ee.value:x[ee];if(i&&vl===null)continue;let Ai=p&&a?ee.replace(/\./g,"%2E"):ee,cm=de(x)?typeof r=="function"?r(ue,Ai):ue:ue+(p?"."+Ai:"["+Ai+"]");h.set(t,E);let Il=new WeakMap;Il.set(aa,h),Uc(M,qc(vl,cm,r,n,o,s,i,a,r==="comma"&&A&&de(x)?null:c,l,u,p,f,y,b,A,_,Il))}return M}function af(t=te){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||te.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=ra;if(typeof t.format<"u"){if(!us(oa,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=oa[r],o=te.filter;(typeof t.filter=="function"||de(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in zc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=te.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:te.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:te.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:te.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:te.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?te.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:te.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:te.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:te.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:te.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:te.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:te.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:te.strictNullHandling}}function Bc(t,e={}){let r=t,n=af(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):de(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=zc[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 y=o[f];n.skipNulls&&r[y]===null||Uc(i,qc(r[y],y,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),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),u.length>0?p+u:""}function Kc(t){return Bc(t,{arrayFormat:"brackets"})}function Vc(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 Wc;function $r(t){let e;return(Wc??(e=new globalThis.TextEncoder,Wc=e.encode.bind(e)))(t)}var Hc;function la(t){let e;return(Hc??(e=new globalThis.TextDecoder,Hc=e.decode.bind(e)))(t)}var _e,we,Dt=class{constructor(){_e.set(this,void 0),we.set(this,void 0),k(this,_e,new Uint8Array,"f"),k(this,we,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?$r(e):e;k(this,_e,Vc([w(this,_e,"f"),r]),"f");let n=[],o;for(;(o=cf(w(this,_e,"f"),w(this,we,"f")))!=null;){if(o.carriage&&w(this,we,"f")==null){k(this,we,o.index,"f");continue}if(w(this,we,"f")!=null&&(o.index!==w(this,we,"f")+1||o.carriage)){n.push(la(w(this,_e,"f").subarray(0,w(this,we,"f")-1))),k(this,_e,w(this,_e,"f").subarray(w(this,we,"f")),"f"),k(this,we,null,"f");continue}let s=w(this,we,"f")!==null?o.preceding-1:o.preceding,i=la(w(this,_e,"f").subarray(0,s));n.push(i),k(this,_e,w(this,_e,"f").subarray(o.index),"f"),k(this,we,null,"f")}return n}flush(){return w(this,_e,"f").length?this.decode(`
|
|
39
|
+
`):[]}};_e=new WeakMap,we=new WeakMap;Dt.NEWLINE_CHARS=new Set([`
|
|
40
|
+
`,"\r"]);Dt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function cf(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 Gc(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 ps={off:0,error:200,warn:300,info:400,debug:500},ca=(t,e,r)=>{if(t){if(Sc(ps,t))return t;Q(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ps))}`)}};function co(){}function ds(t,e,r){return!e||ps[t]>ps[r]?co:e[t].bind(e)}var uf={error:co,warn:co,info:co,debug:co},Jc=new WeakMap;function Q(t){let e=t.logger,r=t.logLevel??"off";if(!e)return uf;let n=Jc.get(e);if(n&&n[0]===r)return n[1];let o={error:ds("error",e,r),warn:ds("warn",e,r),info:ds("info",e,r),debug:ds("debug",e,r)};return Jc.set(e,[r,o]),o}var He=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var uo,je=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?Q(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 df(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(p){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),p}if(u&&u.error)throw new H(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(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new H(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 Dt,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,w(this,uo,"f")),new t(()=>o(r),this.controller,w(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=$r(JSON.stringify(o)+`
|
|
41
|
+
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*df(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 Dt,o=ea(t.body);for await(let s of pf(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*pf(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"?$r(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Gc(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]=mf(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function mf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ms(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return Q(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):je.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let 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 Q(t).debug(`[${n}] response parsed`,He({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,Ft=class t extends Promise{constructor(e,r,n=ms){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(w(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(w(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 fs,Nr=class{constructor(e,r,n,o){fs.set(this,void 0),k(this,fs,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 w(this,fs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},mo=class extends Ft{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await ms(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends Nr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},$=class extends Nr{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:{...as(this.options.query),after:r}}:null}},F=class extends Nr{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:{...as(this.options.query),after:e}}:null}},X=class extends Nr{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:{...as(this.options.query),after:e}}:null}};var hf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},gf="urn:ietf:params:oauth:grant-type:token-exchange",hs=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ls()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r={grant_type:gf,subject_token:e,subject_token_type:hf[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 c=await n.text(),l;try{l=JSON.parse(c)}catch{}throw n.status===400||n.status===401||n.status===403?new Lt(n.status,l,n.headers):H.generate(n.status,l,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new C("Token exchange response missing 'access_token' field");let s=o.access_token,i=o.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:s,expiresAt:a},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var 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 Lr(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 gs=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",ht=async(t,e)=>pa(t.body)?{...t,body:await Qc(t.body,e)}:t,me=async(t,e)=>({...t,body:await Qc(t.body,e)}),Zc=new WeakMap;function yf(t){let e=typeof t=="function"?t:t.fetch,r=Zc.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 Zc.set(e,n),n}var Qc=async(t,e)=>{if(!await yf(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},Yc=t=>t instanceof Blob&&"name"in t,_f=t=>typeof t=="object"&&t!==null&&(t instanceof Response||gs(t)||Yc(t)),pa=t=>{if(_f(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,Lr([await r.blob()],fo(r)));else if(gs(r))t.append(e,Lr([await new Response(cs(r)).blob()],fo(r)));else if(Yc(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 Xc=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",wf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Xc(t),bf=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,wf(t))return t instanceof File?t:Lr([await t.arrayBuffer()],t.name);if(bf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Lr(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 Lr(n,e,r)}async function ha(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Xc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(gs(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}`:""}${Af(t)}`)}return e}function Af(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var g=class{constructor(e){this._client=e}};function tu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var eu=Object.freeze(Object.create(null)),vf=(t=tu)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i=r.reduce((u,p,f)=>{/[?#]/.test(p)&&(o=!0);let y=n[f],b=(o?encodeURIComponent:t)(""+y);return f!==n.length&&(y==null||typeof y=="object"&&y.toString===Object.getPrototypeOf(Object.getPrototypeOf(y.hasOwnProperty??eu)??eu)?.toString)&&(b=y+"",s.push({start:u.length+p.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(y).slice(8,-1)} is not a valid path parameter`})),u+p+(f===n.length?"":b)},""),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,p)=>u.start-p.start),s.length>0){let u=0,p=s.reduce((f,y)=>{let b=" ".repeat(y.start-u),A="^".repeat(y.length);return u=y.start+y.length,f+b+A},"");throw new C(`Path parameters result in path with invalid segments:
|
|
43
|
+
${s.map(f=>f.error).join(`
|
|
44
|
+
`)}
|
|
45
|
+
${i}
|
|
46
|
+
${p}`)}return i},m=vf(tu);var jt=class extends g{list(e,r={},n){return this._client.getAPIList(m`/chat/completions/${e}/messages`,$,{query:r,...n,__security:{bearerAuth:!0}})}};function go(t){return t!==void 0&&"function"in t&&t.function!==void 0}function nu(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 zt(t){return t?.$brand==="auto-parseable-tool"}function ou(t,e){return!e||!ga(e)?{...t,choices:t.choices.map(r=>(iu(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 Mr;if(n.finish_reason==="content_filter")throw new Rr;return iu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Sf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Tf(e,n.message.content):null}}});return{...t,choices:r}}function Tf(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 Sf(t,e){let r=t.tools?.find(n=>go(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:zt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function su(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>go(n)&&n.function?.name===e.function.name);return go(r)&&(zt(r)||r?.function.strict||!1)}function ga(t){return yo(t.response_format)?!0:t.tools?.some(e=>zt(e)||e.type==="function"&&e.function.strict===!0)??!1}function iu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function au(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 Dr=t=>t?.role==="assistant",ya=t=>t?.role==="tool";var ys,_s,ws,wo,bo,bs,Ao,Ve,As,xo,xs,vs,Fr,lu,cu,gt=class{constructor(){ys.add(this),this.controller=new AbortController,_s.set(this,void 0),ws.set(this,()=>{}),wo.set(this,()=>{}),bo.set(this,void 0),bs.set(this,()=>{}),Ao.set(this,()=>{}),Ve.set(this,{}),As.set(this,[]),xo.set(this,!1),xs.set(this,!1),vs.set(this,!1),Fr.set(this,!1),k(this,_s,new Promise((e,r)=>{k(this,ws,e,"f"),k(this,wo,r,"f")}),"f"),k(this,bo,new Promise((e,r)=>{k(this,bs,e,"f"),k(this,Ao,r,"f")}),"f"),w(this,_s,"f").catch(()=>{}),w(this,bo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,ys,"m",cu).bind(this))},0)}_connected(){this.ended||(w(this,ws,"f").call(this),this._emit("connect"))}get ended(){return w(this,xo,"f")}get errored(){return w(this,xs,"f")}get aborted(){return w(this,vs,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),w(this,As,"f").push({signal:e,listener:r})}on(e,r){return(w(this,Ve,"f")[e]||(w(this,Ve,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=w(this,Ve,"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(w(this,Ve,"f")[e]||(w(this,Ve,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{k(this,Fr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){k(this,Fr,!0,"f"),await w(this,bo,"f")}_emit(e,...r){if(w(this,xo,"f"))return;e==="end"&&(w(this,ys,"m",lu).call(this),k(this,xo,!0,"f"),w(this,bs,"f").call(this));let n=w(this,Ve,"f")[e];if(n&&(w(this,Ve,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!w(this,Fr,"f")&&!n?.length&&Promise.reject(o),w(this,wo,"f").call(this,o),w(this,Ao,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!w(this,Fr,"f")&&!n?.length&&Promise.reject(o),w(this,wo,"f").call(this,o),w(this,Ao,"f").call(this,o),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,ws=new WeakMap,wo=new WeakMap,bo=new WeakMap,bs=new WeakMap,Ao=new WeakMap,Ve=new WeakMap,As=new WeakMap,xo=new WeakMap,xs=new WeakMap,vs=new WeakMap,Fr=new WeakMap,ys=new WeakSet,lu=function(){for(let{signal:e,listener:r}of w(this,As,"f").splice(0))e.removeEventListener("abort",r)},cu=function(e){if(k(this,xs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new V),e instanceof V)return k(this,vs,!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 uu(t){return typeof t.parse=="function"}var fe,_a,Is,wa,ba,Aa,du,pu,Cf=10,jr=class extends gt{constructor(){super(...arguments),fe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),ya(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Dr(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(),w(this,fe,"m",_a).call(this)}async finalMessage(){return await this.done(),w(this,fe,"m",Is).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,fe,"m",wa).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,fe,"m",ba).call(this)}async totalUsage(){return await this.done(),w(this,fe,"m",Aa).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=w(this,fe,"m",Is).call(this);r&&this._emit("finalMessage",r);let n=w(this,fe,"m",_a).call(this);n&&this._emit("finalContent",n);let o=w(this,fe,"m",wa).call(this);o&&this._emit("finalFunctionToolCall",o);let s=w(this,fe,"m",ba).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",w(this,fe,"m",Aa).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),w(this,fe,"m",du).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_o(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:i="auto",stream:a,...c}=r,l=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:u=Cf,afterCompletion:p}=o||{},f=r.tools.map(_=>{if(zt(_)){if(!_.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),y={};for(let _ of f)_.type==="function"&&(y[_.function.name||_.function.function.name]=_.function);let b="tools"in r?f.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(let _ of r.messages)this._addMessage(_,!1);let A=async _=>{if(_.type!=="function")return{message:void 0,functionCalled:!1};let h=_.id,{name:x,arguments:S}=_.function,E=y[x];if(!E){let z=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(y).map(B=>JSON.stringify(B)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:h,content:z},functionCalled:!1}}if(l&&l!==x){let z=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:h,content:z},functionCalled:!1}}let q;if(uu(E)){let z;try{z=await E.parse(S)}catch(B){let ue=B instanceof Error?B.message:String(B);return{message:{role:s,tool_call_id:h,content:ue},functionCalled:!1}}q=await E.function(z,n)}else q=await E.function(S,n);let M=w(this,fe,"m",pu).call(this,q);return{message:{role:s,tool_call_id:h,content:M},functionCalled:!0}};for(let _=0;_<u;++_){let h=await this._createChatCompletion(e,{...c,tool_choice:i,tools:b,messages:[...this.messages]},o),x=h.choices[0]?.message;if(!x)throw new C("missing message in ChatCompletion response");if(!x.tool_calls?.length){await p?.(h,n);return}if(l||r.parallel_tool_calls===!1)for(let S of x.tool_calls){let E=await A(S);if(E.message&&this._addMessage(E.message),l&&E.functionCalled){await p?.(h,n);return}}else{let S=await Promise.allSettled(x.tool_calls.map(A));for(let E of S)if(E.status==="rejected")throw E.reason;for(let E of S)E.status==="fulfilled"&&E.value.message&&this._addMessage(E.value.message)}await p?.(h,n)}}};fe=new WeakSet,_a=function(){return w(this,fe,"m",Is).call(this).content??null},Is=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Dr(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(Dr(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(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}},Aa=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},du=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.")},pu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var vo=class t extends jr{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),Dr(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},xa=class extends Error{},va=class extends Error{};function kf(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 Ef(t.trim(),e)}var Ef=(t,e)=>{let r=t.length,n=0,o=f=>{throw new xa(`${f} at position ${n}`)},s=f=>{throw new va(`${f} at position ${n}`)},i=()=>(p(),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,y=!1;for(n++;n<r&&(t[n]!=='"'||y&&t[n-1]==="\\");)y=t[n]==="\\"?!y:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(y)))}catch(b){s(String(b))}else if(se.STR&e)try{return JSON.parse(t.substring(f,n-Number(y))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,p();let f={};try{for(;t[n]!=="}";){if(p(),n>=r&&se.OBJ&e)return f;let y=a();p(),n++;try{let b=i();Object.defineProperty(f,y,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(se.OBJ&e)return f;throw b}p(),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()),p(),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(y){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(y))}}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(b){s(String(b))}}},p=()=>{for(;n<r&&`
|
|
47
|
+
\r `.includes(t[n]);)n++};return i()},Ia=t=>kf(t,se.ALL^se.NUM);var re,Ge,zr,yt,Ta,Ts,Sa,Ca,ka,Ss,Ea,mu,Ut=class t extends jr{constructor(e){super(),re.add(this),Ge.set(this,void 0),zr.set(this,void 0),yt.set(this,void 0),k(this,Ge,e,"f"),k(this,zr,[],"f")}get currentChatCompletionSnapshot(){return w(this,yt,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion,this._listenForAbort(n?.signal),w(this,re,"m",Ta).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)w(this,re,"m",Sa).call(this,s);if(o.controller.signal?.aborted)throw new V;return this._addChatCompletion(w(this,re,"m",Ss).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),w(this,re,"m",Ta).call(this),this._connected();let n=je.fromReadableStream(e,this.controller),o;for await(let s of n)o&&o!==s.id&&this._addChatCompletion(w(this,re,"m",Ss).call(this)),w(this,re,"m",Sa).call(this,s),o=s.id;if(n.controller.signal?.aborted)throw new V;return this._addChatCompletion(w(this,re,"m",Ss).call(this))}[(Ge=new WeakMap,zr=new WeakMap,yt=new WeakMap,re=new WeakSet,Ta=function(){this.ended||k(this,yt,void 0,"f")},Ts=function(r){let n=w(this,zr,"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},w(this,zr,"f")[r.index]=n,n)},Sa=function(r){if(this.ended)return;let n=w(this,re,"m",mu).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=w(this,re,"m",Ts).call(this,s);s.finish_reason&&(w(this,re,"m",ka).call(this,s),i.current_tool_call_index!=null&&w(this,re,"m",Ca).call(this,s,i.current_tool_call_index));for(let a of o.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(w(this,re,"m",ka).call(this,s),i.current_tool_call_index!=null&&w(this,re,"m",Ca).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))}}},Ca=function(r,n){if(w(this,re,"m",Ts).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=w(this,Ge,"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:zt(i)?i.$parseRaw(s.function.arguments):i?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},ka=function(r){let n=w(this,re,"m",Ts).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=w(this,re,"m",Ea).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}))},Ss=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=w(this,yt,"f");if(!r)throw new C("request ended without sending any chunks");return k(this,yt,void 0,"f"),k(this,zr,[],"f"),Of(r,w(this,Ge,"f"))},Ea=function(){let r=w(this,Ge,"f")?.response_format;return yo(r)?r:null},mu=function(r){var n,o,s,i;let a=w(this,yt,"f"),{choices:c,...l}=r;a?Object.assign(a,l):a=k(this,yt,{...l,choices:[]},"f");for(let{delta:u,finish_reason:p,index:f,logprobs:y=null,...b}of r.choices){let A=a.choices[f];if(A||(A=a.choices[f]={finish_reason:p,index:f,message:{},logprobs:y,...b}),y)if(!A.logprobs)A.logprobs=Object.assign({},y);else{let{content:M,refusal:z,...B}=y;Object.assign(A.logprobs,B),M&&((n=A.logprobs).content??(n.content=[]),A.logprobs.content.push(...M)),z&&((o=A.logprobs).refusal??(o.refusal=[]),A.logprobs.refusal.push(...z))}if(p&&(A.finish_reason=p,w(this,Ge,"f")&&ga(w(this,Ge,"f")))){if(p==="length")throw new Mr;if(p==="content_filter")throw new Rr}if(Object.assign(A,b),!u)continue;let{content:_,refusal:h,function_call:x,role:S,tool_calls:E,...q}=u;if(Object.assign(A.message,q),h&&(A.message.refusal=(A.message.refusal||"")+h),S&&(A.message.role=S),x&&(A.message.function_call?(x.name&&(A.message.function_call.name=x.name),x.arguments&&((s=A.message.function_call).arguments??(s.arguments=""),A.message.function_call.arguments+=x.arguments)):A.message.function_call=x),_&&(A.message.content=(A.message.content||"")+_,!A.message.refusal&&w(this,re,"m",Ea).call(this)&&(A.message.parsed=A.message.content.trim()?Ia(A.message.content):null)),E){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:M,id:z,type:B,function:ue,...Y}of E){let ee=(i=A.message.tool_calls)[M]??(i[M]={});Object.assign(ee,Y),z&&(ee.id=z),B&&(ee.type=B),ue&&(ee.function??(ee.function={name:ue.name??"",arguments:""})),ue?.name&&(ee.function.name=ue.name),ue?.arguments&&(ee.function.arguments+=ue.arguments,su(w(this,Ge,"f"),ee)&&(ee.function.parsed_arguments=Ia(ee.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 je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Of(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:p,logprobs:f,...y})=>{if(!u)throw new C(`missing finish_reason for choice ${p}`);let{content:b=null,function_call:A,tool_calls:_,...h}=l,x=l.role;if(!x)throw new C(`missing role for choice ${p}`);if(A){let{arguments:S,name:E}=A;if(S==null)throw new C(`missing function_call.arguments for choice ${p}`);if(!E)throw new C(`missing function_call.name for choice ${p}`);return{...y,message:{content:b,function_call:{arguments:S,name:E},role:x,refusal:l.refusal??null},finish_reason:u,index:p,logprobs:f}}return _?{...y,index:p,finish_reason:u,logprobs:f,message:{...h,role:x,content:b,refusal:l.refusal??null,tool_calls:_.map((S,E)=>{let{function:q,type:M,id:z,...B}=S,{arguments:ue,name:Y,...ee}=q||{};if(z==null)throw new C(`missing choices[${p}].tool_calls[${E}].id
|
|
48
|
+
${Cs(t)}`);if(M==null)throw new C(`missing choices[${p}].tool_calls[${E}].type
|
|
49
|
+
${Cs(t)}`);if(Y==null)throw new C(`missing choices[${p}].tool_calls[${E}].function.name
|
|
50
|
+
${Cs(t)}`);if(ue==null)throw new C(`missing choices[${p}].tool_calls[${E}].function.arguments
|
|
51
|
+
${Cs(t)}`);return{...B,id:z,type:M,function:{...ee,name:Y,arguments:ue}}})}}:{...y,message:{...h,content:b,role:x,refusal:l.refusal??null},finish_reason:u,index:p,logprobs:f}}),created:o,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return ou(c,e)}function Cs(t){return JSON.stringify(t)}var Io=class t extends Ut{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var Je=class extends g{constructor(){super(...arguments),this.messages=new jt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return au(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 Ut.createChatCompletion(this._client,e,r)}};Je.Messages=jt;var _t=class extends g{constructor(){super(...arguments),this.completions=new Je(this._client)}};_t.Completions=Je;var Ur=class extends g{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends g{list(e={},r){return this._client.getAPIList("/organization/audit_logs",F,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends g{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(m`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",F,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends g{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends g{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",F,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends g{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",X,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends g{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",F,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Gr=class extends g{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends g{create(e,r,n){return this._client.post(m`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(m`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/groups/${e}/roles`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(m`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends g{create(e,r,n){return this._client.post(m`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(m`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/groups/${e}/users`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(m`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var wt=class extends g{constructor(){super(...arguments),this.users=new Zr(this._client),this.roles=new Jr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",X,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};wt.Users=Zr;wt.Roles=Jr;var Qr=class extends g{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/api_keys`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends g{list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/certificates`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(m`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(m`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var en=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var tn=class extends g{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var rn=class extends g{listRateLimits(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/rate_limits`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var nn=class extends g{create(e,r,n){return this._client.post(m`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/projects/${e}/roles`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var on=class extends g{create(e,r,n){return this._client.post(m`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/service_accounts`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var sn=class extends g{create(e,r,n){return this._client.post(m`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/spend_alerts`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var an=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/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(m`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(m`/projects/${o}/groups/${e}/roles`,X,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(m`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends g{constructor(){super(...arguments),this.roles=new an(this._client)}create(e,r,n){return this._client.post(m`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(m`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/groups`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=an;var ln=class extends g{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/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(m`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(m`/projects/${o}/users/${e}/roles`,X,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(m`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Bt=class extends g{constructor(){super(...arguments),this.roles=new ln(this._client)}create(e,r,n){return this._client.post(m`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/users`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Bt.Roles=ln;var ie=class extends g{constructor(){super(...arguments),this.users=new Bt(this._client),this.serviceAccounts=new on(this._client),this.apiKeys=new Qr(this._client),this.rateLimits=new rn(this._client),this.modelPermissions=new tn(this._client),this.hostedToolPermissions=new en(this._client),this.groups=new qt(this._client),this.roles=new nn(this._client),this.dataRetention=new Xr(this._client),this.spendAlerts=new sn(this._client),this.certificates=new Yr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",F,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(m`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ie.Users=Bt;ie.ServiceAccounts=on;ie.APIKeys=Qr;ie.RateLimits=rn;ie.ModelPermissions=tn;ie.HostedToolPermissions=en;ie.Groups=qt;ie.Roles=nn;ie.DataRetention=Xr;ie.SpendAlerts=sn;ie.Certificates=Yr;var cn=class extends g{create(e,r,n){return this._client.post(m`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(m`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/users/${e}/roles`,X,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(m`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends g{constructor(){super(...arguments),this.roles=new cn(this._client)}retrieve(e,r){return this._client.get(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",F,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Kt.Roles=cn;var ae=class extends g{constructor(){super(...arguments),this.auditLogs=new qr(this._client),this.adminAPIKeys=new Ur(this._client),this.usage=new Gr(this._client),this.invites=new Wr(this._client),this.users=new Kt(this._client),this.groups=new wt(this._client),this.roles=new Hr(this._client),this.dataRetention=new Kr(this._client),this.spendAlerts=new Vr(this._client),this.certificates=new Br(this._client),this.projects=new ie(this._client)}};ae.AuditLogs=qr;ae.AdminAPIKeys=Ur;ae.Usage=Gr;ae.Invites=Wr;ae.Users=Kt;ae.Groups=wt;ae.Roles=Hr;ae.DataRetention=Kr;ae.SpendAlerts=Vr;ae.Certificates=Br;ae.Projects=ie;var bt=class extends g{constructor(){super(...arguments),this.organization=new ae(this._client)}};bt.Organization=ae;var fu=Symbol("brand.privateNullableHeaders");function*ih(t){if(!t)return;if(fu 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 ih(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{[fu]:!0,values:e,nulls:r}};var un=class extends g{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:T([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var dn=class extends g{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var pn=class extends g{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var ze=class extends g{constructor(){super(...arguments),this.transcriptions=new dn(this._client),this.translations=new pn(this._client),this.speech=new un(this._client)}};ze.Transcriptions=dn;ze.Translations=pn;ze.Speech=un;var Wt=class extends g{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",$,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var mn=class extends g{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/assistants/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",$,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var fn=class extends g{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var hn=class extends g{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var At=class extends g{constructor(){super(...arguments),this.sessions=new fn(this._client),this.transcriptionSessions=new hn(this._client)}};At.Sessions=fn;At.TranscriptionSessions=hn;var gn=class extends g{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var yn=class extends g{retrieve(e,r){return this._client.get(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",F,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(m`/chatkit/threads/${e}/items`,F,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var xt=class extends g{constructor(){super(...arguments),this.sessions=new gn(this._client),this.threads=new yn(this._client)}};xt.Sessions=gn;xt.Threads=yn;var _n=class extends g{create(e,r,n){return this._client.post(m`/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(m`/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(m`/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(m`/threads/${e}/messages`,$,{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(m`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var wn=class extends g{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(m`/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(m`/threads/${o}/runs/${e}/steps`,$,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var hu=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 Se=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,Vt,Oa,Ue,ks,Ce,Gt,bn,Ht,Ps,be,Es,Os,Co,To,So,gu,yu,_u,wu,bu,Au,xu,Ze=class extends gt{constructor(){super(...arguments),le.add(this),Oa.set(this,[]),Ue.set(this,{}),ks.set(this,{}),Ce.set(this,void 0),Gt.set(this,void 0),bn.set(this,void 0),Ht.set(this,void 0),Ps.set(this,void 0),be.set(this,void 0),Es.set(this,void 0),Os.set(this,void 0),Co.set(this,void 0)}[(Oa=new WeakMap,Ue=new WeakMap,ks=new WeakMap,Ce=new WeakMap,Gt=new WeakMap,bn=new WeakMap,Ht=new WeakMap,Ps=new WeakMap,be=new WeakMap,Es=new WeakMap,Os=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 Vt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=je.fromReadableStream(e,this.controller);for await(let o of n)w(this,le,"m",To).call(this,o);if(n.controller.signal?.aborted)throw new V;return this._addRun(w(this,le,"m",So).call(this))}toReadableStream(){return new je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Vt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},i=await e.submitToolOutputs(r,s,{...o,signal:this.controller.signal});this._connected();for await(let a of i)w(this,le,"m",To).call(this,a);if(i.controller.signal?.aborted)throw new V;return this._addRun(w(this,le,"m",So).call(this))}static createThreadAssistantStream(e,r,n){let o=new Vt;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 Vt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return w(this,Es,"f")}currentRun(){return w(this,Os,"f")}currentMessageSnapshot(){return w(this,Ce,"f")}currentRunStepSnapshot(){return w(this,Co,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,Ue,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,ks,"f"))}async finalRun(){if(await this.done(),!w(this,Gt,"f"))throw Error("Final run was not received.");return w(this,Gt,"f")}async _createThreadAssistantStream(e,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let i of s)w(this,le,"m",To).call(this,i);if(s.controller.signal?.aborted)throw new V;return this._addRun(w(this,le,"m",So).call(this))}async _createAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},i=await e.create(r,s,{...o,signal:this.controller.signal});this._connected();for await(let a of i)w(this,le,"m",To).call(this,a);if(i.controller.signal?.aborted)throw new V;return this._addRun(w(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)}};Vt=Ze,To=function(e){if(!this.ended)switch(k(this,Es,e,"f"),w(this,le,"m",_u).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":w(this,le,"m",xu).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":w(this,le,"m",yu).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":w(this,le,"m",gu).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(!w(this,Gt,"f"))throw Error("Final run has not been received");return w(this,Gt,"f")},gu=function(e){let[r,n]=w(this,le,"m",bu).call(this,e,w(this,Ce,"f"));k(this,Ce,r,"f"),w(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!=w(this,bn,"f")){if(w(this,Ht,"f"))switch(w(this,Ht,"f").type){case"text":this._emit("textDone",w(this,Ht,"f").text,w(this,Ce,"f"));break;case"image_file":this._emit("imageFileDone",w(this,Ht,"f").image_file,w(this,Ce,"f"));break}k(this,bn,o.index,"f")}k(this,Ht,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,bn,"f")!==void 0){let o=e.data.content[w(this,bn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,w(this,Ce,"f"));break;case"text":this._emit("textDone",o.text,w(this,Ce,"f"));break}}w(this,Ce,"f")&&this._emit("messageDone",e.data),k(this,Ce,void 0,"f")}},yu=function(e){let r=w(this,le,"m",wu).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==w(this,Ps,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(w(this,be,"f")&&this._emit("toolCallDone",w(this,be,"f")),k(this,Ps,s.index,"f"),k(this,be,r.step_details.tool_calls[s.index],"f"),w(this,be,"f")&&this._emit("toolCallCreated",w(this,be,"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"&&w(this,be,"f")&&(this._emit("toolCallDone",w(this,be,"f")),k(this,be,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},_u=function(e){w(this,Oa,"f").push(e),this._emit("event",e)},wu=function(e){switch(e.event){case"thread.run.step.created":return w(this,Ue,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=w(this,Ue,"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=Vt.accumulateDelta(r,n.delta);w(this,Ue,"f")[e.data.id]=o}return w(this,Ue,"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":w(this,Ue,"f")[e.data.id]=e.data;break}if(w(this,Ue,"f")[e.data.id])return w(this,Ue,"f")[e.data.id];throw new Error("No snapshot available")},bu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let i=r.content[s.index];r.content[s.index]=w(this,le,"m",Au).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")},Au=function(e,r){return Vt.accumulateDelta(r,e)},xu=function(e){switch(k(this,Os,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":k(this,Gt,e.data,"f"),w(this,be,"f")&&(this._emit("toolCallDone",w(this,be,"f")),k(this,be,void 0,"f"));break;case"thread.run.cancelling":break}};var Jt=class extends g{constructor(){super(...arguments),this.steps=new wn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(m`/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(m`/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(m`/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(m`/threads/${e}/runs`,$,{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(m`/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 Ze.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 De(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Ze.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(m`/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 Ze.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Jt.Steps=wn;var vt=class extends g{constructor(){super(...arguments),this.runs=new Jt(this._client),this.messages=new _n(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/threads/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ze.createThreadAssistantStream(e,this._client.beta.threads,r)}};vt.Runs=Jt;vt.Messages=_n;var ke=class extends g{constructor(){super(...arguments),this.realtime=new At(this._client),this.chatkit=new xt(this._client),this.assistants=new mn(this._client),this.threads=new vt(this._client)}};ke.Realtime=At;ke.ChatKit=xt;ke.Assistants=mn;ke.Threads=vt;var Zt=class extends g{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var An=class extends g{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(m`/containers/${o}/files/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Qt=class extends g{constructor(){super(...arguments),this.content=new An(this._client)}create(e,r,n){return this._client.post(m`/containers/${e}/files`,ht({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(m`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/containers/${e}/files`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(m`/containers/${o}/files/${e}`,{...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Qt.Content=An;var It=class extends g{constructor(){super(...arguments),this.files=new Qt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};It.Files=Qt;var xn=class extends g{create(e,r,n){let{include:o,...s}=r;return this._client.post(m`/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(m`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/conversations/${e}/items`,F,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(m`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var Tt=class extends g{constructor(){super(...arguments),this.items=new xn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};Tt.Items=xn;var Yt=class extends g{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&Q(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:(Q(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=hu(c)}),i)))}};var vn=class extends g{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(m`/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(m`/evals/${o}/runs/${e}/output_items`,$,{query:s,...n,__security:{bearerAuth:!0}})}};var Xt=class extends g{constructor(){super(...arguments),this.outputItems=new vn(this._client)}create(e,r,n){return this._client.post(m`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(m`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/evals/${e}/runs`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(m`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(m`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Xt.OutputItems=vn;var St=class extends g{constructor(){super(...arguments),this.runs=new Xt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};St.Runs=Xt;var er=class extends g{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(m`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait: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 De(r),i=await this.retrieve(e),Date.now()-s>n)throw new Ne({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var In=class extends g{};var Tn=class extends g{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var tr=class extends g{constructor(){super(...arguments),this.graders=new Tn(this._client)}};tr.Graders=Tn;var Sn=class extends g{create(e,r,n){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,F,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(m`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends g{constructor(){super(...arguments),this.permissions=new Sn(this._client)}};rr.Permissions=Sn;var Cn=class extends g{list(e,r={},n){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,$,{query:r,...n,__security:{bearerAuth:!0}})}};var nr=class extends g{constructor(){super(...arguments),this.checkpoints=new Cn(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",$,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,$,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};nr.Checkpoints=Cn;var Ee=class extends g{constructor(){super(...arguments),this.methods=new In(this._client),this.jobs=new nr(this._client),this.checkpoints=new rr(this._client),this.alpha=new tr(this._client)}};Ee.Methods=In;Ee.Jobs=nr;Ee.Checkpoints=rr;Ee.Alpha=tr;var kn=class extends g{};var Ct=class extends g{constructor(){super(...arguments),this.graderModels=new kn(this._client)}};Ct.GraderModels=kn;var or=class extends g{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var sr=class extends g{retrieve(e,r){return this._client.get(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var ir=class extends g{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var En=class extends g{accept(e,r,n){return this._client.post(m`/realtime/calls/${e}/accept`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(m`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(m`/realtime/calls/${e}/refer`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(m`/realtime/calls/${e}/reject`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var On=class extends g{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Qe=class extends g{constructor(){super(...arguments),this.clientSecrets=new On(this._client),this.calls=new En(this._client)}};Qe.ClientSecrets=On;Qe.Calls=En;function vu(t,e){if(!e||!Dh(e)){let r={...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(o=>({...o,parsed:null}))}:n)};return Iu(t,r)&&Ae(r),r}return Pa(t,e)}function Pa(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?zh(e,s):null};if(s.type==="message"){let i=s.content.map(a=>a.type==="output_text"?{...a,parsed:r?Lh(e,a.text):null}:a);return{...s,content:i}}return s}),o=Object.assign({},t,{output:n});return Iu(t,o)&&Ae(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let s of o.output)if(s.type==="message"){for(let i of s.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),o}function Lh(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Dh(t){return!!yo(t.text?.format)}function Fh(t){return t?.$brand==="auto-parseable-tool"}function jh(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function zh(t,e){let r=jh(t.tools??[],e.name);return{...e,...e,parsed_arguments:Fh(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Iu(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function Ae(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}function Su(t,e){if(!e){if(t.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Tu(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&Ae(e);break}case"response.output_item.done":{D(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&Ae(e);break}case"response.content_part.added":{let r=D(e,t.output_index),n=r.type,o=t.part;n==="message"&&o.type!=="reasoning_text"?(r.content.push(structuredClone(o)),o.type==="output_text"&&Ae(e)):n==="reasoning"&&o.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(o)));break}case"response.content_part.done":{let r=D(e,t.output_index),n=t.part;if(r.type==="message"&&n.type!=="reasoning_text")xe(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&Ae(e);else if(r.type==="reasoning"&&n.type==="reasoning_text"){let o=r.content;if(!o)throw new C(`missing content at index ${t.content_index}`);xe(o,t.content_index),o[t.content_index]=structuredClone(n)}break}case"response.output_text.delta":{let r=D(e,t.output_index);if(r.type==="message"){let n=xe(r.content,t.content_index);if(n.type!=="output_text")throw new C(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=D(e,t.output_index);if(r.type==="message"){let n=xe(r.content,t.content_index);if(n.type!=="output_text")throw new C(`expected content to be 'output_text', got ${n.type}`);n.text=t.text,Ae(e)}break}case"response.output_text.annotation.added":{let r=D(e,t.output_index);if(r.type==="message"){let n=xe(r.content,t.content_index);if(n.type!=="output_text")throw new C(`expected content to be 'output_text', got ${n.type}`);n.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=D(e,t.output_index);if(r.type==="message"){let n=xe(r.content,t.content_index);if(n.type!=="refusal")throw new C(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}break}case"response.refusal.done":{let r=D(e,t.output_index);if(r.type==="message"){let n=xe(r.content,t.content_index);if(n.type!=="refusal")throw new C(`expected content to be 'refusal', got ${n.type}`);n.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=D(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=D(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=D(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let n=xe(r.content,t.content_index);if(n.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.reasoning_text.done":{let r=D(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let n=xe(r.content,t.content_index);if(n.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${n.type}`);n.text=t.text}break}case"response.reasoning_summary_part.added":{let r=D(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=D(e,t.output_index);r.type==="reasoning"&&(xe(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=D(e,t.output_index);if(r.type==="reasoning"){let n=xe(r.summary,t.summary_index);n.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=D(e,t.output_index);if(r.type==="reasoning"){let n=xe(r.summary,t.summary_index);n.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=D(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=D(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=D(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=D(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=D(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=D(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=D(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=D(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=D(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=D(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=D(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=D(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=D(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=D(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=D(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=D(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=D(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=D(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=D(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=D(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=D(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=Tu(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:Uh(t)}return e}function Tu(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&Ae(e),e}function D(t,e){let r=t.output[e];if(!r)throw new C(`missing output at index ${e}`);return r}function xe(t,e){let r=t[e];if(!r)throw new C(`missing content at index ${e}`);return r}function Uh(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var ko,Ms,ar,Rs,Cu,ku,Eu,$s=class t extends gt{constructor(e){super(),ko.add(this),Ms.set(this,void 0),ar.set(this,void 0),Rs.set(this,void 0),k(this,Ms,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){this._listenForAbort(n?.signal),w(this,ko,"m",Cu).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let i of o)w(this,ko,"m",ku).call(this,i,s);if(o.controller.signal?.aborted)throw new V;return w(this,ko,"m",Eu).call(this)}[(Ms=new WeakMap,ar=new WeakMap,Rs=new WeakMap,ko=new WeakSet,Cu=function(){this.ended||k(this,ar,void 0,"f")},ku=function(r,n){if(this.ended)return;let o=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},s=Su(r,w(this,ar,"f"));switch(k(this,ar,s,"f"),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}},Eu=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=w(this,ar,"f");if(!r)throw new C("request ended without sending any events");k(this,ar,void 0,"f");let n=qh(r,w(this,Ms,"f"));return k(this,Rs,n,"f"),n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,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=w(this,Rs,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function qh(t,e){return vu(t,e)}var Pn=class extends g{list(e,r={},n){return this._client.getAPIList(m`/responses/${e}/input_items`,$,{query:r,...n,__security:{bearerAuth:!0}})}};var Mn=class extends g{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var qe=class extends g{constructor(){super(...arguments),this.inputItems=new Pn(this._client),this.inputTokens=new Mn(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"&&Ae(n),n))}retrieve(e,r={},n){return this._client.get(m`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&Ae(o),o))}delete(e,r){return this._client.delete(m`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Pa(n,e))}stream(e,r){return $s.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(m`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};qe.InputItems=Pn;qe.InputTokens=Mn;var Rn=class extends g{retrieve(e,r){return this._client.get(m`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var $n=class extends g{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(m`/skills/${o}/versions/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var lr=class extends g{constructor(){super(...arguments),this.content=new $n(this._client)}create(e,r={},n){return this._client.post(m`/skills/${e}/versions`,ht({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(m`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/skills/${e}/versions`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(m`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};lr.Content=$n;var Ye=class extends g{constructor(){super(...arguments),this.content=new Rn(this._client),this.versions=new lr(this._client)}create(e={},r){return this._client.post("/skills",ht({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Ye.Content=Rn;Ye.Versions=lr;var Nn=class extends g{create(e,r,n){return this._client.post(m`/uploads/${e}/parts`,me({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var kt=class extends g{constructor(){super(...arguments),this.parts=new Nn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(m`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};kt.Parts=Nn;var Ou=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 Ln=class extends g{create(e,r,n){return this._client.post(m`/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(m`/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(m`/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(m`/vector_stores/${o}/file_batches/${e}/files`,$,{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 De(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 y of f){let b=await a.files.create({file:y,purpose:"assistants"},o);l.push(b.id)}}let p=Array(i).fill(c).map(u);return await Ou(p),await this.createAndPoll(e,{file_ids:l})}};var Dn=class extends g{create(e,r,n){return this._client.post(m`/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(m`/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(m`/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(m`/vector_stores/${e}/files`,$,{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(m`/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 De(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(m`/vector_stores/${o}/files/${e}/content`,pe,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Xe=class extends g{constructor(){super(...arguments),this.files=new Dn(this._client),this.fileBatches=new Ln(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/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",$,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(m`/vector_stores/${e}/search`,pe,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};Xe.Files=Dn;Xe.FileBatches=Ln;var cr=class extends g{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",F,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(m`/videos/${e}/content`,{query:r,...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(m`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(m`/videos/${e}/remix`,ht({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Fn,Pu,Ns,ur=class extends g{constructor(){super(...arguments),Fn.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");w(this,Fn,"m",Pu).call(this,n);let s=T([r]).values,i=w(this,Fn,"m",Ns).call(this,s,"webhook-signature"),a=w(this,Fn,"m",Ns).call(this,s,"webhook-timestamp"),c=w(this,Fn,"m",Ns).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new Le("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>o)throw new Le("Webhook timestamp is too old");if(l>u+o)throw new Le("Webhook timestamp is too new");let p=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"),y=c?`${c}.${a}.${e}`:`${a}.${e}`,b=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let _=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",b,_,new TextEncoder().encode(y)))return}catch{continue}throw new Le("The given webhook signature does not match the expected signature")}};Fn=new WeakSet,Pu=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Ns=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Ru=Symbol.for("openai.node.providerDefinitions.v1"),$u=globalThis,Nu=$u[Ru],Lu=Nu??new WeakMap;Nu||Object.defineProperty($u,Ru,{value:Lu});function Du(t){let e=Lu.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Ma,Ra,Eo,Fu,Qh="workload-identity-auth",P=class{constructor(e={}){Ma.add(this),Eo.set(this,void 0),this.completions=new Zt(this),this.chat=new _t(this),this.embeddings=new Yt(this),this.files=new er(this),this.images=new or(this),this.audio=new ze(this),this.moderations=new ir(this),this.models=new sr(this),this.fineTuning=new Ee(this),this.graders=new Ct(this),this.vectorStores=new Xe(this),this.webhooks=new ur(this),this.beta=new ke(this),this.batches=new Wt(this),this.uploads=new kt(this),this.admin=new bt(this),this.responses=new qe(this),this.realtime=new Qe(this),this.conversations=new Tt(this),this.evals=new St(this),this.containers=new It(this),this.skills=new Ye(this),this.videos=new cr(this);let r=e.provider;if(r){let A=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(_=>e[_]!=null);if(A.length)throw new C(`The \`provider\` option cannot be used with ${A.map(_=>`\`${_}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=r?null:Se("OPENAI_BASE_URL"),apiKey:o=r?null:Se("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Se("OPENAI_ADMIN_KEY")??null,organization:i=r?null:Se("OPENAI_ORG_ID")??null,project:a=r?null:Se("OPENAI_PROJECT_ID")??null,webhookSecret:c=Se("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...u}=e,p=r?Du(r):void 0,f={apiKey:o,adminAPIKey:s,organization:i,project:a,webhookSecret:c,workloadIdentity:l,provider:r,...u,baseURL:p?.baseURL??(n||"https://api.openai.com/v1")};if(o&&l)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!o&&!s&&!l)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Mc())throw new C(`It looks like you're running in a browser-like environment.
|
|
52
|
+
|
|
53
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
54
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
55
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
56
|
+
|
|
57
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
58
|
+
|
|
59
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
60
|
+
`);this.baseURL=f.baseURL,this.timeout=f.timeout??Ra.DEFAULT_TIMEOUT,this.logger=f.logger??console;let y="warn";this.logLevel=y,this.logLevel=ca(f.logLevel,"ClientOptions.logLevel",this)??ca(Se("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??y,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??ls(),k(this,Eo,Nc,"f");let b=r?void 0:Se("OPENAI_CUSTOM_HEADERS");if(b){let A={};for(let _ of b.split(`
|
|
61
|
+
`)){let h=_.indexOf(":");h>=0&&(A[_.substring(0,h).trim()]=_.substring(h+1).trim())}f.defaultHeaders=T([A,f.defaultHeaders])}this._options=f,this._provider=p,l&&(this._workloadIdentityAuth=new hs(l,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=s,this.organization=i,this.project=a,this.webhookSecret=c}withOptions(e){let r=this._options.provider,n=e.provider??r,o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,n!==r&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return T([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return T([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return T([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return T([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Kc(e)}getUserAgent(){return`${this.constructor.name}/JS ${ft}`}defaultIdempotencyKey(){return`stainless-node-retry-${Zi()}`}makeStatusError(e,r,n,o){return H.generate(e,r,n,o)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof 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=!w(this,Ma,"m",Fu).call(this)&&n||this.baseURL,s=Tc(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){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Ft(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}),await this._provider?.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}`,p=Date.now();if(Q(this).debug(`[${l}] sending request`,He({retryOfRequestLogID:n,method:o.method,url:a,options:o,headers:i.headers})),o.signal?.aborted)throw new V;let f=o.__security??{bearerAuth:!0},y=new AbortController,b=await this.fetchWithAuth(a,i,c,y,f).catch(io),A=Date.now();if(b instanceof globalThis.Error){let x=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new V;let S=so(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(r)return Q(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${x}`),Q(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${x})`,He({retryOfRequestLogID:n,url:a,durationMs:A-p,message:b.message})),this.retryRequest(o,r,n??l);throw Q(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),Q(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,He({retryOfRequestLogID:n,url:a,durationMs:A-p,message:b.message})),b instanceof Lt||b instanceof ao?b:S?new Ne:new mt({message:Yh(b),cause:b})}let _=[...b.headers.entries()].filter(([x])=>x==="x-request-id").map(([x,S])=>", "+x+": "+JSON.stringify(S)).join(""),h=`[${l}${u}${_}] ${i.method} ${a} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${A-p}ms`;if(!b.ok){if(b.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await ta(b.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let x=await this.shouldRetry(b);if(r&&x){let B=`retrying, ${r} attempts remaining`;return await ta(b.body),Q(this).info(`${h} - ${B}`),Q(this).debug(`[${l}] response error (${B})`,He({retryOfRequestLogID:n,url:b.url,status:b.status,headers:b.headers,durationMs:A-p})),this.retryRequest(o,r,n??l,b.headers)}let S=x?"error; no more retries left":"error; not retryable";Q(this).info(`${h} - ${S}`);let E=await b.text().catch(B=>io(B).message),q=kc(E),M=q?void 0:E;throw Q(this).debug(`[${l}] response error (${S})`,He({retryOfRequestLogID:n,url:b.url,status:b.status,headers:b.headers,message:M,durationMs:Date.now()-p})),this.makeStatusError(b.status,q,M,b.headers)}return Q(this).info(h),Q(this).debug(`[${l}] response start`,He({retryOfRequestLogID:n,url:b.url,status:b.status,headers:b.headers,durationMs:A-p})),{response:b,options:o,controller:y,requestLogID:l,retryOfRequestLogID:n,startTime:p}}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 ${Qh}`){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,p={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(p.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,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 De(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&&Cc("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u,isStreamingBody:p}=this.buildBody({options:n});p&&(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))}:{},...Rc(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:n}=e;if(!r)return r===void 0&&"body"in e?{...w(this,Eo,"f").call(this,{body:r,headers:T([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=T([n]),s=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,i=!s&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&o.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||s?{bodyHeaders:void 0,body:r,isStreamingBody:!i}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:cs(r),isStreamingBody:!0}:typeof r=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{...w(this,Eo,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};Ra=P,Eo=new WeakMap,Ma=new WeakSet,Fu=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};P.OpenAI=Ra;P.DEFAULT_TIMEOUT=6e5;P.OpenAIError=C;P.APIError=H;P.APIConnectionError=mt;P.APIConnectionTimeoutError=Ne;P.APIUserAbortError=V;P.NotFoundError=Cr;P.ConflictError=kr;P.RateLimitError=Or;P.BadRequestError=Ir;P.AuthenticationError=Tr;P.InternalServerError=Pr;P.PermissionDeniedError=Sr;P.UnprocessableEntityError=Er;P.InvalidWebhookSignatureError=Le;P.toFile=ho;P.Completions=Zt;P.Chat=_t;P.Embeddings=Yt;P.Files=er;P.Images=or;P.Audio=ze;P.Moderations=ir;P.Models=sr;P.FineTuning=Ee;P.Graders=Ct;P.VectorStores=Xe;P.Webhooks=ur;P.Beta=ke;P.Batches=Wt;P.Uploads=kt;P.Admin=bt;P.Responses=qe;P.Realtime=Qe;P.Conversations=Tt;P.Evals=St;P.Containers=It;P.Skills=Ye;P.Videos=cr;function Yh(t){if(Xh(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 Xh(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 eg(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 ve(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Ne.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===V.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):eg(t)?e=Bl.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 Oe=t=>t();function et(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function tg(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 Ls(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var rg="LC_AUTOGENERATED";function dr(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),rg)}function tt(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 tg(t);default:throw new Error(`Unknown message type: ${e}`)}}function ju(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function rt(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 Na(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function zu(t){let e=Oe(()=>{if(Na(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Na(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 Uu(){let t=ql();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function nt(t,e=!1,r="1.0.0"){let n=zu(t),o=Uu(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function qu(t,e){let r;return Ar(t)?r=Ni(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function ng(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Bu(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(Ku(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
62
|
+
`)}function Ku(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}: ${Ds(o,e)},`):r.push(`${n}?: ${Ds(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
|
|
63
|
+
`)}function Ds(t,e){if(ng(t))return t.anyOf.map(r=>Ds(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Ku(t,e+2),"}"].join(`
|
|
64
|
+
`);case"array":return t.items?`${Ds(t.items,e)}[]`:"any[]";default:return""}}function Fs(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function jn(t){return"type"in t&&t.type!=="function"}function Wu(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 Hu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function pr(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function js(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Vu(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 Gu(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 Ju(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Zu(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 Qu(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 Yu(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 ed=Symbol("Let zodToJsonSchema decide on which parser to use"),Xu={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"},td=t=>typeof t=="string"?{...Xu,basePath:["#"],definitions:{},name:t}:{...Xu,basePath:["#"],definitions:{},...t};var Oo=t=>"_def"in t?t._def:t;function rd(t){if(!t)return!0;for(let e in t)return!1;return!0}var nd=t=>{let e=td(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])=>[Oo(o),{def:Oo(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function La(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function j(t,e,r,n,o){t[e]=r,La(t,e,n,o)}function od(){return{}}function sd(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=R(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&j(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&j(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(j(r,"minItems",t.exactLength.value,t.exactLength.message,e),j(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function id(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?j(r,"minimum",n.value,n.message,e):j(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?j(r,"maximum",n.value,n.message,e):j(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",n.value,n.message,e));break;case"multipleOf":j(r,"multipleOf",n.value,n.message,e);break}return r}function ad(){return{type:"boolean"}}function ld(t,e,r){return R(t.type._def,e,r)}var cd=(t,e,r)=>R(t.innerType._def,e,r);function Da(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Da(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 og(t,e)}}var og=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":j(r,"minimum",n.value,n.message,e);break;case"max":j(r,"maximum",n.value,n.message,e);break}return r};function ud(t,e,r){return{...R(t.innerType._def,e,r),default:t.defaultValue()}}function dd(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function pd(t){return{type:"string",enum:[...t.values]}}var sg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function md(t,e){let r=[R(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),R(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(sg(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 fd(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 Fa,mr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Fa===void 0&&(Fa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fa),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 zs(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?ig(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Pe(r,"email",o.message,e);break;case"format:idn-email":Pe(r,"idn-email",o.message,e);break;case"pattern:zod":Me(r,mr.email,o.message,e);break}break;case"url":Pe(r,"uri",o.message,e);break;case"uuid":Pe(r,"uuid",o.message,e);break;case"regex":Me(r,o.regex,o.message,e);break;case"cuid":Me(r,mr.cuid,o.message,e);break;case"cuid2":Me(r,mr.cuid2,o.message,e);break;case"startsWith":Me(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":Me(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Pe(r,"date-time",o.message,e);break;case"date":Pe(r,"date",o.message,e);break;case"time":Pe(r,"time",o.message,e);break;case"duration":Pe(r,"duration",o.message,e);break;case"length":j(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),j(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{Me(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Pe(r,"ipv4",o.message,e),o.version!=="v4"&&Pe(r,"ipv6",o.message,e);break}case"emoji":Me(r,mr.emoji,o.message,e);break;case"ulid":{Me(r,mr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Pe(r,"binary",o.message,e);break}case"contentEncoding:base64":{j(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Me(r,mr.base64,o.message,e);break}}break}case"nanoid":Me(r,mr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var ig=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Pe=(t,e,r,n)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):j(t,"format",e,r,n)},Me=(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:hd(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):j(t,"pattern",hd(e,n),r,n)},hd=(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
|
+
]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
|
|
66
|
+
]))`;continue}}if(n.s&&o[l]==="."){s+=a?`${o[l]}\r
|
|
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 Us(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(zs(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 gd(t,e){if(e.mapStrategy==="record")return Us(t,e);let r=R(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=R(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 yd(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 _d(){return{not:{}}}function wd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Po={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ad(t,e){if(e.target==="openApi3")return bd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Po&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Po[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 bd(t,e)}var bd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>R(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 xd(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Po[t.innerType._def.typeName],nullable:!0}:{type:[Po[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function vd(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",La(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?j(r,"minimum",n.value,n.message,e):j(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),j(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?j(r,"maximum",n.value,n.message,e):j(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),j(r,"maximum",n.value,n.message,e));break;case"multipleOf":j(r,"multipleOf",n.value,n.message,e);break}return r}function ag(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Id(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=R(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:ag(t,e)};return r.required.length||delete r.required,r}var Td=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return R(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Sd=(t,e,r)=>{if(e.pipeStrategy==="input")return R(t.in._def,e,r);if(e.pipeStrategy==="output")return R(t.out._def,e,r);let n=R(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=R(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Cd(t,e,r){return R(t.type._def,e,r)}function kd(t,e){let n={type:"array",uniqueItems:!0,items:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&j(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&j(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Ed(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:R(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Od(){return{not:{}}}function Pd(){return{}}var Md=(t,e,r)=>R(t.innerType._def,e,r);function R(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==ed)return s}if(n&&!r){let s=lg(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=dg(t,t.typeName,e,r);return s&&pg(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var lg=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((n,o)=>o===0?n:cg(n)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:ug(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Rd="_x_",cg=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Rd))return t;let e=Rd;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},ug=(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("/")},dg=(t,e,r,n)=>{switch(e){case N.ZodString:return zs(t,r);case N.ZodNumber:return vd(t,r);case N.ZodObject:return Id(t,r);case N.ZodBigInt:return id(t,r);case N.ZodBoolean:return ad();case N.ZodDate:return Da(t,r);case N.ZodUndefined:return Od();case N.ZodNull:return wd(r);case N.ZodArray:return sd(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return Ad(t,r);case N.ZodIntersection:return md(t,r);case N.ZodTuple:return Ed(t,r);case N.ZodRecord:return Us(t,r);case N.ZodLiteral:return fd(t,r);case N.ZodEnum:return pd(t);case N.ZodNativeEnum:return yd(t);case N.ZodNullable:return xd(t,r,n);case N.ZodOptional:return Td(t,r,n);case N.ZodMap:return gd(t,r);case N.ZodSet:return kd(t,r);case N.ZodLazy:return R(t.getter()._def,r,n);case N.ZodPromise:return Cd(t,r,n);case N.ZodNaN:case N.ZodNever:return _d();case N.ZodEffects:return dd(t,r,n);case N.ZodAny:return od();case N.ZodUnknown:return Pd();case N.ZodDefault:return ud(t,r,n);case N.ZodBranded:return ld(t,r,n);case N.ZodReadonly:return Md(t,r,n);case N.ZodCatch:return cd(t,r,n);case N.ZodPipeline:return Sd(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},pg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ja=(t,e)=>{let r=nd(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=R(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(rd(r.definitions))return;let c={},l=new Set;for(let u=0;u<500;u++){let p=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(p.length===0)break;for(let[f,y]of p)c[f]=R(Oo(y),{...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 $d(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return ot(e,[],e)}function za(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(za(e))return!0;for(let e of t.anyOf??[])if(za(e))return!0;return!1}function ot(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!fr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(fr(n))for(let[f,y]of Object.entries(n))ot(y,[...e,"$defs",f],r);let o=t.definitions;if(fr(o))for(let[f,y]of Object.entries(o))ot(y,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(fr(a)){for(let[f,y]of Object.entries(a))if(!za(y)&&!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,y])=>[f,ot(y,[...e,"properties",f],r)]))}let c=t.items;fr(c)&&(t.items=ot(c,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,y)=>ot(f,[...e,"anyOf",String(y)],r)));let u=t.allOf;if(Array.isArray(u))if(u.length===1){let f=ot(u[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=u.map((f,y)=>ot(f,[...e,"allOf",String(y)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&fg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=mg(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!fr(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,ot(t,e,r)}return t}function mg(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(!fr(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 fr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fg(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function hg(t,e){return ja(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function gg(t){return $d(Zl(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function yg(t){return"_zod"in t}function Nd(t,e,r){return nu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:yg(t)?gg(t):hg(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var Ld=["jsonSchema","functionCalling","jsonMode"];function Dd(t,e){if(typeof e<"u"&&!Ld.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Ld.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 _g(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Fd(t,e,r){if(Ql(t))return Nd(t,e,r);if(Zo(t))return _g({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:$t(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Gl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function jd(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 zd={"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 zn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var hr=class extends es{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_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??Te("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Te("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!et(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&&Rt(t.json_schema.schema)?Fd(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=rt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=nt(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return pr(t)?Yu(t.metadata.customTool):Yo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:qu(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(jn(n)||pr(n))return n;if(Wu(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return Ar(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(tt(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(p){console.error("Error parsing function arguments",p,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=Bu(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 ve(o)}})}get profile(){return zd[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=Dd(this.model,e?.method);if(a==="jsonMode"){n=Ri(o);let c=$t(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=$t(o),l={name:s??"extract",description:Pi(c),schema:Rt(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}}}),Rt(o)||Jo(o)){let u=Ri(o);n=dt.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:u.invoke(p.content))}else n=new ec}else{let c=s??"extract",l=$t(o),u;Rt(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=tc(o,c)}return rc(r,n,i)}};var qs={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=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=ki({dataUrl:t.url}),r=dr(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=dr(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Ua=({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(br(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 U({content:jd(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")}},qa=({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 ut({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 Wl({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new Ei({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Kl({content:s,role:o,response_metadata:a})},Ud=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=Hl(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=dr(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},qd=({message:t,model:e})=>{let r=tt(t);if(r==="system"&&et(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 U.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"&&K.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=Ud(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Un=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return qd({message:r});let n=tt(r);n==="system"&&et(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>Wo(i)?Ho(i,qs):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),U.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),K.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 Bs=class extends hr{constructor(t,e){super(zn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:Fs(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),et(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=Un({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let y of i){y.message.response_metadata={...y.generationInfo,...y.message.response_metadata};let b=y.generationInfo?.completion??0;a[b]===void 0?a[b]=y:a[b]=a[b].concat(y)}let c=Object.entries(a).sort(([y],[b])=>parseInt(y,10)-parseInt(b,10)).map(([y,b])=>b),{functions:l,function_call:u}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,u),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=p,n.output_tokens=f,n.total_tokens=p+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:p}=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}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let y of i?.choices??[]){let b={text:y.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(y.message??{role:"assistant"},i)};b.generationInfo={...y.finish_reason?{finish_reason:y.finish_reason}:{},...y.logprobs?{logprobs:y.logprobs}:{}},ct(b.message)&&(b.message.usage_metadata=n),b.message=new U(Object.fromEntries(Object.entries(b.message).filter(([A])=>!A.startsWith("lc_")))),f.push(b)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=Un({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=Un({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 p=this._convertCompletionsDeltaToBaseMessageChunk(u,c,s);s=u.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let y={...f};l.finish_reason!=null&&(y.finish_reason=l.finish_reason,y.system_fingerprint=c.system_fingerprint,y.model_name=c.model,y.service_tier=c.service_tier),this.logprobs&&(y.logprobs=l.logprobs);let b=new eo({message:p,text:p.content,generationInfo:y});yield b,await r?.handleLLMNewToken(b.text??"",f,void 0,void 0,void 0,{chunk:b})}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 ut({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 ve(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return qa({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Ua({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Ks="__openai_function_call_ids__",Ws="__openai_custom_tool_call_ids__";function Jd(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 bg(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 Mo=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}},Hs=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(Jd),...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(br(c,u))}i[Ks]??={},a.id&&(i[Ks][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=Vu(a);c?(r.push(c),i[Ws]??={},a.id&&a.call_id&&(i[Ws][a.call_id]=a.id)):n.push(br(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=Gu(a);c?r.push(c):n.push(br(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 U({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Mo(t.usage),additional_kwargs:i,response_metadata:s})},Zd=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}},Ba=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:[Jd(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[Ks]={[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[Ws]={[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=Hs(t.response);if(n=Mo(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,p)=>({...u,index:p})):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 ut({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},Qd=t=>{let e=U.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Oe(()=>{try{let h=tt(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,i=new Set,a=new Map,c=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let u=(h,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},p=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{let x=Oe(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:x,file_id:h.fileId};if(h.url)return{type:"input_image",detail:x,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},y=h=>{if(h.fileId){let x=Ls(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=Ls(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=dr(h),S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${S}`,filename:x}}},b=h=>{let x=Oe(()=>{if(Array.isArray(h.summary)){let E=h.summary?.map(q=>q?.text).filter(q=>typeof q=="string")??[];if(E.length>0)return E}return h.reasoning?[h.reasoning]:[]}),S=x.length>0?x.map(E=>({type:"summary_text",text:E})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:S}},A=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:p(h.args)}),_=h=>{let x=p(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:x,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let x=Oe(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});u([{type:"input_text",text:h.text}],x)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield b(h);else if(h.type==="tool_call"){yield*l();let x=h.id??"";x&&(s.add(x),a.delete(x)),yield A(h)}else if(h.type==="tool_call_chunk"){if(h.id){let x=a.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),a.set(h.id,x)}}else if(h.type==="server_tool_call"){yield*l();let x=h.id??"";x&&(i.add(x),c.delete(x)),yield A(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let x=c.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),c.set(h.id,x)}}else if(h.type==="server_tool_call_result")yield*l(),yield _(h);else if(h.type!=="audio")if(h.type==="file"){let x=y(h);x&&u([x])}else if(h.type==="image"){let x=f(h);x&&u([x])}else if(h.type==="video"){let x=y(h);x&&u([x])}else h.type==="text-plain"?h.text&&u([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,x]of a){if(!h||s.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}for(let[h,x]of c){if(!h||i.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}}return Array.from(r())},Ro=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Qd(n);let s=n.additional_kwargs,i=tt(n);if(i==="system"&&et(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 p=a.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id: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=Zd(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:Oe(()=>typeof u=="string"?u:u.flatMap(_=>{if(_.type==="text"){let h=_;return{type:"output_text",text:h.text,annotations:(h.annotations??[]).map(bg)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:Oe(()=>{if(Array.isArray(u))return u.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};a.push(A)}let p=s?.[Ks],f=s?.[Ws];U.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(A=>Zu(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}:Ju(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:p?.[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:p?.[A.id]}})));let y=o?.output?.length?o?.output:s.tool_outputs,b=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){let A=y?.filter(_=>b.includes(_.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=Ls(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:dr(l)}}return Ho(l,qs)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Oe(()=>{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:Oe(()=>{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*Ka(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,i=0,a=!1,c,l,u,p,f=new Set,y=(_,h)=>{let x=s.get(_);if(x!==void 0)return{index:x,isNew:!1};let S=i++;return s.set(_,S),o.set(S,{...h}),{index:S,isNew:!0}},b=function*(){a||(a=!0,yield{event:"message-start",id:c})},A=function*(_){if(f.has(_))return;let h=o.get(_);h&&(f.add(_),yield{event:"content-block-finish",index:_,content:nc(h)})};for await(let _ of t){if(_.type==="response.created"){c=_.response.id,yield*b(),yield{event:"provider",provider:n,name:"response.created",payload:{model:_.response.model,id:_.response.id}};continue}if(_.type==="response.output_text.delta"){yield*b();let{index:h,isNew:x}=y(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let S=o.get(h);S.text=(S.text??"")+_.delta,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*b();let{index:h,isNew:x}=y(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let S=o.get(h);S.reasoning=(S.reasoning??"")+_.delta,yield{event:"content-block-delta",index:h,delta:{type:"reasoning-delta",reasoning:_.delta}};continue}if(_.type==="response.output_item.added"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*b();let h=`tool:${_.output_index}`,x=_.item.type==="custom_tool_call",S=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:E,isNew:q}=y(h,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:S,index:_.output_index,...x?{isCustomTool:!0}:{}});if(q&&(yield{event:"content-block-start",index:E,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:S,index:_.output_index}}),S){let M=o.get(E);yield{event:"content-block-delta",index:E,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...M.id!=null?{id:M.id}:{},...M.name!=null?{name:M.name}:{},args:M.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*b();let{index:h,isNew:x}=y(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:h,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let S=o.get(h);S.args=(S.args??"")+_.delta,yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*b();let h=`tool:${_.output_index}`,x=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:S,isNew:E}=y(h,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:x,index:_.output_index});if(E)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:x,index:_.output_index}};else{let q=o.get(S);q.args=x,q.id=_.item.call_id,q.name=_.item.name}yield*A(S);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*b(),c=_.response.id,u=Ag(_.response.status,_.type),p={model_provider:n,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(l=Mo(_.response.usage),yield{event:"usage",usage:l});continue}_.type!=="response.image_generation_call.partial_image"&&(yield*b(),yield{event:"provider",provider:n,name:_.type,payload:_})}a||(yield{event:"message-start"});for(let[_]of o)f.has(_)||(yield*A(_));yield{event:"message-finish",reason:u,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function Ag(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Vs=class extends hr{constructor(t,e){super(zn(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:Hu(t?.tool_choice)?t?.tool_choice:(()=>{let o=Fs(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:Ro({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Hs(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:Ro({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Ka(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:Ro({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=Ba(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 ve(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 ve(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(jn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(pr(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 js(n)&&r.push(Qu(n));return r}};var Gs=class Yd extends hr{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=zn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Vs(n),this.completions=n?.completions??new Bs(n)}_useResponsesApi(e){let r=e?.tools?.some(jn),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(js)||e?.tools?.some(pr);return this.useResponsesApi||r||n||o||ju(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 Yd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Js=class extends Yl{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??Te("OPENAI_API_KEY");this.organization=e?.configuration?.organization??Te("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=rt({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=nt(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 ve(r)}})}};var Tg=I.object({type:I.literal("screenshot")}),Sg=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),Cg=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),kg=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),Eg=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),Og=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),Pg=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),Mg=I.object({type:I.literal("type"),text:I.string()}),Rg=I.object({type:I.literal("wait"),duration:I.number().optional()}),$g=I.union([Tg,Sg,Cg,kg,Eg,Og,Pg,Mg,Rg]),tK=I.object({action:$g});var Ng=I.object({type:I.literal("exec"),command:I.array(I.string()),env:I.record(I.string(),I.string()).optional(),working_directory:I.string().optional(),timeout_ms:I.number().optional(),user:I.string().optional()}),sK=I.union([Ng]);var cK=I.object({commands:I.array(I.string()).describe("Array of shell commands to execute"),timeout_ms:I.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:I.number().optional().describe("Optional maximum number of characters to return from each command")});var Lg=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),Dg=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),Fg=I.object({type:I.literal("delete_file"),path:I.string()}),mK=I.union([Lg,Dg,Fg]);var ep={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Ha={default:"text-embedding-ada-002"},Wa=new Map,Zs=null,qg=()=>{let t=Xd.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},tp=async t=>{let e=qg();Wa.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=>Wa.set(o.name,o))}catch(n){throw Zs=null,n}})()),await Zs);let r=Wa.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Bg=async(t="default")=>await tp(ep[t]),rp=async(t="default")=>await tp(Ha[t]),Bn=(t,e)=>e,np=(t,e)=>({...t,...e}),op=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
|
|
69
|
+
|
|
70
|
+
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
71
|
+
|
|
72
|
+
${r}`},sp=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Et=()=>({agentExecutionContext:O({reducer:np,default:sp}),outputMessage:O({reducer:op,default:()=>""}),summary:O({reducer:Bn,default:()=>""}),status:O({reducer:Bn})}),Va=()=>({...Et(),sharedStatePatch:O({reducer:Bn})}),Kg=O.Root({agentExecutionContext:O({default:sp,reducer:np}),currentIntent:O({default:()=>"none",reducer:Bn}),lastExecutedAgent:O({default:()=>"",reducer:Bn}),requiresFollowUp:O({default:()=>!0,reducer:Bn}),stepCount:O({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:O({default:()=>"",reducer:op})});var Wg=t=>typeof t=="string"&&t.length>0?t:void 0,Hg=()=>kl(),Vg=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Gg=t=>{let e=t?.configurable;return{conversationId:Wg(e?.thread_id),abortSignal:t?.signal,requestId:Hg(),requestSource:Vg(Ug.applicationName)}},ip=async({config:t})=>{let e=Xd.getDefault(),r=(await zg.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:i,requestId:a,requestSource:c}=Gg(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",c)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),a.length>0&&l.set("X-Esri-Request-Id",a);let u=i&&o?.signal?AbortSignal.any([i,o.signal]):o?.signal??i;return await fetch(n,{...o,headers:l,signal:u})}},Ga=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=ep[e],s=await Bg(e);return new Gs({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await ip({config:n})}})},ap=async(t={})=>{let{tier:e="default",config:r}=t,n=Ha[e],o=await rp(e);return new Js({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:await ip({config:r})},batchSize:2048,maxConcurrency:10})},Jg=I.object({id:I.string().min(1),name:I.string().min(1),description:I.string().min(1)});I.array(Jg);var lp="0.1",qn=1536,cp="openai",up=Ha.default,dp=`Name: {name}
|
|
73
|
+
Title: {title}
|
|
74
|
+
Description: {description}`,pp=`Name: {name}
|
|
75
|
+
Alias: {alias}
|
|
76
|
+
Description: {description}`,mp=I.object({schemaVersion:I.literal(lp),modified:I.number().int().nonnegative(),embeddings:I.object({modelProvider:I.literal(cp),model:I.literal(up),dimensions:I.literal(qn),templates:I.object({layer:I.string().default(dp),field:I.string().default(pp)})}),layers:I.array(I.object({id:I.string().min(1),name:I.string().min(1),title:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(qn,{message:`Layer vector must be exactly ${qn} dimensions`}),fields:I.array(I.object({name:I.string().min(1),alias:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(qn,{message:`Field vector must be exactly ${qn} dimensions`})}))})).default([])});var fp=(t,e)=>{let r=oc.fromTemplate(t);return sc.fromMessages([r,...e])},Zg=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=fp(e,o??[]),a=await Ga({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 Zg({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=fp(e,o??[]),l=(await Ga({modelTier:r,temperature:n,config:a})).withStructuredOutput(i);return await c.pipe(l).invoke(s??{},a)};var Qg=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),L2=d.object({fields:d.array(Qg)});var D2=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var hp=async t=>{try{return await(await ap()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var yp=t=>Array.isArray(t)&&t.every(Xn),Xg=t=>typeof t=="object"&&t!=null&&"messages"in t&&yp(t.messages),ey=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,st=class extends ic{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"||Mt(i)?i:new K({status:"success",name:n.name,content:typeof i=="string"?i:JSON.stringify(i),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||Ko(o))throw o;return new K({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(ey(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(yp(t))s=t;else if(Xg(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(ct(l)){a=l;break}}if(a==null||!ct(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(Mt))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Mt(s)?s.graph===We.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Ul(i))?o?o.goto.push(...s.goto):o=new We({graph:We.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var LW=O.Root({llmInputMessages:O({reducer:(t,e)=>to([],e),default:()=>[]})});var No=(t,e)=>e??t,Ny=O.Root({...Va(),intent:O({reducer:No}),vectorSearchLayerResults:O({reducer:No,default:()=>[]}),vectorSearchFieldResults:O({reducer:No}),navigationInternalState:O({reducer:No,default:()=>({toolCallMessage:void 0})})});async function Ly(t,e){let r=gr.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=`${Ja.assetsPath?.endsWith("/")?Ja.assetsPath:`${Ja.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await ny(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 oy({url:s,width:24,height:24}),c=new ry({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 Dy=["mapView"];function Be(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Dy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Fy({address:t},e){let{mapView:r}=Be(e);return await Ly(t,r)}var jy=d.object({address:d.string().describe("The full address or place name to locate.")}),zy=L(Fy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:jy});async function Uy(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 qy({bookmarkName:t},e){let{mapView:r}=Be(e);return await Promise.resolve(Uy(t,r))}var By=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),Ky=L(qy,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:By});async function Wy(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 Hy({layerId:t,where:e},r){let{mapView:n}=Be(r);return await Wy(t,e,n)}var Vy=I.object({layerId:I.string().describe("The layerId of the layer to zoom to."),where:I.string().describe("The sql-92 where clause used to query features to zoom to")}),Gy=L(Hy,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Vy});async function Jy(t){let e=new sy({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function Zy(t,e){let{mapView:r}=Be(e);return await Jy(r)}var Qy=I.object({}),Yy=L(Zy,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Qy});async function Xy(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 e_(t,e){let{mapView:r}=Be(e);return await Xy(r)}var t_=d.object({}),r_=L(e_,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:t_});async function n_(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 o_({layerId:t},e){let{mapView:r}=Be(e);return await n_(t,r)}var s_=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),i_=L(o_,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:s_});async function a_(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function l_({scale:t},e){let{mapView:r}=Be(e);return await a_(t,r)}var c_=d.object({scale:d.number().describe("The map scale of the view to go to.")}),u_=L(l_,{name:"goToScale",description:"Go to the specified view scale.",schema:c_});async function d_(t,e,r){let n={target:new Sp({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 p_({center:t,zoom:e,scale:r},n){let{mapView:o}=Be(n);return await d_(t,o,{zoom:e,scale:r})}var m_=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.")}),f_=L(p_,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:m_});async function h_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function g_({zoom:t},e){let{mapView:r}=Be(e);return await h_(t,r)}var y_=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),__=L(g_,{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:y_}),vp=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 it(t){let e=Object.entries(vp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
78
|
+
Available prompts:
|
|
79
|
+
${Object.keys(vp).join(`
|
|
80
|
+
`)}`);return await e[1]()}var Hn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function w_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=ay({basemapTheme:await bp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=ly({basemapTheme:await bp(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 b_(t){return await iy(t)}async function A_({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 w_(c),u=await b_(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 x_=["mapView"];function Re(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=x_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function v_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await A_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var I_=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)")}),T_=L(v_,{name:"chart",description:`Label: Charts
|
|
81
|
+
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
82
|
+
Keywords: pie, chart, all categories, breakdown, proportion
|
|
83
|
+
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
84
|
+
Fields: This style requires 2-8 number fields.
|
|
85
|
+
|
|
86
|
+
Label: Charts and Size
|
|
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
|
+
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
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:I_});function S_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,i=e[0],a;return s&&(a=sl({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 C_(t){return await cy(t)}async function k_({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=S_(c),u=await C_(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 E_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await k_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var O_=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")}),P_=L(E_,{name:"color-age",description:`Label: Age (color)
|
|
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
|
+
Keywords: since, age, how old, how long
|
|
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:O_});function M_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,i=e[1],a=e[0],c;return o&&(c=sl({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 R_(t){return await uy(t)}async function $_({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=M_(c),u=await R_(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 N_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await $_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var L_=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")}),D_=L(N_,{name:"color",description:`Label: Counts and Amounts (color)
|
|
95
|
+
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
96
|
+
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
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:L_});function F_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,i,a,c=e[0];return o&&(a=sl({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 j_(t){return await dy(t)}async function z_({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=F_(c),u=await j_(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 U_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await z_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var q_=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")}),B_=L(U_,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
99
|
+
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
100
|
+
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
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:q_});function K_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=my({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 W_(t){return await py(t)}async function H_({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=K_(a),l=await W_(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 V_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Re(n);return await ye({type:"show-legend",data:{layerIds:[t]}},n),await H_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var G_=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")}),J_=L(V_,{name:"dot-density",description:`Dot Density
|
|
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
|
+
**Use cases:**
|
|
105
|
+
- Population distribution visualization
|
|
106
|
+
- Comparing multiple categories within areas
|
|
107
|
+
- Showing spatial distribution patterns
|
|
108
|
+
**Examples:**
|
|
109
|
+
- Show the density of the population based on various race/ethnic groups
|
|
110
|
+
- Visualize distribution of different crops across regions
|
|
111
|
+
- Display demographic patterns within census tracts
|
|
112
|
+
**Fields:** Requires 2-8 number fields.
|
|
113
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:G_});function Z_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i=e[0];return o&&(s=hy({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:i,heatmapScheme:s}}async function Q_(t){return await fy(t)}async function Y_({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=Z_(a),l=await Q_(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 X_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Re(n);return await ye({type:"show-legend",data:{layerIds:[t]}},n),await Y_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var ew=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")}),tw=L(X_,{name:"heatmap",description:`Label: Heat Map
|
|
114
|
+
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
115
|
+
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
116
|
+
Example: Create a heatmap
|
|
117
|
+
Fields: This typically requires zero or one field of type number.`,schema:ew});function rw(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s&&(i=yy({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 nw(t){return await gy(t)}async function ow({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=rw(c),u=await nw(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 sw({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await ow({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var iw=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)")}),aw=L(sw,{name:"predominance",description:`Label: Predominant category
|
|
118
|
+
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
119
|
+
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
120
|
+
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
121
|
+
Fields: This style relies on 2-10 number fields.
|
|
122
|
+
|
|
123
|
+
Label: Predominant category and Size
|
|
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
|
+
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
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:iw});function lw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i={field:e[0]},a={field:e[1]};return o&&(s=wy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:i,field2:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function cw(t){return await _y(t)}async function uw({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=lw(a),l=await cw(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 dw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Re(n);return await ye({type:"show-legend",data:{layerIds:[t]}},n),await uw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var pw=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")}),mw=L(dw,{name:"relationship",description:`Label: Relationship
|
|
128
|
+
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
129
|
+
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
130
|
+
Example: Show the relationship between tree height and carbon storage
|
|
131
|
+
Fields: This style requires two number fields.`,schema:pw});function fw(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 hw(t){return await by(t)}async function gw({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=fw(c),u=await hw(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 yw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await gw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var _w=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")}),ww=L(yw,{name:"size-age",description:`Label: Age (size)
|
|
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
|
+
Keywords: since, age, how old, how long
|
|
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:_w});function bw(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 Aw(t){return await Ay(t)}async function xw({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=bw(c),u=await Aw(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 vw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await xw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Iw=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")}),Tw=L(vw,{name:"size",description:`Label: Counts and Amounts (size)
|
|
136
|
+
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
137
|
+
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
138
|
+
Example: Vary the size of each point based on the total population.
|
|
139
|
+
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.
|
|
140
|
+
|
|
141
|
+
Label: Continuous Timeline (size)
|
|
142
|
+
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
143
|
+
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
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:Iw});function Sw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],i=e[1],a=e[2],c;return o&&(c=vy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:i,field3:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Cw(t){return await xy(t)}async function kw({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=Sw(c),u=await Cw(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 Ew({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Re(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await kw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Ow=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")}),Pw=L(Ew,{name:"type",description:`Label: Types (unique symbols)
|
|
146
|
+
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
147
|
+
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
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:Ow}),Mw=O.Root({...Et(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),selectedLayerId:O()}),Rw=O.Root({...Et(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),queryResponse:O(),dataExplorationMessages:O({reducer:to,default:()=>[]})}),$w=["mapView"];function Ot(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=$w.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var Nw=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."},Lw=async(t,e)=>{let{mapView:r}=Ot(e);return Nw(r)},WH=L(Lw,{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({})}),Dw=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."},Fw=async(t,e)=>{let{mapView:r}=Ot(e);return await Dw(r)},HH=L(Fw,{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({})}),Ip=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 Sp({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:Ip+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Ip)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]:kp.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"}},jw=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)}}},zw=async(t,e,r,n,o,s)=>{let i=e.map?.allLayers.find(p=>p.id===t.layerId);if(!i)return`Could not find target layer with ID: ${t.layerId}`;let a;if(o){let p=await oi(o,e);if("error"in p)return p.error;a=p.geometry}if(i.featureEffect=null,i.featureEffect=new Iy({filter:new Cp({...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 jw(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}`},Uw=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Pt=d.enum(Uw),qw=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}=Ot(s);return await zw(t,i,n,o,e,r)},Bw=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:Pt.optional().describe("The units for the distance buffer.")}),Kw=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:Pt.optional().describe("The units for the distance buffer.")}),Ww=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([Bw,Kw]).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.")}),VH=L(qw,{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:Ww}),Qa=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},Hw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Vw=t=>{if(typeof t=="string"&&t)return t;let e=Qa(t);return e?e.toISOString().slice(0,10):null};var Gw=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=Vw(t);return s?Ty(s,Ys("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Sy(t,Ys("long-time"));let s=Qa(t);return s?Ap(s,{...Ys("long-time"),timeZone:"UTC"}):t}let o=Qa(t);return o?Ap(o,{...Ys("short-date-short-time"),timeZone:Hw(r)}):t},Op=(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},Jw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Zw=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},Qw=(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}},Yw=(t,e,r)=>{let n=Zw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=Jw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Pp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,Mp=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?Qw(r,s):s?.type==="date-time"?Yw(r,s,o):Gw(r,n,o)},Xw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Op(e,r,t)??r;return Mp(t,e,s,o?.type,n)},eb=(t,e)=>Pp(t,e),Rp=(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 p=Op(l.name,u,t)??u,f=Pp(t,l.name);c[f]=Mp(t,l.name,p,l.type,r)}),c});return{objectIds:o,attributes:s}},tb=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},rb=async(t,e,r,n)=>{let o=n.map?.allLayers.find(u=>u.id===t),s=tb(o,e,r.where),i=(await o.queryFeatures(s)).features[0],a=i?i.attributes[e]:null,c=Xw(o,e,a,n.timeZone),l=eb(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 nb({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Ot(n),s=await rb(t,e,r,o);return JSON.stringify(s,null,2)}var ob=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.")})}),sb=L(nb,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:ob}),il=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function ri(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var ib=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:i}=t,a=o.map?.allLayers.find(h=>h.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 p,f;if(i){let h=await oi(i,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw Lo(i)?new Error(`No features found matching: ${i.where}`):new Error("Failed to create geometry");if(Lo(i)){let x=o.map?.allLayers.find(S=>S.id===i.layerId);p={geometryLayerName:x?.title??x?.id,geometryLayerId:i.layerId,geometryWhere:i.where,distance:i.distance,units:i.units,applied:!0}}else ti(i)&&(p={point:i.point,distance:i.distance,units:i.units,applied:!0});f=new Cp({geometry:h.geometry,distance:i.distance,units:i.units,spatialRelationship:"intersects"})}let y=il(c,[r],!1),b=null,A=null,_=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:a,useFeaturesInView:y,view:y?o:void 0,field:r,sqlWhere:ri(a.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};b=await Cy(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(A=(await ky({layer:a,useFeaturesInView:y,view:y?o:void 0,field:r,sqlWhere:ri(a.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((E,q)=>q.count-E.count).slice(0,_)),A&&l.domain?.type==="coded-value"&&(A=A.map(E=>({...E,value:S?S.getName(E.value)??E.value:E.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:a.title??e.layerId,summary:`${n} = ${typeof b?.[n]=="number"?b[n]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:n,statistic:b?.[n]??null,summaryStatistics:b,uniqueValues:A,where:e.where,spatialFilterInfo:p}}};async function ab({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Hn(o,"layersAndFieldsRegistry"),{mapView:i}=Ot(o),a=await ib({targetLayer:t,fieldName:e,statisticType:r,mapView:i,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(a,null,2)}var lb=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:Pt.optional().describe("The units for the distance buffer.")}),cb=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:Pt.optional().describe("The units for the distance buffer.")}),ub=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([lb,cb]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),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.")}),db=L(ab,{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
|
+
|
|
151
|
+
USE THIS TOOL FOR:
|
|
152
|
+
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
153
|
+
- "Most common/frequent value of [field]?" \u2014 frequency analysis
|
|
154
|
+
- Questions requiring a mathematical aggregation across many features
|
|
155
|
+
|
|
156
|
+
DO NOT USE FOR:
|
|
157
|
+
- "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
|
|
158
|
+
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
159
|
+
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
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:ub}),pb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),mb=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,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])];try{let f;if(l){let A=new Ey({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Oy({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=p.length?p:["*"],A.orderByFields=e.orderByFields,A.returnGeometry=!1,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 _=[...new Set([...t.outFields,...pb(e.orderByFields)])],h=il(i,_,o??!1);try{f=h?await i.queryFeatures(A):await s.queryFeatures(A)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(A)}}let y=f.features.map(A=>A.attributes[u]),{attributes:b}=Rp(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:a,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:b,objectIds:y,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)}}}},fb=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Ot(o),i=await mb(t,e,s,r,n);return JSON.stringify(i,null,2)},hb=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:Pt.optional().describe("The units for the distance buffer.")}),gb=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:Pt.optional().describe("The units for the distance buffer.")}),yb=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([hb,gb]).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).")}),_b=L(fb,{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:yb}),Za=25,wb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),bb=async(t,e,r,n)=>{let o=e.map?.allLayers.find(_=>_.id===t.layerId),s=await e.whenLayerView(o),i=o.title??t.layerId,a;if(r){let _=await oi(r,e);if("error"in _){let h={error:_.error};if(Lo(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else ti(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"Geometry lookup failed",details:h}}if(!_.geometry){let h={};if(Lo(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else ti(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"No features found for geometry filter",details:h}}a=_.geometry}else n&&(a=e.extent.clone());let c=[...new Set([...t.outFields,...wb(t.orderByFields)])],l=il(s,c,n??!1),u=o.objectIdField,p=o.createQuery();p.where=ri(o.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])],p.orderByFields=t.orderByFields,a&&(p.geometry=a,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let f,y;try{f=l?await s.queryFeatureCount(p):await o.queryFeatureCount(p),f>0&&f<=Za&&(y=l?await s.queryFeatures(p):await o.queryFeatures(p))}catch(_){console.warn("Client-side query failed, falling back to server:",_),f=await o.queryFeatureCount(p),f>0&&f<=Za&&(y=await o.queryFeatures(p))}let{objectIds:b,attributes:A}=y?Rp(o,y,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:i,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...b&&{objectIds:b,objectIdField:u},...A&&{attributes:A},...f>Za&&{note:`${f} features found.`}}}};async function Ab({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Ot(n),s=await bb(t,o,e,r);return JSON.stringify(s,null,2)}var xb=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:Pt.optional().describe("The units for the distance buffer.")}),vb=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:Pt.optional().describe("The units for the distance buffer.")}),Ib=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([xb,vb]).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).")}),Tb=L(Ab,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
162
|
+
|
|
163
|
+
USE THIS TOOL FOR:
|
|
164
|
+
- "Show / display / list features where..." \u2014 finding and listing features
|
|
165
|
+
- "How many X are Y?" \u2014 counting features that match a condition
|
|
166
|
+
- "Which features..." / "Find features..." \u2014 identifying specific features
|
|
167
|
+
- Spatial queries \u2014 finding features near/within/intersecting other features
|
|
168
|
+
- Any question where the user wants to SEE or COUNT matching features
|
|
169
|
+
|
|
170
|
+
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Ib}),$p=[sb,db,_b,Tb];var GH=new st($p,{handleToolErrors:!1});var Sb=O.Root({...Et(),helpInternalState:O({reducer:No,default:()=>({toolCallMessage:void 0})})}),Cb=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(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
|
+
`);return`**${r.layerItem.title}** has ${n.length} field(s):
|
|
172
|
+
|
|
173
|
+
${o}`},kb=async({layerTitle:t},e)=>{let r=Hn(e,"layersAndFieldsRegistry");return Cb(r,t)},Eb=L(kb,{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.")})}),Ob=O.Root({...Et(),intent:O({reducer:(t,e)=>e}),arcgisKnowledgeMessages:O({reducer:to,default:()=>[]}),arcgisKnowledgeToolResult:O({reducer:(t,e)=>e,default:()=>null})});function Np(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function Vn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function si(t){!t||Vn(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)&&Np(r),{view:r}}async function Gn(t){let e=t?.configurable?.context;if(Pb(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 xp(n)}}else{Np(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await xp(n)}}}}function Pb(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 Ya=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(Xa.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Mb(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=Rb(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:$b(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}},Xa=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}},Mb=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Rb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function $b(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function ii(t){return t?.signal}async function Nb(t,e){let r=await it("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
|
|
175
|
+
|
|
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
|
+
|
|
178
|
+
Attempt Number: ${e.attemptCount}
|
|
179
|
+
Execution Error: ${e.executionError}
|
|
180
|
+
Failed Query:
|
|
181
|
+
${e.failedGraphQuery}`:`${t} ${r}`}async function Lb(t,e,r,n){let{graphQuery:o,explanation:s}=await al(t,e,r,n);return{graphQuery:o,explanation:s}}async function al(t,e,r,n,o){let s={message:await Nb(t,o),context:new Ya(e)},i=ii(n);await Z({text:"Attempting to generate a cypher query from your prompt..."},n);let a=await wp(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:_p.findCredential(gr.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,p="",f="",y=1;for(;!c;){await new Promise(A=>setTimeout(A,1e3)),await Z({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,y)}`},n),y=y%3+1;let b=await wp(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:a.data.conversationId,inquiryId:a.data.inquiryId,ackSequenceNumber:u}),headers:{"Content-Type":"application/json",token:_p.findCredential(gr.getDefault().url)?.token??""},signal:i});if(b.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${b.httpStatus}`,{cause:b.data});if(b.data.context?.kind){if(b.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${b.data.message}`,{cause:b.data});p=b.data.context.graphQuery,f=b.data.message||"",c=!0}else if(!b.data.hasMore)c=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");u=b.data.sequenceNumber}return{graphQuery:p,explanation:f}}function Db(t,e){Kn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Kn(t,e){if(!(!t||typeof t!="object")){if(jb(t))for(let r of t.path)Kn(r,e);else if(Fb(t))e(t);else if(Array.isArray(t))for(let r of t)Kn(r,e);else if(zb(t))for(let r of Object.values(t.properties??{}))Kn(r,e)}}function Fb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function jb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function zb(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Ub(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 qb(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[p]of u.members||[])c.push(p)}}return{allNamedTypesFullyDynamic:i,bindParameters:r,nonDynamicTypes:n}}var Wn=3;function Lp(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 Jn(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 Bb=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,p=()=>{l.abort(u?.reason)};u&&(u.aborted?l.abort(u.reason):u.addEventListener("abort",p,{once:!0}));try{let f=await My(t,e,o);a=f.resultHeader;let y=f.resultRowsStream.getReader(),b=0,A=Date.now(),_=!1;for(;;){let{done:h,value:x}=await y.read();if(h)break;if(!_&&i&&Date.now()-A>i)return l.abort(),{type:"timeout"};for(let S of x){if(b++,s&&b>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:Jn(f),error:f}}finally{u?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:a,processedResult:c}};async function Dp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c,config:l}){let u;for(let p=1;p<=Wn;p++){let f;try{f=await al(t,r.dataModel,n,l,u)}catch(A){return{type:"generation-error",errorMessage:Jn(A),error:A}}await Z({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let y=await Bb({kg:r,queryParams:new Ep({openCypherQuery:f.graphQuery,bindParameters:e}),targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c}),b=y.type==="aborted"?"Query execution was aborted.":y.type==="timeout"?"Query execution timed out.":y.type==="error"?`Query failed with error: ${y.errorMessage}`:"";if(y.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:y.rowLimitReached,resultHeader:y.resultHeader,processedResult:y.processedResult};if(y.type==="aborted")return{type:"aborted",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation};if(p>=Wn)return y.type==="timeout"?{type:"timeout",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:b,error:y.error,graphQuery:f.graphQuery,explanation:f.explanation};u={failedGraphQuery:f.graphQuery,executionError:b,attemptCount:p},await Z({text:`Attempt ${p} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Wn} attempts.`)}var Kb=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 p=(await Ry(t,new $y({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:u}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:y,value:b}=await p.read();if(y){f=!0;break}for(let A of b)for(let _ of A)i.push(_)}}}catch(l){let u=Jn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:u,error:l}:{type:"error",errorMessage:u,error:l}}return{type:"success",results:i}},Fp="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function jp({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(Fp),!Vn(e)){let u=await it("arcgis_knowledge_current_lc_context"),p=Ub(e.map,r);return o.push(u),{enhancedPrompt:o.join(`
|
|
182
|
+
|
|
183
|
+
`),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:i,bindParameters:a,nonDynamicTypes:c}=qb(s,r);if(i)return{enhancedPrompt:o.join(`
|
|
184
|
+
|
|
185
|
+
`),bindParameters:a,allNamedTypesFullyDynamic:!0};let l=(await it("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(c));return o.push(l),{enhancedPrompt:o.join(`
|
|
186
|
+
|
|
187
|
+
`),bindParameters:a,allNamedTypesFullyDynamic:i}}async function Wb(t,e,r,n,o,s){let{view:i}=o,a=await Dp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,y)=>{for(let b of y)Db(b,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,p=Array.from(u.values());return await Z({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),!Vn(i)&&i?.map?(await i.map.addRecords(p),await si(i),{generatedQuery:c,explanation:l,addedIdTypePairs:p}):(await i?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(p),{generatedQuery:c,explanation:l,addedIdTypePairs:p})}var Xs="addRecords",Hb=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.")}),Vb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Gn(e),n=Fo(e),{view:o}=n,s=gr.getDefault().helperServices,{enhancedPrompt:i,bindParameters:a,allNamedTypesFullyDynamic:c}=await jp({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:p}=await Wb(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
|
+
|
|
189
|
+
Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:u,addedIdTypePairs:p}}}catch(l){let u=Jn(l);return{toolName:Xs,status:"error",errorMessage:`Failed to add records to the link chart. ${u}`,error:l}}},Gb=L(Vb,{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
|
+
|
|
191
|
+
example prompts:
|
|
192
|
+
- "add all suppliers and the parts they produce to the link chart"
|
|
193
|
+
- "show me the competitors of company x and add them to the link chart"
|
|
194
|
+
- "add the relationships between company x and company y to the link chart"
|
|
195
|
+
- "expand all the companies"
|
|
196
|
+
- "expand company x through all the buildings it owns"
|
|
197
|
+
- "connect company x and company y"
|
|
198
|
+
- "connect all buildings on the link chart"
|
|
199
|
+
`,schema:Hb});async function Jb(t,e){return await e.map?.applyLayout(t),await si(e),{appliedLayout:t}}var el="applyLayout",Zb=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(Vn(r))return{toolName:el,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await Jb(t,r);return{toolName:el,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},Yb=L(Qb,{name:el,description:"Apply a diagram layout to the link chart",schema:Zb});async function Xb(t,e){return e.map?.changeNonspatialDataDisplay(t),await si(e),{appliedNonspatialDataDisplayMode:t}}var tl="changeNonspatialVisibility",eA=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),tA=async({setting:t},e)=>{let{view:r}=Fo(e);if(Vn(r))return{toolName:tl,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await Xb(t,r);return{toolName:tl,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},rA=L(tA,{name:tl,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:eA});async function nA(t,e,r,n,o){let s,i="";for(let a=1;a<=Wn;a++){let{graphQuery:c,explanation:l}=await al(t,e.dataModel,r,o,s);try{await Z({text:`Attempting to create link chart from derived query: ${c}`},o);let u=await Py.fromCypherQuery(e,new Ep({openCypherQuery:c}));await Z({text:"Link chart created successfully, loading..."},o),await u.load();let p=n.map;return n.map=u,await n.when(),await Tp.whenOnce(()=>!n.updating),u.entityCount===0&&u.relationshipCount===0?(n.map===u&&(n.map=p),u.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
|
|
200
|
+
${c}
|
|
201
|
+
|
|
202
|
+
Explanation: ${l}`}):(await si(n),{type:"success",graphQuery:c,explanation:l})}catch(u){let p=Jn(u);if(a>=Wn){i=p;break}s={failedGraphQuery:c,executionError:p,attemptCount:a},await Z({text:`Attempt ${a} to create link chart failed with error: ${p}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Wn} attempts. Last error: ${i}`}}var ei="createLinkChart",oA=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.")}),sA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Gn(e),{view:n}=Fo(e);if(Vn(n))return{toolName:ei,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=gr.getDefault().helperServices,s=await nA(`${t}
|
|
203
|
+
|
|
204
|
+
${Fp}`,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
|
+
${i}
|
|
206
|
+
|
|
207
|
+
Explanation: ${a}`,details:{generatedQuery:i,explanation:a}}}},iA=L(sA,{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:oA}),rl="queryGraphData",aA=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.")}),lA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Gn(e),n=gr.getDefault().helperServices,o=t,s=null,i=null;try{({view:i}=Fo(e))}catch{}i&&({enhancedPrompt:o,bindParameters:s}=await jp({prompt:t,view:i,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let a=await Dp({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(A,_)=>(A.push(_),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:rl,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:p}=a,f=p.headerKeys;for(let A of u)for(let _ of A)Kn(_,h=>Lp(h));let y=50,b=u.slice(0,y).map(A=>JSON.stringify(A));return{toolName:rl,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
208
|
+
|
|
209
|
+
\`\`\`cypher
|
|
210
|
+
${c}
|
|
211
|
+
\`\`\`
|
|
212
|
+
|
|
213
|
+
Query Results:
|
|
214
|
+
${b.length} result(s) found.
|
|
215
|
+
|
|
216
|
+
Column Headers: ${f.join(", ")}
|
|
217
|
+
|
|
218
|
+
${b.length>y?`Showing top ${y} results:
|
|
219
|
+
|
|
220
|
+
`:`Results:
|
|
221
|
+
|
|
222
|
+
`}${b.join(`
|
|
223
|
+
`)}
|
|
224
|
+
`,details:{generatedQuery:c,explanation:l,resultHeader:p,queryResults:u}}},cA=L(lA,{name:rl,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:aA}),nl="generateCypher",uA=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),dA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Gn(e),n=gr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await Lb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:nl,status:"success",summary:`Generated Graph Query:
|
|
225
|
+
${o}
|
|
226
|
+
|
|
227
|
+
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Jn(o);return{toolName:nl,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},pA=L(dA,{name:nl,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:uA}),mA=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(p=>u.add(p)),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
|
+
${n.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
|
|
229
|
+
`)}`,i=`Relationship Types:
|
|
230
|
+
${o.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
|
|
231
|
+
`)}`;return`${s}
|
|
232
|
+
|
|
233
|
+
${i}`};async function fA(t,e,r){let n=await it("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:mA(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 ol="searchGraphData",hA=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.")}),gA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Gn(e);await Z({text:"Generating search query for the user inquiry"},e);let n=await fA(t,r,e);await Z({text:"Executing graph search with generated search query"},e);let o=await Kb({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:ol,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let a of o.results)Kn(a,c=>Lp(c));let s=10,i=o.results.slice(0,s);return{toolName:ol,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
|
|
234
|
+
Query: ${n.query}
|
|
235
|
+
Type Category Filter: ${n.typeCategoryFilter}
|
|
236
|
+
Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
|
|
237
|
+
Result Limit: ${n.resultLimit??"No limit"}
|
|
238
|
+
|
|
239
|
+
Search Results: ${o.results.length} result(s) found.
|
|
240
|
+
|
|
241
|
+
${o.results.length>s?`Showing top ${s} results:
|
|
242
|
+
|
|
243
|
+
`:""}${i.map(a=>JSON.stringify(a)).join(`
|
|
244
|
+
`)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},yA=L(gA,{name:ol,description:`
|
|
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
|
+
Example prompts:
|
|
247
|
+
- "Find 'Bradley'"
|
|
248
|
+
- "find the person john smith"
|
|
249
|
+
- "find all people named smith"
|
|
250
|
+
- "Find all references to 'delayed parts shipment'"
|
|
251
|
+
- "Find all reports authored by someone with the title of 'Researcher'"
|
|
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:hA});var dV=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
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
|
+
|
|
256
|
+
Supported actions:
|
|
257
|
+
- **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
|
|
258
|
+
- **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
|
|
259
|
+
- **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
|
|
260
|
+
- **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
|
|
261
|
+
- **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
|
|
262
|
+
- **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
|
|
263
|
+
- **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
|
|
264
|
+
- **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
|
|
265
|
+
|
|
266
|
+
_Example: “Zoom to Texas”_
|
|
267
|
+
_Example: “Go to the water mains layer”_
|
|
268
|
+
_Example: “Zoom to to the extent of my link chart”_
|
|
269
|
+
_Example: “Center the map on San Francisco at scale 50000”_
|
|
270
|
+
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
271
|
+
_Example: “Go to the Downtown bookmark”_
|
|
272
|
+
_Example: “Where is Mount Rainier?”_`;var UV=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
|
|
273
|
+
_Example: “Color points by sales amount”_
|
|
274
|
+
_Example: “Show population density with a color gradient”_
|
|
275
|
+
_Example: “Create a relationship map between height and depth”_
|
|
276
|
+
_Example: “Vary circle sizes according to population”_`;var dG=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
|
|
277
|
+
The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
|
|
278
|
+
_Example: “Only show stations where Brand is Shell”_
|
|
279
|
+
_Example: “Make Shell stations stand out on the map”_
|
|
280
|
+
_Example: “Gray out all stations that aren’t Shell”_
|
|
281
|
+
This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
|
|
282
|
+
_Example: “How many features are there?”_
|
|
283
|
+
_Example: “What’s the average population?”_
|
|
284
|
+
_Example: “Which values are in the status field?”_
|
|
285
|
+
|
|
286
|
+
This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var kG=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
|
|
287
|
+
|
|
288
|
+
_Example: “Tell me about this map”_
|
|
289
|
+
_Example: “List all layers in this map”_
|
|
290
|
+
_Example: “List fields in protected areas layer”_
|
|
291
|
+
_Example: “What agents are available to me?”_
|
|
292
|
+
_Example: “What can you do?”_
|
|
293
|
+
_Example: “What can I ask”_
|
|
294
|
+
|
|
295
|
+
If the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent so it can politely refuse and redirect to map-related questions.
|
|
296
|
+
|
|
297
|
+
IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
|
|
298
|
+
_Example: "Create a chart"_
|
|
299
|
+
_Example: "Create a table"_`;var HG=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
|
|
300
|
+
This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
|
|
301
|
+
For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
|
|
302
|
+
expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
|
|
303
|
+
that exist out from specified entities and adding those to the link chart, changing whether or not nonspatial data is visible, or changing the layout of the link chart.
|
|
304
|
+
This agent is designed to handle requests that manipulate the specific link chart.
|
|
305
|
+
For knowledge graph data more generally, the agent can generate Open Cypher queries based on user prompts that represent inquiries into the data of the knowledge service and its graph database,
|
|
306
|
+
and can alternatively use those queries to create a new link chart visualization from the results if requested.
|
|
307
|
+
|
|
308
|
+
Supported actions:
|
|
309
|
+
- **Change or Apply Layout**: Changes the current layout visualization strategy of the link chart (e.g., "Change the layout to basic-grid", "Apply hierarchical layout"). Valid layout types include organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline. A best effort should be made to transform the user's request into one of these layout types.
|
|
310
|
+
- **Change Nonspatial Data Visibility**: Changes whether or not nonspatial data is visible on the link chart (e.g., "Show nonspatial data", "Hide nonspatial data"). Valid settings are "hidden" and "visible". A best effort should be made to transform the user's request into one of these settings.
|
|
311
|
+
- **Generate a cypher query**: 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. The user should explicitly request that a cypher query be returned - if they do not, the purpose of the query is for one of the other tools or skills.
|
|
312
|
+
- **Create a New Link Chart from a user prompt**: Identifies that the users prompt is an inquiry into the data of the knowledge service and its graph database and creates a new link chart from the results. The user should have requested that a link chart be created or made(or similar term) from their prompt
|
|
313
|
+
- **Add Records (entities or relationships)**: Identifies that the users prompt is an inquiry into the data of the knowledge graph service and its graph database, and that the user wants to take the result of the inquiry and add those entities and/or relationships to the link chart. The generated query should be syntactically correct and optimized for performance.
|
|
314
|
+
- **Search Graph Data**: Generates and runs a lucene syntax query based on the user's prompt, returning matching entity and relationship records from the knowledge graph.
|
|
315
|
+
- **Query Graph Data**: Generates and executes a cypher query based on the user's prompt, and displays the results in the chat pane, allowing the user to explore the data in their knowledge graph.
|
|
316
|
+
|
|
317
|
+
_example: "Change the layout to hierarchical-bottom-to-top"_
|
|
318
|
+
_example: "Apply radial-root-centric layout"_
|
|
319
|
+
_example: "Show nonspatial data"_
|
|
320
|
+
_example: "Hide nonspatial data"_
|
|
321
|
+
_example: "Turn off nonspatial visibility"_
|
|
322
|
+
_example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
|
|
323
|
+
_example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
|
|
324
|
+
_example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
|
|
325
|
+
_example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
|
|
326
|
+
_example: "Find all people who work for Microsoft and put them on a new link chart"_
|
|
327
|
+
_example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
|
|
328
|
+
_example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
|
|
329
|
+
_example: "Find all the products supplied by Supplier X and add them to my visualization"_
|
|
330
|
+
_example: "Expand the link chart from 'Entity D' to show its direct connections"_
|
|
331
|
+
_example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
|
|
332
|
+
_example: "Connect Emma and Rob on the link chart if there is a relationship between them"
|
|
333
|
+
_example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
|
|
334
|
+
_example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
|
|
335
|
+
_example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
|
|
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 bA=(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))},zp=Qs,at=$o;var $e=Z,Up=hp,qp=bA;var li=()=>Et();var cl={};Tl(cl,{JsonPatchError:()=>G,_areEquals:()=>qo,applyOperation:()=>yr,applyPatch:()=>Qn,applyReducer:()=>TA,deepClone:()=>vA,getValueByPointer:()=>mi,validate:()=>Kp,validator:()=>fi});var AA=(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)}})(),xA=Object.prototype.hasOwnProperty;function ui(t,e){return xA.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 Ke(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 Bp(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){AA(e,t);function e(r,n,o,s,i){var a=this.constructor,c=t.call(this,Bp(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=Bp(r,{name:n,index:o,operation:s,tree:i}),c}return e})(Error);var G=Uo,vA=ce,Zn={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=yr(r,{op:"remove",path:this.from}).removed;return yr(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=mi(r,this.from);return yr(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}}},IA={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:Zn.move,copy:Zn.copy,test:Zn.test,_get:Zn._get};function mi(t,e){if(e=="")return t;var r={op:"_get",path:e};return yr(t,r),r.value}function yr(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 G("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 G("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,p=c.length,f=void 0,y=void 0,b=void 0;for(typeof r=="function"?b=r:b=fi;;){if(y=c[u],y&&y.indexOf("~")!=-1&&(y=zo(y)),o&&(y=="__proto__"||y=="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[y]===void 0?f=c.slice(0,u).join("/"):u==p-1&&(f=e.path),f!==void 0&&b(e,0,t,f)),u++,Array.isArray(l)){if(y==="-")y=l.length;else{if(r&&!pi(y))throw new G("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(y)&&(y=~~y)}if(u>=p){if(r&&e.op==="add"&&y>l.length)throw new G("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=IA[e.op].call(e,l,y,t);if(i.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(u>=p){var i=Zn[e.op].call(e,l,y,t);if(i.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(l=l[y],r&&u<p&&(!l||typeof l!="object"))throw new G("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Qn(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new G("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]=yr(t,e[i],r,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function TA(t,e,r){var n=yr(t,e);if(n.test===!1)throw new G("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 G("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Zn[t.op]){if(typeof t.path!="string")throw new G("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new G('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 G("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 G("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 G("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 G("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 G("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=Kp([i],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new G("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Kp(t,e,r){try{if(!Array.isArray(t))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Qn(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 G)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 ml={};Tl(ml,{compare:()=>RA,generate:()=>ul,observe:()=>MA,unobserve:()=>PA});var dl=new WeakMap,SA=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),CA=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function kA(t){return dl.get(t)}function EA(t,e){return t.observers.get(e)}function OA(t,e){t.observers.delete(e.callback)}function PA(t,e){e.unobserve()}function MA(t,e){var r=[],n,o=kA(t);if(!o)o=new SA(t),dl.set(t,o);else{var s=EA(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(){ul(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(){ul(n),clearTimeout(n.next),OA(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 CA(e,n)),n}function ul(t,e){e===void 0&&(e=!1);var r=dl.get(t.object);pl(r.value,t.object,t.patches,"",e),t.patches.length&&Qn(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function pl(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],p=t[u];if(ui(e,u)&&!(e[u]===void 0&&p!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof p=="object"&&p!=null&&typeof f=="object"&&f!=null&&Array.isArray(p)===Array.isArray(f)?pl(p,f,r,n+"/"+Ke(u),o):p!==f&&(a=!0,o&&r.push({op:"test",path:n+"/"+Ke(u),value:ce(p)}),r.push({op:"replace",path:n+"/"+Ke(u),value:ce(f)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+Ke(u),value:ce(p)}),r.push({op:"remove",path:n+"/"+Ke(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+"/"+Ke(u),value:ce(e[u])})}}}function RA(t,e,r){r===void 0&&(r=!1);var n=[];return pl(t,e,n,"",r),n}var wJ=Object.assign({},cl,ml,{JsonPatchError:Uo,deepClone:ce,escapePathComponent:Ke,unescapePathComponent:zo});var LA=Sl`: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 Ie(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
|
|
339
|
+
Available prompts:
|
|
340
|
+
${Object.keys(t).join(`
|
|
341
|
+
`)}`);return await r[1]()}function wi(t){return t?.configurable?.context?.translations}function Vp(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 Gp(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var DA=I.object({needsContext:I.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:I.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),Wp=t=>t?.signal?.aborted??!1,Jp=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 FA(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 Zp(t){let e=(t??"").trim();if(!e)return"en";let r=e.split(/[-_]/)[0]?.toLowerCase();return r?r.slice(0,2):"en"}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 UA(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function Qp(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function gl(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 qA=t=>new Promise(e=>setTimeout(e,t));async function BA(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 Ie(Jp,"transformQuery"),i=await at({promptText:s,modelTier:"advanced",temperature:0,schema:DA,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 KA=O.Root({...li(),solutionResponse:O({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:O({reducer:(t,e)=>e??null,default:()=>null}),conversationId:O({reducer:(t,e)=>e??t,default:()=>null})}),WA=()=>new ge(KA).addNode("initializeAgent",VA).addNode("askSolutionsQuestions",HA).addEdge(he,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",W),Yp=async(t,e,r,n)=>{if(!t)return;let o=Qp(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:Zp(r),use_llm:!1}}}}};n&&(s.conversationId=n),gl(s,o,e??"")},HA=async(t,e)=>{if(Wp(e))return{};let r=wi(e),n=t.documentSkillUrl,o=[],s=await BA(t,e);await $e({text:r.agentProgress.explorerAgentSearching},e);let i=await gl({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:Zp(e?.configurable?.context?.configContext.locale),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 p=u.context?.results?.[0]?.reply??"";if(p!==""){let y=FA(p),b=jA(y),A=zA(b,e);c=A.source,o=[...o,...A.allMatches.filter(_=>!o.some(h=>h.solution.id===_.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let y="";f===1?y=r.agentProgress.explorerAgentReading:f===2?y=r.agentProgress.explorerAgentReviewing:f===3&&(y=r.agentProgress.explorerAgentPreparing),await $e({text:y},e)}};for(await l(i);a.hasMore;){if(Wp(e))return{};await qA(500),i=await gl({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 Qp(e?.configurable?.context.portal)&&Yp(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?Gp(o[0].solution.id):Vp(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},VA=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=UA(e.configurable.context.portal)),{documentSkillUrl:r}};await Ie(Jp,"solutions_explorer_description");var Xp=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"},GA=t=>{let e=Xp(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)}},JA=t=>Xp(t)==="human",ZA=(t,e=3)=>t.filter(r=>JA(r)).slice(-e).map(GA),QA=(t,e=" ")=>ZA(t).map(r=>r.content).join(e).trim(),YA={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?"},XA={builderMessages:YA},_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}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=os(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=ss(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=os(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=ss(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=os(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=ss(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(ac.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(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 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(!uc(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(cc.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}},ex=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.")}),tx=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.")}),Hp=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.")}),rx=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(Hp).describe("User/business fields specific to the solution."),requiredFields:d.array(Hp).describe("Fields required for solution functionality (e.g., relationship keys).")}),nx=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(rx)}),_l=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(ex).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:d.array(tx).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:nx.describe("Primary feature layer item and its schema/layers/tables details.")}),ox=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.")}),sx=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(ox).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),ix=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),ax=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.")}),lx=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),cx=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.")}),ux=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(cx).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),dx=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
|
|
342
|
+
`):"No validation errors were provided.",px=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await at({promptText:await Ie(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:ix,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:dx(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},wl=t=>t in xr,mx=5,fx=.8,hx=.5,gx="Web Mapping Application",yx="Embeddings",hi=null,hl=null,gi=null,yi=null,_x="Build",_r=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)}),wx=XA.builderMessages,J=t=>t?.signal?.aborted??!1,ne=(t,e,r)=>wi(e)?.builderMessages?.[t]??wx[t],em=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},bx=async(t,e,r)=>{if(!t)return null;let n=`type:"${gx}" AND typekeywords:${yx} AND group:${t}`;return(await Si({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function Ax(t,e,r,n){try{let o=await bx(t,e,r);if(!o||J(n))return null;let s=new NA({id:o.id});return await s.load(),J(n)?null:await s.fetchData("json")}catch{return null}}var xx=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${_x} AND group:${t}`;return(await Si({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},vx=async(t,e,r)=>{try{let n=await jl(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}},wr=(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},tm=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Li({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},bl=async t=>{if(hl){Object.entries(hl).forEach(([i,a])=>{xr[i]&&(xr[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=nm(t),n=om(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await xx(r,e,n),s={};J(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 vx(i.id,e,n);if(!l||J(t))return;let{buildSolution:u,params:p}=l;if(typeof u=="object"&&u!==null&&"solution"in u){let y=u.solution;y.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,y.item=i}let f={...a,buildSolution:u};s[c]=wr(new Li(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(u),params:p?structuredClone(p):null}),xr[c]={...a,initialTemplate:s[c]}})),hl=s)},rm=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},nm=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},om=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},Ix=async t=>{await Promise.all([im(t),bl(t)])},sm=async t=>{let e=rm(t);(!gi||e&&e!==yi)&&(yi=e??yi,gi=Ix(t).catch(r=>{throw gi=null,yi=null,r})),await gi};async function im(t){if(hi)return hi;let e=nm(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=om(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new $A(n?{url:n}:void 0).load(),J(t))return null;let o=rm(t)??void 0,s=await Ax(e,o,r,t);return J(t)?null:s?(hi=s.items,hi):null}var Tx=()=>Object.entries(xr).map(([t,e])=>`ID: ${t}
|
|
343
|
+
Label: ${e.label}
|
|
344
|
+
Description: ${e.description}`).join(`
|
|
345
|
+
|
|
346
|
+
`),Sx=t=>{let e=t?.configurable?.context?.solutionDesignJson;if(typeof e!="string"||!e.trim())return null;try{let r=JSON.parse(e),n=wr({response:"",...r},{itemId:r?.solution?.itemId??null}),o=_l.safeParse(n);if(!o.success)return null;let{response:s,...i}=o.data,a=r.templateId,c=typeof a=="string"&&wl(a)?a:null;return wr(i,{sourceBuildSolution:r.sourceBuildSolution,templateId:c,params:r.params??null})}catch{return null}},Cx=O.Root({...li(),templateDescription:O({reducer:(t,e)=>typeof e=="string"||e===null?e:t??null,default:()=>null}),currentDesign:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),assessment:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),selectedTemplate:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),updateAssessment:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),existingMatches:O({reducer:(t=[],e)=>e===void 0?t:e??[],default:()=>[]}),continueBuilding:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null})}),kx=(t,e)=>{if(J(e))return{};let r=Sx(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},Ex=async(t,e)=>{if(J(e))return{};await $e({text:ne("understandingRequest",e)},e),await sm(e);let r=t.agentExecutionContext.userRequest,n=Tx(),o=t.agentExecutionContext.messages.slice(-11),s=await at({promptText:await Ie(_r,"assessBuildRequest"),modelTier:"advanced",temperature:0,schema:ux,messages:o,inputVariables:{query:r,availableTemplates:n}}),i=s.matchedTemplates.filter(p=>wl(p.templateId)),a={...s,matchedTemplates:i},[c,l]=i,u=c&&c.confidence>=fx&&(l===void 0||c.confidence-l.confidence>=hx)?c.templateId:null;return{assessment:a,selectedTemplate:u,existingMatches:[],continueBuilding:null}},Ox=t=>{let e=t.assessment?.assistantResponse??"";return{outputMessage:e,summary:e,status:"success"}},Px=async(t,e)=>{if(J(e))return{};let{currentDesign:r}=t;if(!r)return{updateAssessment:{assistantResponse:"",isValidUpdate:!0}};await $e({text:ne("understandingRequest",e)},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);return{updateAssessment:await at({promptText:await Ie(_r,"assessUpdateRequest"),modelTier:"advanced",temperature:0,schema:ax,messages:o,inputVariables:{currentDesign:JSON.stringify(Fi(r)),query:n}})}},Mx=(t,e)=>{let r=t.updateAssessment?.assistantResponse??ne("applyChangeFailed",e);return{outputMessage:r,summary:r,status:"success"}},Rx=(t,e)=>{if(J(e))return{};let{hitlResponse:r}=e.configurable,n="selectTemplate",o=t.assessment?.matchedTemplates.filter(c=>wl(c.templateId))??[],s=o.map(c=>`${c.templateDescription}`);if(r?.agentId!=="solutionBuilder"||r.id!==n){let c={agentId:"solutionBuilder",id:n,kind:"singleSelection",message:ne("selectTemplatePrompt",e),metadata:[...s]};throw new Bo(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}},$x=async(t,e)=>{if(J(e))return{};await $e({text:ne("searchingExistingSolutions",e)},e);let r=t.agentExecutionContext.userRequest,n=QA(t.agentExecutionContext.messages)||r,o=await im(e);if(J(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 Up([n]);if(J(e))return{};let i=o.map(u=>({solution:u,score:qp(s,u.embedding)}));i.sort((u,p)=>p.score-u.score);let a=i.slice(0,mx);if(!a.length)return{existingMatches:[]};let c=a.map(({solution:u})=>`${u.title}
|
|
347
|
+
Snippet: ${u.snippet}
|
|
348
|
+
Description: ${u.description}`).join(`
|
|
349
|
+
|
|
350
|
+
`),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await at({promptText:await Ie(_r,"findExistingSolution"),modelTier:"fast",temperature:0,schema:lx,messages:l,inputVariables:{query:r,candidates:c}})).matchedTitles.map(u=>a.find(({solution:p})=>p.title===u)).filter(u=>u!==void 0)}},Nx=(t,e)=>{if(J(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?Gp(r[0].solution.id):Vp(r);let a=ne("existingSolutionMatch",e),c=[ne("continueBuildingYes",e),ne("continueBuildingNo",e)],l={agentId:"solutionBuilder",id:o,kind:"singleSelection",message:a,metadata:c};throw new Bo(l)}let s=String(n.payload??"").trim(),i=ne("continueBuildingNo",e);return{continueBuilding:s!==i}},Lx=(t,e)=>{let r=ne("continueBuildingDeclined",e);return{outputMessage:r,summary:r,status:"success"}},am=async(t,e)=>{if(J(e))return{};if(await sm(e),J(e))return{};let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await $e({text:ne("creatingDesign",e)},e);let o=ro(t.selectedTemplate);if(o?.initialTemplate||(await bl(e),o=ro(t.selectedTemplate)),J(e))return{};if(!o?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let s=wr(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 at({promptText:await Ie(_r,"designSolution"),modelTier:"advanced",temperature:0,schema:_l,messages:i,inputVariables:{currentDesign:JSON.stringify(Di(s)),templateInstructions:o.instructions,query:n}});if(await $e({text:" of design solution 1"},e),J(e))return{};let{response:c,featureLayer:l,...u}=a,p=ji(l,s.featureLayer),f=wr({...u,featureLayer:p},{itemId:s?.solution?.itemId,sourceBuildSolution:s.sourceBuildSolution,templateId:t.selectedTemplate??null,params:s.params??null}),y=new _i(f,o.initialTemplate);if(!y.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:y.issues,llmResponse:a}),{outputMessage:ne("createDesignFailed",e)};let b=f.sourceBuildSolution,A=tm(f,b);if(!A.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:A.error,llmResponse:a,design:f});let _=ne("createDesignFailed",e);return{outputMessage:_,summary:_,status:"success"}}return J(e)?{}:(em(f),{outputMessage:c,summary:c,status:"success",currentDesign:f})},Dx=async(t,e)=>{if(J(e))return{};let{currentDesign:r}=t;if(!r)return am(t,e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);await $e({text:ne("updatingDesign",e)},e);let s;try{s=await at({promptText:await Ie(_r,"updateDesign"),modelTier:"advanced",temperature:0,schema:sx,messages:o,inputVariables:{currentDesign:JSON.stringify(Fi(r)),query:n}})}catch(M){console.warn("[SolutionBuilder] updateDesign structured prompt failed:",M);let z=ne("applyChangeFailed",e);return{outputMessage:z,summary:z,status:"success"}}let{response:i,patches:a}=s;if(!a||a.length===0)return{outputMessage:i,summary:i,status:"success"};let c=M=>{try{return JSON.parse(M)}catch{let z=M.replace(/[\u0000-\u001F]/g,B=>{switch(B){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
351
|
+
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+B.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(z)}catch{return M}}},l=[...a.map(M=>({op:M.op,path:M.path.replace(/\/+$/,""),...M.value!=null&&M.value!==""?{value:c(M.value)}:{},...M.from!=null&&M.from!==""?{from:M.from}:{}}))].sort((M,z)=>M.op!=="remove"||z.op!=="remove"?0:z.path.localeCompare(M.path,void 0,{numeric:!0})),u=structuredClone(Di(r));try{Qn(u,l,!0)}catch(M){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:M,llmResponse:s,patches:l,patchTarget:u});let z=ne("applyChangeFailed",e);return{outputMessage:z,summary:z,status:"success"}}let p=wr({response:"",...u},{itemId:r.solution?.itemId??null}),f=_l.safeParse(p);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:p});let M=ne("applyChangeFailed",e);return{outputMessage:M,summary:M,status:"success"}}let{response:y,featureLayer:b,...A}=f.data,_=ji(b,r.featureLayer),h=wr({...A,featureLayer:_},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),x=ro(t.selectedTemplate);if(x?.initialTemplate||(await bl(e),x=ro(t.selectedTemplate)),J(e))return{};if(!x?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let S=new _i(h,x.initialTemplate,!1);if(!S.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:S.issues,llmResponse:s,patchedDesign:h});let M=await px({query:n,validationIssues:S.issues,recentMessages:o,fallbackMessage:ne("applyChangeFailed",e),promptModules:_r});return{outputMessage:M,summary:M,status:"success"}}let E=h.sourceBuildSolution,q=tm(h,E);if(!q.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:q.error,llmResponse:s,design:h});let M=ne("applyChangeFailed",e);return{outputMessage:M,summary:M,status:"success"}}return J(e)?{}:(em(h),{outputMessage:i,summary:i,status:"success",currentDesign:h})},Fx=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",Ux=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",qx=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",Bx=()=>new ge(Cx).addNode("syncCurrentDesignFromContext",kx).addNode("assessBuildRequest",Ex).addNode("assessUpdateRequest",Px).addNode("invalidBuildExit",Ox).addNode("invalidUpdateExit",Mx).addNode("selectTemplateHIL",Rx).addNode("findExistingSolutions",$x).addNode("confirmContinueBuildingHIL",Nx).addNode("declineContinueBuildingExit",Lx).addNode("designSolution",am).addNode("updateDesign",Dx).addEdge(he,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",Fx,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",jx,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",zx,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",W).addEdge("invalidUpdateExit",W).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Ux,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",qx,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",W).addEdge("designSolution",W).addEdge("updateDesign",W);await Ie(_r,"description");var Kx=I.object({tool:I.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:I.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:I.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),bi=t=>t?.signal?.aborted??!1,Al=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)}),Wx=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}},xl=(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)},lm=O.Root({...li(),selectedTool:O({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:O({reducer:(t,e)=>e??null,default:()=>null})}),Hx=async(t,e)=>{if(bi(e))return{};let r=wi(e);await $e({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=Wx(e),a=await Ie(Al,"classifyIntent"),c=await at({promptText:a,modelTier:"advanced",temperature:0,schema:Kx,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},Vx=async(t,e)=>{if(bi(e))return{};let r=await WA().compile().invoke(t,e);return xl(e,"explorer"),r},Gx=async(t,e)=>{if(bi(e))return{};let r=await Bx().compile().invoke(t,e);return xl(e,"builder"),r},Jx=async(t,e)=>{if(bi(e))return{};let r=wi(e),n=t.agentExecutionContext.userRequest;await $e({text:r?.executingSolutionsAssistantAgent},e);let o=await Ie(Al,"assistantResponse"),s=t.agentExecutionContext.messages.slice(-11),i=await zp({promptText:o,modelTier:"advanced",temperature:0,messages:s,inputVariables:{query:n}});return xl(e,"assistant"),{outputMessage:i,summary:i,status:"success"}},Zx=t=>t.selectedTool??"other",Qx=()=>new ge(lm).addNode("classifyIntent",Hx).addNode("routeToExplorer",Vx).addNode("routeToBuilder",Gx).addNode("assistantResponse",Jx).addEdge(he,"classifyIntent").addConditionalEdges("classifyIntent",Zx,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",W).addEdge("routeToBuilder",W).addEdge("assistantResponse",W),Yx=await Ie(Al,"description"),Xx={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:Yx,createGraph:Qx,workspace:lm},ev="https://links.esri.com/solutions/agol-organizational-account",tv="https://links.esri.com/solutions/configure-assistants",yl=class extends $l{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=Ll({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=Ml(),this._configContextConsumer=Ti({context:Dl,subscribe:!0,callback:e=>{e?.portalURL&&(fl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Ti({context:Fl,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=zl(this._chatStartTime);this._telemetry?.logEvent({category:Yn.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=LA}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(){fl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(fl.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||(Yp(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 lt`<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 lt`<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">${dc(this._translations.noPermissionMessage.replace("{{orgUrl}}",ev).replace("{{configAI}}",tv))}</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)]),lt`<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?lt`${!this._isMobile&<`<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:Yn.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&<`<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)}} ${Rl(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:Yn.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=${Xx} .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&<`<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:Yn.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,p)=>p.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)}};Nl("arcgis-solutions-assistant",yl);return yl},"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","portal/Portal","portal/PortalItem",a,b)
|