@arcgis/portal-components 6.0.0-next.41 → 6.0.0-next.42

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.
Files changed (37) hide show
  1. package/dist/cdn/{ONRTCGLU.js → 24JMI26O.js} +1 -1
  2. package/dist/cdn/55C6QNU6.js +63 -0
  3. package/dist/cdn/7LTDWHLV.js +16 -0
  4. package/dist/cdn/BCCFB3DG.js +18 -0
  5. package/dist/cdn/{RX64JXHI.js → EP2IQ53W.js} +29 -29
  6. package/dist/cdn/{BX7Q3V2Y.js → FIYYZIGB.js} +2 -2
  7. package/dist/cdn/HFPMMGTC.js +2 -0
  8. package/dist/cdn/HLERJBHM.js +119 -0
  9. package/dist/cdn/JVMGFTLZ.js +106 -0
  10. package/dist/cdn/KPGUIUD7.js +2 -0
  11. package/dist/cdn/{3HZI6MKD.js → QBJZCFZW.js} +1 -1
  12. package/dist/cdn/SCIZKRKA.js +93 -0
  13. package/dist/cdn/UK7WZMZ4.js +3 -0
  14. package/dist/cdn/{Y7ZCEONL.js → YZZQ3Y6G.js} +1 -1
  15. package/dist/cdn/index.js +1 -1
  16. package/dist/chunks/contextUsage.js +25 -16
  17. package/dist/components/arcgis-portal-ai-assistant/customElement.js +243 -247
  18. package/dist/components/arcgis-portal-ai-assistant-diagnostics/contextUsage.d.ts +8 -0
  19. package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.d.ts +3 -2
  20. package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.js +194 -30
  21. package/dist/components/arcgis-portal-ai-assistant-diagnostics/index.js +5 -2
  22. package/dist/components/arcgis-portal-navigation/index.js +4 -4
  23. package/dist/docs/api.json +1 -1
  24. package/dist/docs/docs.json +1 -1
  25. package/dist/docs/vscode.html-custom-data.json +1 -1
  26. package/dist/docs/web-types.json +1 -1
  27. package/package.json +8 -8
  28. package/dist/cdn/5ZHNRQOW.js +0 -2
  29. package/dist/cdn/7VPB6Q55.js +0 -63
  30. package/dist/cdn/DU2R3VC4.js +0 -2
  31. package/dist/cdn/ITRJGXFV.js +0 -93
  32. package/dist/cdn/KWL2D56D.js +0 -3
  33. package/dist/cdn/L3YOPSRB.js +0 -135
  34. package/dist/cdn/N47MW5HI.js +0 -9
  35. package/dist/cdn/QAXFE5DD.js +0 -2
  36. package/dist/cdn/R6KJVAX3.js +0 -99
  37. package/dist/cdn/XYHIVGUK.js +0 -2
@@ -0,0 +1,16 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{a as O}from"./FIYYZIGB.js";import{d as n,j as _,k as j,l as k,m as v,n as I,o as z,p as w,q as y,r as q}from"./UK7WZMZ4.js";import{a as C}from"./EFMYI4L2.js";import{L as P,M,N as A,T as F,h as W,j as c}from"./VWOBCSD6.js";import"./KHKREBVZ.js";import{a as U,b as D}from"./BCCFB3DG.js";import"./JVMGFTLZ.js";import{Ca as E}from"./EP2IQ53W.js";import"./55C6QNU6.js";import"./3UFTKKFG.js";import"./5PV2GUZW.js";var G=(r,s)=>{let e=U.fromTemplate(r);return D.fromMessages([e,...s])},H=async r=>{let{promptText:s,modelTier:e,messages:t,config:i}=r,l=G(s,t??[]),o=await O({modelTier:e,config:i});return l.pipe(o)},B=async r=>{let{promptText:s,modelTier:e="default",messages:t,inputVariables:i,config:l}=r,o=await(await H({promptText:s,modelTier:e,messages:t,config:l})).invoke(i??{},l);return typeof o=="string"?o:o.text};var h={heading:"Summary",findings:"Findings ({count})",noFindings:"No findings in the recorded model calls.",showCall:"Show call",modelSummary:"AI review",summarize:"Generate review",summaryNote:"Written by the model from the findings, figures, tool names and run names in this window. It cannot see message text, tool arguments, errors or timings, and can be wrong.",summaryBasis:"Based on {count}.",summaryFailed:"The review could not be generated."},K=.8,Q=1024,X=.5,Z=8e3,ee=6,te=2e4,V=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:0});function J(r,s,e=t=>t.runName?`"${v(t)}"`:v(t)){let t=[],i=new Set,l=new Set;for(let a of k(r)){let m=e(a),g=a.usages.at(-1)?.id,u=a.usages.flatMap(d=>d.promptSize===void 0||!d.contextWindow?[]:[{usage:d,share:d.promptSize/d.contextWindow}]).sort((d,p)=>p.share-d.share).at(0);if(u&&u.share>=K){let d=u.share>=1;t.push({level:d?"danger":"warning",title:d?"Input over the context limit":"Input near the context limit",message:`${m}, model call ${u.usage.number.toLocaleString("en")}: ${u.usage.promptSize?.toLocaleString("en")} of ${u.usage.contextWindow?.toLocaleString("en")} input tokens (${V.format(u.share)}). Trim the conversation history or tool results.`,callId:u.usage.id})}let R=a.usages.slice(1);R.length>0&&R.every(({cacheRead:d,promptSize:p})=>d===0&&(p??0)>=Q)&&t.push({level:"warning",title:"No prompt cache reads in a run",message:`${m}: ${a.usages.length.toLocaleString("en")} model calls, and none after the first read from the prompt cache. The start of the prompt may change between calls.`,callId:g});let b,T=new Map;for(let d of a.usages){let p=d.messages.reduce((x,{text:f})=>x+f.length,0);for(let{role:x,text:f,toolCalls:Y}of d.messages){for(let $ of Y??[])if($.id&&$.name&&!l.has($.id)){l.add($.id);let N=`${$.name}
3
+ ${$.args}`;T.set(N,{name:$.name,count:(T.get(N)?.count??0)+1})}x==="system"||f.length<Z||i.has(f)||(i.add(f),!b&&f.length/p>=X&&(b={level:"warning",title:"One message dominates",message:`${m}, model call ${d.number.toLocaleString("en")}: one ${x} message is ${V.format(f.length/p)} of the message text (${f.length.toLocaleString("en")} characters). Trim what that tool or message carries.`,callId:d.id}))}}b&&t.push(b),a.usages.length>=ee&&t.push({level:"warning",title:"Many model calls in a run",message:`${m}: ${a.usages.length.toLocaleString("en")} model calls. Check for a tool loop or unclear tool descriptions.`,callId:g});for(let{name:d,count:p}of T.values())p>1&&t.push({level:"warning",title:"Repeated tool call",message:`${m}: ${d} was called ${p.toLocaleString("en")} times with the same arguments. Cache the tool's results, or make its description clearer.`,callId:g})}let o=s.reduce((a,{description:m,schema:g})=>a+m.length+g.length,0);return o>=te&&t.push({level:"warning",title:"Large tool definitions",message:`${s.length.toLocaleString("en")} registered tools total ${o.toLocaleString("en")} characters. Shorten descriptions or register fewer tools.`}),t.sort((a,m)=>+(a.level==="warning")-+(m.level==="warning"))}var S=["Overview","Working well","Worth improving"];function ae(r){let s=[];for(let e of r.split(`
4
+ `).map(t=>t.trim())){let t=S.find(a=>a.toLowerCase()===e.replace(/:$/u,"").toLowerCase()),i=/^(?<number>\d+)[.)]\s+(?<text>.+)$/u.exec(e)?.groups,l=i&&{number:Number(i.number),text:i.text},o=s.at(-1);t?s.push({heading:t}):l&&o&&"items"in o?o.items.push(l):l?s.push({items:[l]}):e&&s.push({paragraph:e})}return s}var ie=`You are reviewing how an AI assistant's agent loop behaved, for the developer who tunes it. Write the way you would explain it to a teammate: plain, direct sentences that connect cause and effect, not a list of readings.
5
+ In one run the model is called, it may ask for tool calls, and it is called again with the results until it has an answer.
6
+ The next message is JSON: the runs with their names (the request that started each), figures for each recorded model call, the registered tools, and "findings", which are problems that fixed checks already found.
7
+ You cannot see message text, tool arguments, errors or timings. Do not give advice that depends on them, and do not comment on speed. The askUser tool is the assistant asking the user a question; calling it several times in a run is expected.
8
+ Mention a figure only when it makes a point, and round it. Say what a figure means for the developer instead of repeating it. Leave out anything you cannot draw a conclusion from.
9
+ Answer in plain text, without markup, in three short parts, each under its heading on its own line:
10
+ ${S[0]}
11
+ Two or three sentences: what the runs did, and whether anything needs attention.
12
+ ${S[1]}
13
+ A short paragraph on what is healthy, in context use (input size against the context window, the prompt cache, the size of messages and tool results) and in model calls (how many each run needed, how tools were asked for).
14
+ ${S[2]}
15
+ Start with the findings. For each, say in your own words what happened, why it matters and one concrete next step. Then add anything the findings missed, including agent loop suggestions where the figures support them: tools asked for one per model call that could be asked for together, tools always called in sequence that could be one tool, repeated calls to the same tool, and input that grows from one call to the next because of large tool results. Write each point on its own line, starting with its number and a full stop. When nothing needs attention, say so in one sentence.
16
+ Name a run by its number and its name, such as Run 1 "List my groups", the first time it appears, and by its number after that.`;function ne(r){return r.runName?`Run ${r.runNumber} "${v(r)}"`:`Run ${r.runNumber}`}function oe(r,s){return JSON.stringify({runs:k(r).map(e=>({run:e.runNumber,name:e.runName?v(e):void 0,modelCalls:e.usages.length})),findings:J(r,s,ne).map(({level:e,title:t,message:i})=>({level:e,title:t,message:i})),modelCalls:r.map(e=>{let t=e.messages.findLastIndex(({toolCalls:i})=>i?.length);return{run:e.runNumber,modelCall:e.number,inputTokens:e.promptSize,contextWindow:e.contextWindow,cacheReadTokens:e.cacheRead,cacheWriteTokens:e.cacheWrite,messages:e.messages.length,messageCharacters:e.messages.reduce((i,{text:l})=>i+l.length,0),toolsRequested:e.messages[t]?.toolCalls?.map(({name:i})=>i)??[],toolResultCharacters:t<0?[]:e.messages.slice(t+1).filter(({role:i})=>i==="tool").map(({text:i})=>i.length)}}),registeredTools:s.map(({name:e,description:t,schema:i,cachePolicy:l})=>({name:e,characters:t.length+i.length,cachePolicy:l}))})}var se=W`:host{display:block;block-size:100%}.content{display:flex;block-size:100%}calcite-action-bar{border-inline-end:1px solid var(--calcite-color-border-3)}.view{flex:1;min-inline-size:0}.context{display:flex;block-size:100%}.context-calls{flex:none;inline-size:16rem;border-inline-end:1px solid var(--calcite-color-border-3)}.context-run{--calcite-block-content-space: 0}.context-calls-info{margin:var(--calcite-spacing-md);max-inline-size:16rem}.context-details{flex:1;min-inline-size:0}.context[hidden],.summary[hidden],.runs[hidden]{display:none}.context-empty{margin:0}.context-tool-description{margin-block:0 var(--calcite-spacing-sm)}.context pre{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--calcite-font-size--2)}.runs{block-size:100%}.summary calcite-notice{margin-block-end:var(--calcite-spacing-sm)}.summary-note{margin-block:0 var(--calcite-spacing-sm);color:var(--calcite-color-text-3);font-size:var(--calcite-font-size--2)}.review{margin-block-end:var(--calcite-spacing-sm);padding:var(--calcite-spacing-md);border:1px solid var(--calcite-color-border-3);background-color:var(--calcite-color-foreground-2);line-height:var(--calcite-font-line-height-relative-snug)}.review h5{margin-block:var(--calcite-spacing-md) var(--calcite-spacing-xs);color:var(--calcite-color-text-1);font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium)}.review h5:first-child{margin-block-start:0}.review p,.review ol{margin-block:0 var(--calcite-spacing-xs)}.review ol{padding-inline-start:var(--calcite-spacing-xl)}.review li{margin-block-end:var(--calcite-spacing-xs)}.review>:last-child{margin-block-end:0}`,L=class extends A{constructor(){super(...arguments),this.callsInfoEl=P(),this.view="runs",this.contextUsages=[],this.registeredTools=[]}static{this.properties={view:16,selectedCallId:16,modelSummary:16,contextUsages:0,registeredTools:0}}static{this.styles=se}async summarize(){if(this.modelSummary==="loading")return;let{contextUsages:s}=this;this.modelSummary="loading";try{let e=await B({promptText:ie,modelTier:"fast",messages:[new E(oe(s,this.registeredTools))]});this.modelSummary={text:e,calls:s.length}}catch(e){console.warn("Portal assistant diagnostics could not generate the model summary.",e),this.modelSummary="failed"}}renderSummary(){let{contextUsages:s,modelSummary:e}=this,t=J(s,this.registeredTools);return c`<calcite-panel class="summary" .hidden=${this.view!=="summary"} .heading=${h.heading} heading-level=3 .description=${s.length?z(s):n.notReported}><calcite-block-group .label=${h.heading}><calcite-block .heading=${h.findings.replace("{count}",t.length.toLocaleString())} heading-level=4 expandable expanded>${t.length===0&&c`<calcite-notice open icon kind=info width=full><div slot=message>${h.noFindings}</div></calcite-notice>`||""}${t.map(({level:i,title:l,message:o,callId:a})=>c`<calcite-notice open icon .kind=${i} width=full><div slot=title>${l}</div><div slot=message>${o}</div>${a&&c`<calcite-link slot=link @click=${()=>{this.selectedCallId=a,this.view="context"}}>${h.showCall}</calcite-link>`||""}</calcite-notice>`)}</calcite-block>${s.length>0&&c`<calcite-block .heading=${h.modelSummary} heading-level=4 expandable expanded><p class="summary-note">${h.summaryNote}</p>${e==="failed"&&c`<calcite-notice open icon kind=danger width=full><div slot=message>${h.summaryFailed}</div></calcite-notice>`||""}${typeof e=="object"&&c`<div class="review">${ae(e.text).map(i=>"heading"in i?c`<h5>${i.heading}</h5>`:"items"in i?c`<ol>${i.items.map(l=>c`<li .value=${l.number}>${l.text}</li>`)}</ol>`:c`<p>${i.paragraph}</p>`)}</div><p class="summary-note">${h.summaryBasis.replace("{count}",I(e.calls))}</p>`||""}<calcite-button appearance=outline icon-start=effects .loading=${e==="loading"} @click=${()=>{this.summarize()}}>${h.summarize}</calcite-button></calcite-block>`||""}</calcite-block-group></calcite-panel>`}renderContext(){let{contextUsages:s,registeredTools:e}=this,t=_(s,this.selectedCallId),i=t?.messages??[],l="calls-info";return c`<div class="context" .hidden=${this.view!=="context"}>${t&&c`<calcite-panel class="context-calls" .heading=${n.calls} heading-level=3 .description=${z(s)} @keydown=${o=>{let a=this.callsInfoEl.value;o.key==="Escape"&&a?.open&&(o.stopPropagation(),a.open=!1)}}><calcite-action slot=header-actions-end id=${l} icon=information .text=${n.callsInfo}></calcite-action><calcite-popover .referenceElement=${l} .label=${n.callsInfo} auto-close overlay-positioning=fixed placement=bottom-start ${M(this.callsInfoEl)}><p class="context-calls-info">${n.callsDescription}</p></calcite-popover><calcite-block-group .label=${n.calls}>${C(k(s),o=>o.runId,o=>c`<calcite-block class="context-run" .heading=${v(o)} heading-level=4 .description=${I(o.usages.length)} expandable expanded><calcite-list .label=${v(o)} selection-mode=single-persist selection-appearance=border>${C(o.usages,a=>a.id,a=>c`<calcite-list-item .label=${n.call.replace("{number}",a.number.toLocaleString())} .description=${n.callSummary.replace("{used}",w(a.promptSize)).replace("{read}",w(a.cacheRead)).replace("{write}",w(a.cacheWrite))} .selected=${a===t} @calciteListItemSelect=${()=>{this.selectedCallId=a.id}}></calcite-list-item>`)}</calcite-list></calcite-block>`)}</calcite-block-group></calcite-panel>`||""}<calcite-panel class="context-details" .heading=${t?n.call.replace("{number}",t.number.toLocaleString()):n.heading} heading-level=3 .description=${q(t)}><calcite-block-group .label=${n.heading}>${t&&c`<calcite-block .heading=${n.messages} heading-level=4 .description=${`${n.cache.replace("{read}",w(t.cacheRead)).replace("{write}",w(t.cacheWrite))}${j(t)?` ${n.cacheUnidentified}`:""}`} expandable expanded><calcite-block-group slot=children .label=${n.messages} scale=s>${i.map(({role:o,text:a,cached:m,hasCachedToolResults:g})=>c`<calcite-block .heading=${o} heading-level=5 expandable .description=${[y(a),...m===void 0?[]:[m?n.cached:n.new],...g?[n.cachedResultsNote]:[]].join(" | ")}><pre>${a}</pre></calcite-block>`)}</calcite-block-group></calcite-block><calcite-block .heading=${n.cachedResults.replace("{count}",t.cachedToolResults.length.toLocaleString())} heading-level=4 .description=${n.cachedResultsDescription} expandable expanded>${t.cachedToolResults.length?c`<calcite-block-group slot=children .label=${n.cachedResultsNote} scale=s>${t.cachedToolResults.map(({toolName:o,input:a,output:m})=>c`<calcite-block .heading=${o} heading-level=5 expandable .description=${[n.cachedResultInput.replace("{input}",()=>a),y(m)].join(" | ")}><pre>${m}</pre></calcite-block>`)}</calcite-block-group>`:c`<p class="context-empty">${n.cachedResultsNone}</p>`}</calcite-block>`||""}<calcite-block .heading=${n.tools.replace("{count}",e.length.toLocaleString())} heading-level=4 expandable expanded><calcite-block-group slot=children .label=${n.tools.replace("{count}",e.length.toLocaleString())} scale=s>${e.map(({name:o,description:a,schema:m,cachePolicy:g})=>c`<calcite-block .heading=${o} heading-level=5 expandable .description=${y(a+m)}>${g!=="no-cache"&&c`<calcite-chip slot=content-end scale=s .label=${n.resultsCached}>${g==="normal"?n.resultsCached:n.resultsCachedNoInvalidation}</calcite-chip>`||""}<p class="context-tool-description">${a}</p><pre>${m}</pre></calcite-block>`)}</calcite-block-group></calcite-block></calcite-block-group></calcite-panel></div>`}render(){return c`<div class="content"><calcite-action-bar><calcite-action icon=list .text=${n.runs} .active=${this.view==="runs"} @click=${()=>{this.view="runs"}}></calcite-action><calcite-action icon=chart-magnifying-glass .text=${n.heading} .active=${this.view==="context"} @click=${()=>{this.view="context"}}></calcite-action><calcite-action icon=lightbulb .text=${h.heading} .active=${this.view==="summary"} @click=${()=>{this.view="summary"}}></calcite-action></calcite-action-bar><div class="view">${this.renderContext()}${this.renderSummary()}<div class="runs" .hidden=${this.view!=="runs"}><slot></slot></div></div></div>`}};F("arcgis-portal-ai-assistant-diagnostics",L);export{L as ArcgisPortalAiAssistantDiagnostics};
@@ -0,0 +1,18 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{E as F,F as Pe,L as ve,M as Te,N as xe}from"./JVMGFTLZ.js";import{C as E,Ca as we,Ha as be,Ma as L,Z as H,a as ge,fa as de,qa as ye,ua as Y}from"./EP2IQ53W.js";var w=class extends F{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(s){super(s);let{inputVariables:e}=s;if(e.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,s)}async mergePartialAndUserVariables(s){let e=this.partialVariables??{},t={};for(let[a,r]of Object.entries(e))typeof r=="string"?t[a]=r:t[a]=await r();return{...t,...s}}async invoke(s,e){let t={...this.metadata,...e?.metadata},a=[...this.tags??[],...e?.tags??[]];return this._callWithConfig(r=>this.formatPromptValue(r),s,{...e,tags:a,metadata:t,runType:"prompt"})}};var v=class extends w{async formatPromptValue(s){let e=await this.format(s);return new ve(e)}};function k(){return E(new Error("Prompt template nesting exceeds maximum depth (256)."),"INVALID_PROMPT_INPUT")}var ke=Object.prototype.toString,I=Array.isArray||function(e){return ke.call(e)==="[object Array]"};function ee(s){return typeof s=="function"}function Ue(s){return I(s)?"array":typeof s}function Z(s){return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _e(s,e){return s!=null&&typeof s=="object"&&e in s}function Be(s,e){return s!=null&&typeof s!="object"&&s.hasOwnProperty&&s.hasOwnProperty(e)}var Ne=RegExp.prototype.test;function De(s,e){return Ne.call(s,e)}var $e=/\S/;function ze(s){return!De($e,s)}var We={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Ge(s){return String(s).replace(/[&<>"'`=\/]/g,function(t){return We[t]})}var He=/\s*/,Le=/\s+/,Ve=/\s*=/,qe=/\s*\}/,Je=/#|\^|\/|>|\{|&|=|!/;function Ke(s,e){if(!s)return[];var t=!1,a=[],r=[],i=[],n=!1,o=!1,l="",p=0;function f(){if(n&&!o)for(;i.length;)delete r[i.pop()];else i=[];n=!1,o=!1}var b,_,fe;function he(P){if(typeof P=="string"&&(P=P.split(Le,2)),!I(P)||P.length!==2)throw new Error("Invalid tags: "+P);b=new RegExp(Z(P[0])+"\\s*"),_=new RegExp("\\s*"+Z(P[1])),fe=new RegExp("\\s*"+Z("}"+P[1]))}he(e||d.tags);for(var m=new B(s),x,h,g,O,G,V;!m.eos();){if(x=m.pos,g=m.scanUntil(b),g)for(var X=0,Oe=g.length;X<Oe;++X)O=g.charAt(X),ze(O)?(i.push(r.length),l+=O):(o=!0,t=!0,l+=" "),r.push(["text",O,x,x+1]),x+=1,O===`
3
+ `&&(f(),l="",p=0,t=!1);if(!m.scan(b))break;if(n=!0,h=m.scan(Je)||"name",m.scan(He),h==="="?(g=m.scanUntil(Ve),m.scan(Ve),m.scanUntil(_)):h==="{"?(g=m.scanUntil(fe),m.scan(qe),m.scanUntil(_),h="&"):g=m.scanUntil(_),!m.scan(_))throw new Error("Unclosed tag at "+m.pos);if(h==">"?G=[h,g,x,m.pos,l,p,t]:G=[h,g,x,m.pos],p++,r.push(G),h==="#"||h==="^")a.push(G);else if(h==="/"){if(V=a.pop(),!V)throw new Error('Unopened section "'+g+'" at '+x);if(V[1]!==g)throw new Error('Unclosed section "'+V[1]+'" at '+x)}else h==="name"||h==="{"||h==="&"?o=!0:h==="="&&he(g)}if(f(),V=a.pop(),V)throw new Error('Unclosed section "'+V[1]+'" at '+m.pos);return Xe(Qe(r))}function Qe(s){for(var e=[],t,a,r=0,i=s.length;r<i;++r)t=s[r],t&&(t[0]==="text"&&a&&a[0]==="text"?(a[1]+=t[1],a[3]=t[3]):(e.push(t),a=t));return e}function Xe(s){for(var e=[],t=e,a=[],r,i,n=0,o=s.length;n<o;++n)switch(r=s[n],r[0]){case"#":case"^":t.push(r),a.push(r),t=r[4]=[];break;case"/":i=a.pop(),i[5]=r[2],t=a.length>0?a[a.length-1][4]:e;break;default:t.push(r)}return e}function B(s){this.string=s,this.tail=s,this.pos=0}B.prototype.eos=function(){return this.tail===""};B.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return"";var a=t[0];return this.tail=this.tail.substring(a.length),this.pos+=a.length,a};B.prototype.scanUntil=function(e){var t=this.tail.search(e),a;switch(t){case-1:a=this.tail,this.tail="";break;case 0:a="";break;default:a=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=a.length,a};function C(s,e){this.view=s,this.cache={".":this.view},this.parent=e}C.prototype.push=function(e){return new C(e,this)};C.prototype.lookup=function(e){var t=this.cache,a;if(t.hasOwnProperty(e))a=t[e];else{for(var r=this,i,n,o,l=!1;r;){if(e.indexOf(".")>0)for(i=r.view,n=e.split("."),o=0;i!=null&&o<n.length;)o===n.length-1&&(l=_e(i,n[o])||Be(i,n[o])),i=i[n[o++]];else i=r.view[e],l=_e(r.view,e);if(l){a=i;break}r=r.parent}t[e]=a}return ee(a)&&(a=a.call(this.view)),a};function u(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}u.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};u.prototype.parse=function(e,t){var a=this.templateCache,r=e+":"+(t||d.tags).join(":"),i=typeof a<"u",n=i?a.get(r):void 0;return n==null&&(n=Ke(e,t),i&&a.set(r,n)),n};u.prototype.render=function(e,t,a,r){var i=this.getConfigTags(r),n=this.parse(e,i),o=t instanceof C?t:new C(t,void 0);return this.renderTokens(n,o,a,e,r)};u.prototype.renderTokens=function(e,t,a,r,i){for(var n="",o,l,p,f=0,b=e.length;f<b;++f)p=void 0,o=e[f],l=o[0],l==="#"?p=this.renderSection(o,t,a,r,i):l==="^"?p=this.renderInverted(o,t,a,r,i):l===">"?p=this.renderPartial(o,t,a,i):l==="&"?p=this.unescapedValue(o,t):l==="name"?p=this.escapedValue(o,t,i):l==="text"&&(p=this.rawValue(o)),p!==void 0&&(n+=p);return n};u.prototype.renderSection=function(e,t,a,r,i){var n=this,o="",l=t.lookup(e[1]);function p(_){return n.render(_,t,a,i)}if(l){if(I(l))for(var f=0,b=l.length;f<b;++f)o+=this.renderTokens(e[4],t.push(l[f]),a,r,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")o+=this.renderTokens(e[4],t.push(l),a,r,i);else if(ee(l)){if(typeof r!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(t.view,r.slice(e[3],e[5]),p),l!=null&&(o+=l)}else o+=this.renderTokens(e[4],t,a,r,i);return o}};u.prototype.renderInverted=function(e,t,a,r,i){var n=t.lookup(e[1]);if(!n||I(n)&&n.length===0)return this.renderTokens(e[4],t,a,r,i)};u.prototype.indentPartial=function(e,t,a){for(var r=t.replace(/[^ \t]/g,""),i=e.split(`
4
+ `),n=0;n<i.length;n++)i[n].length&&(n>0||!a)&&(i[n]=r+i[n]);return i.join(`
5
+ `)};u.prototype.renderPartial=function(e,t,a,r){if(a){var i=this.getConfigTags(r),n=ee(a)?a(e[1]):a[e[1]];if(n!=null){var o=e[6],l=e[5],p=e[4],f=n;l==0&&p&&(f=this.indentPartial(n,p,o));var b=this.parse(f,i);return this.renderTokens(b,t,a,f,r)}}};u.prototype.unescapedValue=function(e,t){var a=t.lookup(e[1]);if(a!=null)return a};u.prototype.escapedValue=function(e,t,a){var r=this.getConfigEscape(a)||d.escape,i=t.lookup(e[1]);if(i!=null)return typeof i=="number"&&r===d.escape?String(i):r(i)};u.prototype.rawValue=function(e){return e[1]};u.prototype.getConfigTags=function(e){return I(e)?e:e&&typeof e=="object"?e.tags:void 0};u.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!I(e))return e.escape};var d={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(s){U.templateCache=s},get templateCache(){return U.templateCache}},U=new u;d.clearCache=function(){return U.clearCache()};d.parse=function(e,t){return U.parse(e,t)};d.render=function(e,t,a,r){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Ue(e)+'" was given as the first argument for mustache#render(template, view, partials)');return U.render(e,t,a,r)};d.escape=Ge;d.Scanner=B;d.Context=C;d.Writer=u;var te=d;var Ye={escape:s=>s},M=s=>{let e=s.split(""),t=[],a=(i,n)=>{for(let o=n;o<e.length;o+=1)if(i.includes(e[o]))return o;return-1},r=0;for(;r<e.length;)if(e[r]==="{"&&r+1<e.length&&e[r+1]==="{")t.push({type:"literal",text:"{"}),r+=2;else if(e[r]==="}"&&r+1<e.length&&e[r+1]==="}")t.push({type:"literal",text:"}"}),r+=2;else if(e[r]==="{"){let i=a("}",r);if(i<0)throw new Error("Unclosed '{' in template.");t.push({type:"variable",name:e.slice(r+1,i).join("")}),r=i+1}else{if(e[r]==="}")throw new Error("Single '}' in template.");{let i=a("{}",r),n=(i<0?e.slice(r):e.slice(r,i)).join("");t.push({type:"literal",text:n}),r=i<0?e.length:i}}return t},Me=(s,e=[],t=0)=>{if(t>=256)throw k();let a=[];for(let r of s)if(r[0]==="name"){let i=r[1].includes(".")?r[1].split(".")[0]:r[1];a.push({type:"variable",name:i})}else if(["#","&","^",">"].includes(r[0])){if(a.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let i=[...e,r[1]],n=Me(r[4],i,t+1);a.push(...n)}}else a.push({type:"literal",text:r[1]});return a},A=s=>{let e=te.parse(s);return Me(e)},re=(s,e)=>M(s).reduce((t,a)=>{if(a.type==="variable"){if(a.name in e)return t+(typeof e[a.name]=="string"?e[a.name]:JSON.stringify(e[a.name]));throw new Error(`(f-string) Missing value for input ${a.name}`)}return t+a.text},""),ae=(s,e)=>te.render(s,e,void 0,Ye),N={"f-string":re,mustache:ae},se={"f-string":M,mustache:A},c=(s,e,t)=>{try{return N[e](s,t)}catch(a){throw E(a,"INVALID_PROMPT_INPUT")}},S=(s,e)=>se[e](s),T=(s,e,t)=>{if(!(e in N)){let a=Object.keys(N);throw new Error(`Invalid template format. Got \`${e}\`;
6
+ should be one of ${a}`)}try{let a=Object.fromEntries(t.map(r=>[r,"foo"]));Array.isArray(s)?s.forEach(r=>{if(r.type==="text"&&"text"in r&&typeof r.text=="string")c(r.text,e,a);else if(r.type==="image_url"){if(typeof r.image_url=="string")c(r.image_url,e,a);else if(typeof r.image_url=="object"&&r.image_url!==null&&"url"in r.image_url&&typeof r.image_url.url=="string"){let i=r.image_url.url;c(i,e,a)}}else throw new Error(`Invalid message template received. ${JSON.stringify(r,null,2)}`)}):c(s,e,a)}catch(a){throw new Error(`Invalid prompt schema: ${a.message}`)}};var y=class D extends v{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),T(this.template,this.templateFormat,t)}}_getPromptType(){return"prompt"}async format(e){let t=await this.mergePartialAndUserVariables(e);return c(this.template,this.templateFormat,t)}static fromExamples(e,t,a,r=`
7
+
8
+ `,i=""){let n=[i,...e,t].join(r);return new D({inputVariables:a,template:n})}static fromTemplate(e,t){let{templateFormat:a="f-string",...r}=t??{},i=new Set;return S(e,a).forEach(n=>{n.type==="variable"&&i.add(n.name)}),new D({inputVariables:[...i],templateFormat:a,template:e,...r})}async partial(e){let t=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},r={...this,inputVariables:t,partialVariables:a};return new D(r)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new D({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}};var R=class Se extends w{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),T([{type:"image_url",image_url:this.template}],this.templateFormat,t)}}_getPromptType(){return"prompt"}async partial(e){let t=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},r={...this,inputVariables:t,partialVariables:a};return new Se(r)}async format(e){let t={};for(let[n,o]of Object.entries(this.template))typeof o=="string"?t[n]=c(o,this.templateFormat,e):t[n]=o;let a=e.url||t.url,r=e.detail||t.detail;if(!a)throw new Error("Must provide either an image URL.");if(typeof a!="string")throw new Error("url must be a string.");let i={url:a};return r&&(i.detail=r),i}async formatPromptValue(e){let t=await this.format(e);return new xe(t)}};var $=class extends F{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(s){let e=s.templateFormat??"f-string",t=ie(s.template,e);super({inputVariables:t,...s}),this.template=s.template,this.templateFormat=e,this.inputVariables=t}async format(s){return ne(this.template,s,this.templateFormat)}async invoke(s){return await this._callWithConfig(this.format.bind(this),s,{runType:"prompt"})}};function ie(s,e,t=0){if(t>=256)throw k();let a=[];for(let r of Object.values(s))if(typeof r=="string")S(r,e).forEach(i=>{i.type==="variable"&&a.push(i.name)});else if(Array.isArray(r))for(let i of r)typeof i=="string"?S(i,e).forEach(n=>{n.type==="variable"&&a.push(n.name)}):typeof i=="object"&&a.push(...ie(i,e,t+1));else typeof r=="object"&&r!==null&&a.push(...ie(r,e,t+1));return Array.from(new Set(a))}function ne(s,e,t,a=0){if(a>=256)throw k();let r={};for(let[i,n]of Object.entries(s))if(typeof n=="string")r[i]=c(n,t,e);else if(Array.isArray(n)){let o=[];for(let l of n)typeof l=="string"?o.push(c(l,t,e)):typeof l=="object"&&o.push(ne(l,e,t,a+1));r[i]=o}else typeof n=="object"&&n!==null?r[i]=ne(n,e,t,a+1):r[i]=n;return r}var z=class extends F{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(s,e){return this._callWithConfig(t=>this.formatMessages(t),s,{...e,runType:"prompt"})}},J=class extends z{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(s){typeof s=="string"&&(s={variableName:s}),super(s),this.variableName=s.variableName,this.optional=s.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(s){let e=s[this.variableName];if(this.optional&&!e)return[];if(!e){let a=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw a.name="InputFormatError",a}let t;try{Array.isArray(e)?t=e.map(L):t=[L(e)]}catch(a){let r=typeof e=="string"?e:JSON.stringify(e,null,2),i=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${r}`,`Additional message: ${a.message}`].join(`
9
+
10
+ `));throw i.name="InputFormatError",i.lc_error_code=a.lc_error_code,i}return t}},oe=class extends z{prompt;constructor(s){"prompt"in s||(s={prompt:s}),super(s),this.prompt=s.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(s){return[await this.format(s)]}},W=class extends w{constructor(s){super(s)}async format(s){return(await this.formatPromptValue(s)).toString()}async formatPromptValue(s){let e=await this.formatMessages(s);return new Te(e)}},le=class extends oe{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(s,e){"prompt"in s||(s={prompt:s,role:e}),super(s),this.role=s.role}async format(s){return new Y(await this.prompt.format(s),this.role)}static fromTemplate(s,e,t){return new this(y.fromTemplate(s,{templateFormat:t?.templateFormat}),e)}};function Ze(s){return s===null||typeof s!="object"||Array.isArray(s)?!1:Object.keys(s).length===1&&"text"in s&&typeof s.text=="string"}function et(s){return s===null||typeof s!="object"||Array.isArray(s)?!1:"image_url"in s&&(typeof s.image_url=="string"||typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string")}var pe=class extends z{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(s,e){if("prompt"in s||(s={prompt:s}),super(s),this.prompt=s.prompt,Array.isArray(this.prompt)){let t=[];this.prompt.forEach(a=>{"inputVariables"in a&&(t=t.concat(a.inputVariables))}),this.inputVariables=t}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=e??this.additionalOptions}createMessage(s){let e=this.constructor;if(e._messageClass())return new(e._messageClass())({content:s});if(e.chatMessageClass){let t=e.chatMessageClass();return new t({content:s,role:this.getRoleFromMessageClass(t.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(s){switch(s){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(s,e){if(typeof s=="string")return new this(y.fromTemplate(s,e));let t=[];for(let a of s)if(typeof a=="string")t.push(y.fromTemplate(a,e));else if(a!==null)if(Ze(a)){let r="";typeof a.text=="string"&&(r=a.text??"");let i={...e,additionalContentFields:a};t.push(y.fromTemplate(r,i))}else if(et(a)){let r=a.image_url??"",i,n=[];if(typeof r=="string"){let o;e?.templateFormat==="mustache"?o=A(r):o=M(r);let l=o.flatMap(p=>p.type==="variable"?[p.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
11
+ Got: ${l}
12
+ From: ${r}`);n=[l[0]]}else n=[];r={url:r},i=new R({template:r,inputVariables:n,templateFormat:e?.templateFormat,additionalContentFields:a})}else if(typeof r=="object"){if("url"in r){let o;e?.templateFormat==="mustache"?o=A(r.url):o=M(r.url),n=o.flatMap(l=>l.type==="variable"?[l.name]:[])}else n=[];i=new R({template:r,inputVariables:n,templateFormat:e?.templateFormat,additionalContentFields:a})}else throw new Error("Invalid image template");t.push(i)}else typeof a=="object"&&t.push(new $({template:a,templateFormat:e?.templateFormat}));return new this({prompt:t,additionalOptions:e})}async format(s){if(this.prompt instanceof v){let e=await this.prompt.format(s);return this.createMessage(e)}else{let e=[];for(let t of this.prompt){let a={};if(!("inputVariables"in t))throw new Error(`Prompt ${t} does not have inputVariables defined.`);for(let r of t.inputVariables)a||(a={[r]:s[r]}),a={...a,[r]:s[r]};if(t instanceof v){let r=await t.format(a),i;"additionalContentFields"in t&&(i=t.additionalContentFields),r!==""&&e.push({...i,type:"text",text:r})}else if(t instanceof R){let r=await t.format(a),i;"additionalContentFields"in t&&(i=t.additionalContentFields),e.push({...i,type:"image_url",image_url:r})}else if(t instanceof $){let r=await t.format(a),i;"additionalContentFields"in t&&(i=t.additionalContentFields),e.push({...i,...r})}}return this.createMessage(e)}}async formatMessages(s){return[await this.format(s)]}},K=class extends pe{static _messageClass(){return we}static lc_name(){return"HumanMessagePromptTemplate"}},me=class extends pe{static _messageClass(){return ye}static lc_name(){return"AIMessagePromptTemplate"}},ce=class extends pe{static _messageClass(){return be}static lc_name(){return"SystemMessagePromptTemplate"}};function tt(s){return typeof s.formatMessages=="function"}function rt(s,e){if(tt(s)||de(s))return s;if(Array.isArray(s)&&s[0]==="placeholder"){let r=s[1];if(e?.templateFormat==="mustache"&&typeof r=="string"&&r.slice(0,2)==="{{"&&r.slice(-2)==="}}")return new J({variableName:r.slice(2,-2),optional:!0});if(typeof r=="string"&&r[0]==="{"&&r[r.length-1]==="}")return new J({variableName:r.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${s[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let t=L(s),a;if(typeof t.content=="string"?a=t.content:a=t.content.map(r=>"text"in r?{...r,text:r.text}:"image_url"in r?{...r,image_url:r.image_url}:r),t._getType()==="human")return K.fromTemplate(a,e);if(t._getType()==="ai")return me.fromTemplate(a,e);if(t._getType()==="system")return ce.fromTemplate(a,e);if(Y.isInstance(t))return le.fromTemplate(t.content,t.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${t._getType()}".`)}function at(s){return s.constructor.lc_name()==="MessagesPlaceholder"}var j=class q extends W{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(e){if(super(e),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let t=new Set;for(let o of this.promptMessages)if(!(o instanceof H))for(let l of o.inputVariables)t.add(l);let a=this.inputVariables,r=new Set(this.partialVariables?a.concat(Object.keys(this.partialVariables)):a),i=new Set([...r].filter(o=>!t.has(o)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let n=new Set([...t].filter(o=>!r.has(o)));if(n.size>0)throw new Error(`Input variables \`${[...n]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,t){return typeof e.content=="string"||(e.content=await Promise.all(e.content.map(async a=>{if(a.type!=="image_url")return a;let r="";typeof a.image_url=="string"?r=a.image_url:typeof a.image_url=="object"&&a.image_url!==null&&"url"in a.image_url&&typeof a.image_url.url=="string"&&(r=a.image_url.url);let i=await y.fromTemplate(r,{templateFormat:this.templateFormat}).format(t);return typeof a.image_url=="object"&&a.image_url!==null&&"url"in a.image_url?a.image_url.url=i:a.image_url=i,a}))),e}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),a=[];for(let r of this.promptMessages)if(r instanceof H)a.push(await this._parseImagePrompts(r,t));else{let i;this.templateFormat==="mustache"?i={...t}:i=r.inputVariables.reduce((o,l)=>{if(!(l in t)&&!(at(r)&&r.optional))throw E(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return o[l]=t[l],o},{});let n=await r.formatMessages(i);a=a.concat(n)}return a}async partial(e){let t=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},r={...this,inputVariables:t,partialVariables:a};return new q(r)}static fromTemplate(e,t){let a=new K({prompt:y.fromTemplate(e,t)});return this.fromMessages([a])}static fromMessages(e,t){let a=e.reduce((n,o)=>n.concat(o instanceof q?o.promptMessages:[rt(o,t)]),[]),r=e.reduce((n,o)=>o instanceof q?Object.assign(n,o.partialVariables):n,Object.create(null)),i=new Set;for(let n of a)if(!(n instanceof H))for(let o of n.inputVariables)o in r||i.add(o);return new this({...t,inputVariables:[...i],promptMessages:a,partialVariables:r,templateFormat:t?.templateFormat})}};var Ee=class ue extends v{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
13
+
14
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(e){if(super(e),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),T(this.prefix+this.suffix,this.templateFormat,t)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let t=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},r={...this,inputVariables:t,partialVariables:a};return new ue(r)}async format(e){let t=await this.mergePartialAndUserVariables(e),a=await this.getExamples(t),r=await Promise.all(a.map(n=>this.examplePrompt.format(n))),i=[this.prefix,...r,this.suffix].join(this.exampleSeparator);return c(i,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){let{example_prompt:t}=e;if(!t)throw new Error("Missing example prompt");let a=await y.deserialize(t),r;if(Array.isArray(e.examples))r=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new ue({inputVariables:e.input_variables,examplePrompt:a,examples:r,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Fe=class Ce extends W{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
15
+
16
+ `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
17
+
18
+ `,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),T(this.prefix+this.suffix,this.templateFormat,t)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),a=await this.getExamples(t);a=a.map(i=>{let n={};return this.examplePrompt.inputVariables.forEach(o=>{n[o]=i[o]}),n});let r=[];for(let i of a){let n=await this.examplePrompt.formatMessages(i);r.push(...n)}return r}async format(e){let t=await this.mergePartialAndUserVariables(e),a=await this.getExamples(t),r=(await Promise.all(a.map(n=>this.examplePrompt.formatMessages(n)))).flat().map(n=>n.content),i=[this.prefix,...r,this.suffix].join(this.exampleSeparator);return c(i,this.templateFormat,t)}async partial(e){let t=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},r={...this,inputVariables:t,partialVariables:a};return new Ce(r)}};var Ie=class Q extends w{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(a=>a.name),t=this.pipelinePrompts.map(a=>a.prompt.inputVariables.filter(r=>!e.includes(r))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce((a,r)=>(a[r]=e[r],a),{})}async formatPipelinePrompts(e){let t=await this.mergePartialAndUserVariables(e);for(let{name:a,prompt:r}of this.pipelinePrompts){let i=Q.extractRequiredInputValues(t,r.inputVariables);r instanceof j?t[a]=await r.formatMessages(i):t[a]=await r.format(i)}return Q.extractRequiredInputValues(t,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(e){let t={...this};return t.inputVariables=this.inputVariables.filter(a=>!(a in e)),t.partialVariables={...this.partialVariables??{},...e},new Q(t)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function Ae(s){return typeof s=="object"&&s!=null&&"withStructuredOutput"in s&&typeof s.withStructuredOutput=="function"}function st(s){return typeof s=="object"&&s!=null&&"lc_id"in s&&Array.isArray(s.lc_id)&&s.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var Re=class je extends j{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(Ae(e))return super.pipe(e.withStructuredOutput(this.schema));if(st(e)&&Ae(e.bound))return super.pipe(new Pe({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(e,t,a){return je.fromMessages(e,{schema:t,method:a})}};var Vr=ge({AIMessagePromptTemplate:()=>me,BaseChatPromptTemplate:()=>W,BaseMessagePromptTemplate:()=>z,BaseMessageStringPromptTemplate:()=>oe,BasePromptTemplate:()=>w,BaseStringPromptTemplate:()=>v,ChatMessagePromptTemplate:()=>le,ChatPromptTemplate:()=>j,DEFAULT_FORMATTER_MAPPING:()=>N,DEFAULT_PARSER_MAPPING:()=>se,DictPromptTemplate:()=>$,FewShotChatMessagePromptTemplate:()=>Fe,FewShotPromptTemplate:()=>Ee,HumanMessagePromptTemplate:()=>K,ImagePromptTemplate:()=>R,MessagesPlaceholder:()=>J,PipelinePromptTemplate:()=>Ie,PromptTemplate:()=>y,StructuredPrompt:()=>Re,SystemMessagePromptTemplate:()=>ce,checkValidTemplate:()=>T,interpolateFString:()=>re,interpolateMustache:()=>ae,parseFString:()=>M,parseMustache:()=>A,parseTemplate:()=>S,renderTemplate:()=>c});export{ce as a,j as b,Vr as c};