promptlayer 1.2.2 → 1.3.0

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/index.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var Yo=Object.create;var He=Object.defineProperty,Ho=Object.defineProperties,Xo=Object.getOwnPropertyDescriptor,Zo=Object.getOwnPropertyDescriptors,Qo=Object.getOwnPropertyNames,Ze=Object.getOwnPropertySymbols,vo=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty,Dn=Object.prototype.propertyIsEnumerable;var cn=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t);var Gn=(t,n,e)=>n in t?He(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e,E=(t,n)=>{for(var e in n||(n={}))pn.call(n,e)&&Gn(t,e,n[e]);if(Ze)for(var e of Ze(n))Dn.call(n,e)&&Gn(t,e,n[e]);return t},Y=(t,n)=>Ho(t,Zo(n));var Qe=(t,n)=>{var e={};for(var o in t)pn.call(t,o)&&n.indexOf(o)<0&&(e[o]=t[o]);if(t!=null&&Ze)for(var o of Ze(t))n.indexOf(o)<0&&Dn.call(t,o)&&(e[o]=t[o]);return e};var ts=(t,n)=>{for(var e in n)He(t,e,{get:n[e],enumerable:!0})},Fn=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Qo(n))!pn.call(t,r)&&r!==e&&He(t,r,{get:()=>n[r],enumerable:!(o=Xo(n,r))||o.enumerable});return t};var ut=(t,n,e)=>(e=t!=null?Yo(vo(t)):{},Fn(n||!t||!t.__esModule?He(e,"default",{value:t,enumerable:!0}):e,t)),es=t=>Fn(He({},"__esModule",{value:!0}),t);var S=(t,n,e)=>new Promise((o,r)=>{var i=u=>{try{d(e.next(u))}catch(_){r(_)}},l=u=>{try{d(e.throw(u))}catch(_){r(_)}},d=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,l);d((e=e.apply(t,n)).next())}),ft=function(t,n){this[0]=t,this[1]=n},ve=(t,n,e)=>{var o=(l,d,u,_)=>{try{var m=e[l](d),b=(d=m.value)instanceof ft,R=m.done;Promise.resolve(b?d[0]:d).then(x=>b?o(l==="return"?l:"next",d[1]?{done:x.done,value:x.value}:x,u,_):u({value:x,done:R})).catch(x=>o("throw",x,u,_))}catch(x){_(x)}},r=l=>i[l]=d=>new Promise((u,_)=>o(l,d,u,_)),i={};return e=e.apply(t,n),i[cn("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var tn=(t,n,e)=>(n=t[cn("asyncIterator")])?n.call(t):(t=t[cn("iterator")](),n={},e=(o,r)=>(r=t[o])&&(n[o]=i=>new Promise((l,d,u)=>(i=r.call(t,i),u=i.done,Promise.resolve(i.value).then(_=>l({value:_,done:u}),d)))),e("next"),e("return"),n);var Ms={};ts(Ms,{PromptLayer:()=>Rn});module.exports=es(Ms);var lo=ut(require("ably")),co=require("centrifuge"),po=ut(require("p-retry"));var Bn={png:"image/png",webp:"image/webp",jpeg:"image/jpeg",jpg:"image/jpeg",gif:"image/gif",url:"image/png"},st=(t,n,e,o)=>E({id:t,type:"function",function:{name:n,arguments:typeof e=="string"?e:JSON.stringify(e)}},o?{tool_id:o}:{}),y=o=>{var r=o,{type:t,item_id:n}=r,e=Qe(r,["type","item_id"]);let i=E({type:t},e);return n&&(i.id=n),i},Pt=(t,n)=>({role:"assistant",input_variables:[],template_format:"f-string",content:t,tool_calls:n}),At=(t,n)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:n});function zn(t){var n,e,o,r;return E(E({type:"url_citation",url:(n=t.url)!=null?n:"",title:(e=t.title)!=null?e:"",start_index:(o=t.start_index)!=null?o:0,end_index:(r=t.end_index)!=null?r:0},t.cited_text!=null?{cited_text:t.cited_text}:{}),t.encrypted_index!=null?{encrypted_index:t.encrypted_index}:{})}var Jn=(t,n,e)=>{var l,d,u,_,m,b,R,x,P,T,h,w,f,g,C,M,W,I,N,j,L,B,$,X,G,Z,J,rt,at,D,nt,it,gt,yt,ht,bt,Rt,xt,wt,Tt;let o=[],r=[];if(Array.isArray(t.content)){for(let q of t.content){if(!q||typeof q!="object")continue;let V=q.type;if(V==="text"){let v=(l=q.text)!=null?l:"",lt=(u=(d=q.citations)!=null?d:q.annotations)!=null?u:[],tt=[];for(let et of lt)et&&typeof et=="object"&&tt.push(zn(et));o.push(y(E({type:"text",text:v},tt.length>0?{annotations:tt}:{})))}else if(V==="thinking")o.push(y({type:"thinking",thinking:(_=q.thinking)!=null?_:"",signature:(m=q.signature)!=null?m:""}));else if(V==="tool_use")r.push(st((b=q.id)!=null?b:"",(R=q.name)!=null?R:"",(x=q.input)!=null?x:{}));else if(V==="server_tool_use")o.push(y({type:"server_tool_use",id:(P=q.id)!=null?P:"",name:(T=q.name)!=null?T:"",input:(h=q.input)!=null?h:{}}));else if(V==="web_search_tool_result"){let v=(w=q.content)!=null?w:[],lt=[];for(let tt of v)if(tt&&typeof tt=="object"&&tt.type==="web_search_result"){let et=tt;lt.push({type:"web_search_result",url:et.url,title:et.title,encrypted_content:et.encrypted_content,page_age:et.page_age})}o.push(y({type:"web_search_tool_result",tool_use_id:(f=q.tool_use_id)!=null?f:"",content:lt}))}else V==="bash_code_execution_tool_result"&&o.push(y({type:"bash_code_execution_tool_result",tool_use_id:(g=q.tool_use_id)!=null?g:"",content:(C=q.content)!=null?C:{}}))}let ot=Pt(o,r);return At(ot,n)}if(t.type==="content_block_start")if(((M=t.content_block)==null?void 0:M.type)==="thinking")o.push(y({type:"thinking",thinking:"",signature:""}));else if(((W=t.content_block)==null?void 0:W.type)==="text")o.push(y({type:"text",text:""}));else if(((I=t.content_block)==null?void 0:I.type)==="tool_use")r.push(st((N=t.content_block.id)!=null?N:"",(j=t.content_block.name)!=null?j:"",{}));else if(((L=t.content_block)==null?void 0:L.type)==="server_tool_use")o.push(y({type:"server_tool_use",id:(B=t.content_block.id)!=null?B:"",name:($=t.content_block.name)!=null?$:"",input:(X=t.content_block.input)!=null?X:{}}));else if(((G=t.content_block)==null?void 0:G.type)==="web_search_tool_result"){let ot=(Z=t.content_block.content)!=null?Z:[],q=[];for(let V of ot)if(V&&typeof V=="object"&&V.type==="web_search_result"){let v=V;q.push({type:"web_search_result",url:v.url,title:v.title,encrypted_content:v.encrypted_content,page_age:v.page_age})}o.push(y({type:"web_search_tool_result",tool_use_id:(J=t.content_block.tool_use_id)!=null?J:"",content:q}))}else((rt=t.content_block)==null?void 0:rt.type)==="bash_code_execution_tool_result"&&o.push(y({type:"bash_code_execution_tool_result",tool_use_id:(at=t.content_block.tool_use_id)!=null?at:"",content:(D=t.content_block.content)!=null?D:{}}));else if(t.type==="content_block_delta"){if(((nt=t.delta)==null?void 0:nt.type)==="thinking_delta")o.push(y({type:"thinking",thinking:(it=t.delta.thinking)!=null?it:"",signature:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="text_delta")o.push(y({type:"text",text:(yt=t.delta.text)!=null?yt:""}));else if(((ht=t.delta)==null?void 0:ht.type)==="signature_delta")o.push(y({type:"thinking",thinking:"",signature:(bt=t.delta.signature)!=null?bt:""}));else if(((Rt=t.delta)==null?void 0:Rt.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?o.push(y({type:"server_tool_use",id:"",name:"",input:(xt=t.delta.partial_json)!=null?xt:{}})):r.push(st("","",(wt=t.delta.partial_json)!=null?wt:""));else if(((Tt=t.delta)==null?void 0:Tt.type)==="citations_delta"&&t.delta.citation){let ot=t.delta.citation,q=[zn(ot)];o.push(y({type:"text",text:"",annotations:q}))}}let i=Pt(o,r);return At(i,n)},ns=t=>typeof t=="string"&&t.startsWith("image/");function Vn(t){var e,o,r,i;let n=t.web;return n&&typeof n=="object"?{uri:(e=n.uri)!=null?e:"",title:(o=n.title)!=null?o:""}:{uri:(r=t.uri)!=null?r:"",title:(i=t.title)!=null?i:""}}function os(t){if(!t||typeof t!="object")return;let n=t.content,e=n==null?void 0:n.parts;if(!Array.isArray(e))return;let o=[];for(let r of e)r&&typeof r=="object"&&typeof r.text=="string"&&o.push(r.text);return o.length>0?o.join(""):void 0}function ss(t){var o,r,i,l;if(!t||typeof t!="object")return[];let n=(o=t.citations)!=null?o:[],e=[];for(let d of n){if(!d||typeof d!="object")continue;let u=(r=d.uri)!=null?r:"";if(!u)continue;let _=(i=d.startIndex)!=null?i:0,m=(l=d.endIndex)!=null?l:0;e.push({type:"url_citation",url:u,title:u,start_index:_,end_index:m})}return e}function rs(t,n){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,o=t.citationMetadata,r=as(e,n),i=ss(o);return[...r,...i]}function as(t,n){var d,u,_,m,b,R,x,P,T;let e=t&&typeof t=="object"?(d=t.groundingChunks)!=null?d:[]:[],o=t&&typeof t=="object"?(u=t.groundingSupports)!=null?u:[]:[];function r(h,w,f){let g=h.text;if(g!=null&&g!=="")return g;if(n!=null&&f>w)return n.slice(w,f)||void 0}if(o.length>0&&e.length>0){let h=[],w=new Set;for(let f of o){if(!f||typeof f!="object")continue;let g=(_=f.segment)!=null?_:{},C=(m=f.groundingChunkIndices)!=null?m:[],M=(b=g.startIndex)!=null?b:0,W=(R=g.endIndex)!=null?R:0,I=r(g,M,W);for(let N of C){if(typeof N!="number"||N>=e.length)continue;let j=e[N];if(!j||typeof j!="object")continue;let L=j.maps;if(L&&typeof L=="object"){let G=(x=L.uri)!=null?x:"",Z=(P=L.title)!=null?P:"",J=L.placeId;(G||Z)&&h.push(E(Y(E({type:"map_citation",url:G,title:Z||G},J!=null?{place_id:J}:{}),{start_index:M,end_index:W}),I!=null?{cited_text:I}:{}));continue}let B=j.retrievedContext;if(B&&typeof B=="object"){let G=(T=B.title)!=null?T:"";G&&!w.has(G)&&(w.add(G),h.push({type:"file_citation",file_id:G,filename:G,index:N}));continue}let{uri:$,title:X}=Vn(j);$&&h.push(E({type:"url_citation",url:$,title:X||$,start_index:M,end_index:W},I!=null?{cited_text:I}:{}))}}return h}if(!t||typeof t!="object")return[];let i=[],l=new Set;return e.forEach((h,w)=>{var I,N,j;if(!h||typeof h!="object")return;let f=h,g=f.maps;if(g&&typeof g=="object"){let L=(I=g.uri)!=null?I:"",B=(N=g.title)!=null?N:"",$=g.placeId;(L||B)&&i.push(Y(E({type:"map_citation",url:L,title:B||L},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let C=f.retrievedContext;if(C&&typeof C=="object"){let L=(j=C.title)!=null?j:"";L&&!l.has(L)&&(l.add(L),i.push({type:"file_citation",file_id:L,filename:L,index:w}));return}let{uri:M,title:W}=Vn(f);M&&i.push({type:"url_citation",url:M,title:W||M,start_index:0,end_index:0})}),i}var Yn=(t,n)=>{var u,_,m,b,R,x,P,T,h;let e=[],o=[];for(let w of(u=t.candidates)!=null?u:[])if(w.content&&w.content.parts&&Array.isArray(w.content.parts))for(let f of w.content.parts)if(f.text!=null)f.thought===!0?e.push(y({type:"thinking",thinking:f.text,signature:(_=f.thoughtSignature)!=null?_:""})):e.push(y(E({type:"text",text:f.text},f.thoughtSignature?{thought_signature:f.thoughtSignature}:{})));else if(f.functionCall)o.push(st(f.functionCall.id||"",f.functionCall.name||"",f.functionCall.args||{}));else if(f.executableCode){let g=f.executableCode;e.push(y(E({type:"code",code:(m=g.code)!=null?m:""},g.language!=null?{language:g.language}:{})))}else if(f.codeExecutionResult){let g=f.codeExecutionResult;e.push(y({type:"code_execution_result",output:(b=g.output)!=null?b:"",outcome:(R=g.outcome)!=null?R:"OUTCOME_OK"}))}else{let g=f.inlineData;if(g&&f.thought!==!0){let C=(x=g.mimeType)!=null?x:"image/png",M=(P=g.data)!=null?P:"";if(ns(C)&&M){let W={};f.thoughtSignature&&(W.thought_signature=f.thoughtSignature),f.aspectRatio!=null&&(W.aspect_ratio=f.aspectRatio),f.imageSize!=null&&(W.image_size=f.imageSize),e.push(y(E({type:"output_media",url:M,mime_type:C,media_type:"image"},Object.keys(W).length?{provider_metadata:W}:{})))}}}let r=(T=t.candidates)==null?void 0:T[0],i=os(r),l=rs(r,i);if(l.length>0)for(let w=0;w<e.length;w++){let f=e[w];if(f&&typeof f=="object"&&f.type==="text"){let g=(h=f.annotations)!=null?h:[];e[w]=Y(E({},f),{annotations:[...g,...l]})}}let d=Pt(e,o);return At(d,n)},un=(t,n)=>{let e=[],o=[];for(let i of t.choices)if(i.delta){i.delta.content&&e.push(y({type:"text",text:i.delta.content}));let l=i.delta.tool_calls||i.delta.toolCalls;if(l&&Array.isArray(l))for(let d of l)d.function&&o.push(st(d.id||"",d.function.name||"",d.function.arguments||""))}let r=Pt(e,o);return At(r,n)},Hn=(t,n)=>{var l,d,u,_,m,b,R,x,P,T,h,w,f,g,C,M,W,I,N,j,L,B,$,X,G,Z,J,rt,at,D,nt,it,gt,yt,ht,bt,Rt,xt,wt,Tt,ot,q,V,v,lt,tt,et,kt,St,It,Ct,Nt,Lt,qt,Mt,Ut,Wt,jt,$t,Kt,Gt,Dt,Ft,Bt,zt,Vt,Jt,Yt,Ht,Xt,Zt,Qt,vt,te,ee,ne,oe,se,re,ae,ie,le,ce,pe,ue,de,_e,me,fe,ge,ye,he,be,Re,xe,we,Te,Ee,Pe,Ae,Oe,ke,Se,Ie,Ce,Ne,Le,qe,Me,Ue,We,je,$e,Ke,Ge,De,Fe,Be,ze,Ve,Je,Ye,A,U,a,c,O,ct,xn,wn,Tn,En,Pn,An,On,kn,Sn,In,Cn,Nn,Ln,qn,Mn,Un,Wn,jn,$n,Kn;let e=[],o=[],r=t==null?void 0:t.type;if(r==="response.reasoning_summary_text.delta"){let s=(l=t==null?void 0:t.delta)!=null?l:"",k=(d=t==null?void 0:t.item_id)!=null?d:"";s&&e.push(y({type:"thinking",item_id:k,thinking:s,signature:""}))}else if(r==="response.reasoning_summary_text.done"){let s=(u=t==null?void 0:t.text)!=null?u:"",k=(_=t==null?void 0:t.item_id)!=null?_:"";s&&e.push(y({type:"thinking",item_id:k,thinking:s,signature:""}))}else if(r==="response.reasoning_summary_part.added"){let s=(m=t==null?void 0:t.part)!=null?m:{},k=(b=t==null?void 0:t.item_id)!=null?b:"";if((s==null?void 0:s.type)==="summary_text"){let p=(R=s==null?void 0:s.text)!=null?R:"";e.push(y({type:"thinking",item_id:k,thinking:p,signature:""}))}}else if(r==="response.reasoning_summary_part.done"){let s=(x=t==null?void 0:t.part)!=null?x:{},k=(P=t==null?void 0:t.item_id)!=null?P:"";if((s==null?void 0:s.type)==="summary_text"){let p=(T=s==null?void 0:s.text)!=null?T:"";p&&e.push(y({type:"thinking",item_id:k,thinking:p,signature:""}))}}else if(r==="response.function_call_arguments.delta"){let s=(h=t==null?void 0:t.item_id)!=null?h:"",k=(w=t==null?void 0:t.delta)!=null?w:"";k&&o.push(st("","",k,s))}else if(r==="response.function_call_arguments.done"){let s=(f=t==null?void 0:t.item_id)!=null?f:"",k=(g=t==null?void 0:t.arguments)!=null?g:"";k&&o.push(st("","",k,s))}else if(r==="response.output_item.added"){let s=(C=t==null?void 0:t.item)!=null?C:{},k=s==null?void 0:s.type,p=(M=s==null?void 0:s.id)!=null?M:"";k==="reasoning"?e.push(y({type:"thinking",thinking:"",signature:"",item_id:p})):k==="function_call"?o.push(st((s==null?void 0:s.call_id)||"",(s==null?void 0:s.name)||"","",p)):k==="message"?e.push(y({type:"text",item_id:p,text:""})):k==="code_interpreter_call"?e.push(y({type:"code",item_id:p,code:(W=s==null?void 0:s.code)!=null?W:"",container_id:(I=s==null?void 0:s.container_id)!=null?I:""})):k==="image_generation_call"?e.push(y({type:"output_media",item_id:p,url:"",mime_type:"image/png",media_type:"image"})):k==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:p,server_label:(N=s==null?void 0:s.server_label)!=null?N:"",tools:(j=s==null?void 0:s.tools)!=null?j:[]})):k==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(L=s==null?void 0:s.name)!=null?L:"",server_label:(B=s==null?void 0:s.server_label)!=null?B:"",arguments:($=s==null?void 0:s.arguments)!=null?$:"",output:s==null?void 0:s.output,error:s==null?void 0:s.error,approval_request_id:s==null?void 0:s.approval_request_id})):k==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:p,name:(X=s==null?void 0:s.name)!=null?X:"",arguments:(G=s==null?void 0:s.arguments)!=null?G:"",server_label:(Z=s==null?void 0:s.server_label)!=null?Z:""})):k==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(J=s==null?void 0:s.call_id)!=null?J:"",action:(rt=s==null?void 0:s.action)!=null?rt:{},status:(at=s==null?void 0:s.status)!=null?at:"in_progress"})):k==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(D=s==null?void 0:s.call_id)!=null?D:"",output:(nt=s==null?void 0:s.output)!=null?nt:[],status:(it=s==null?void 0:s.status)!=null?it:"in_progress"})):k==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(gt=s==null?void 0:s.call_id)!=null?gt:"",operation:(yt=s==null?void 0:s.operation)!=null?yt:{},status:(ht=s==null?void 0:s.status)!=null?ht:"in_progress"})):k==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(bt=s==null?void 0:s.call_id)!=null?bt:"",output:(Rt=s==null?void 0:s.output)!=null?Rt:"",status:(xt=s==null?void 0:s.status)!=null?xt:"in_progress"}))}else if(r==="response.content_part.added"){let s=(wt=t==null?void 0:t.part)!=null?wt:{},k=(Tt=s==null?void 0:s.type)!=null?Tt:"output_text",p=(ot=t==null?void 0:t.item_id)!=null?ot:"";k==="output_text"&&e.push(y({type:"text",item_id:p,text:(q=s==null?void 0:s.text)!=null?q:"",annotations:(s==null?void 0:s.annotations)||[]}))}else if(r==="response.content_part.done"){let s=(V=t==null?void 0:t.part)!=null?V:{},k=(v=s==null?void 0:s.type)!=null?v:"output_text",p=(lt=t==null?void 0:t.item_id)!=null?lt:"";k==="output_text"&&e.push(y({type:"text",item_id:p,text:(tt=s==null?void 0:s.text)!=null?tt:"",annotations:(s==null?void 0:s.annotations)||[]}))}else if(r==="response.output_text.annotation.added"){let s=(t==null?void 0:t.annotation)||{},k=s==null?void 0:s.type,p=null;k==="url_citation"?p={type:"url_citation",title:(et=s==null?void 0:s.title)!=null?et:"",url:(kt=s==null?void 0:s.url)!=null?kt:"",start_index:(St=s==null?void 0:s.start_index)!=null?St:0,end_index:(It=s==null?void 0:s.end_index)!=null?It:0}:k==="file_citation"?p={type:"file_citation",index:(Ct=s==null?void 0:s.index)!=null?Ct:0,file_id:(Nt=s==null?void 0:s.file_id)!=null?Nt:"",filename:(Lt=s==null?void 0:s.filename)!=null?Lt:""}:p=s,e.push(y({type:"text",item_id:(qt=t==null?void 0:t.item_id)!=null?qt:"",text:"",annotations:[p]}))}else if(r==="response.code_interpreter_call.in_progress")e.push(y({type:"code",item_id:(Mt=t==null?void 0:t.item_id)!=null?Mt:"",code:(Ut=t==null?void 0:t.code)!=null?Ut:"",container_id:(Wt=t==null?void 0:t.container_id)!=null?Wt:""}));else if(r==="response.code_interpreter_call_code.delta")e.push(y({type:"code",item_id:(jt=t==null?void 0:t.item_id)!=null?jt:"",code:($t=t==null?void 0:t.delta)!=null?$t:"",container_id:(Kt=t==null?void 0:t.container_id)!=null?Kt:""}));else if(r==="response.output_text.delta"){let s=(Gt=t==null?void 0:t.delta)!=null?Gt:"";s&&e.push(y({type:"text",item_id:(Dt=t==null?void 0:t.item_id)!=null?Dt:"",text:s}))}else if(r==="response.output_text.done")e.push(y({type:"text",item_id:(Ft=t==null?void 0:t.item_id)!=null?Ft:"",text:(Bt=t==null?void 0:t.text)!=null?Bt:""}));else if(r==="response.output_item.done"){let s=(zt=t==null?void 0:t.item)!=null?zt:{},k=s==null?void 0:s.type,p=(Vt=s==null?void 0:s.id)!=null?Vt:"";if(k==="reasoning"){let K=((Jt=s==null?void 0:s.summary)!=null?Jt:[]).map(pt=>{var z;return(z=pt==null?void 0:pt.text)!=null?z:""}).join("");e.push(y({type:"thinking",item_id:p,thinking:K,signature:""}))}else if(k==="function_call")o.push(st((s==null?void 0:s.call_id)||"",(s==null?void 0:s.name)||"",(s==null?void 0:s.arguments)||"",p));else if(k==="message"){let F=(Yt=s==null?void 0:s.content)!=null?Yt:[];for(let K of F)(K==null?void 0:K.type)==="output_text"&&e.push(y({type:"text",item_id:p,text:(Ht=K==null?void 0:K.text)!=null?Ht:""}))}else if(k==="code_interpreter_call")e.push(y({type:"code",item_id:p,code:(Xt=s==null?void 0:s.code)!=null?Xt:"",container_id:(Zt=s==null?void 0:s.container_id)!=null?Zt:""}));else if(k==="image_generation_call"){let F=(Qt=s==null?void 0:s.result)!=null?Qt:"",pt=((vt=s==null?void 0:s.output_format)!=null?vt:"png")==="webp"?"image/webp":"image/png",z={};for(let mt of["revised_prompt","background","size","quality","output_format"])(s==null?void 0:s[mt])!=null&&(z[mt]=s[mt]);e.push(y(E({type:"output_media",item_id:p,url:F,mime_type:pt,media_type:"image"},Object.keys(z).length?{provider_metadata:z}:{})))}else k==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:p,server_label:(te=s==null?void 0:s.server_label)!=null?te:"",tools:(ee=s==null?void 0:s.tools)!=null?ee:[],error:s==null?void 0:s.error})):k==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(ne=s==null?void 0:s.name)!=null?ne:"",server_label:(oe=s==null?void 0:s.server_label)!=null?oe:"",arguments:(se=s==null?void 0:s.arguments)!=null?se:"",output:s==null?void 0:s.output,error:s==null?void 0:s.error,approval_request_id:s==null?void 0:s.approval_request_id})):k==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:p,name:(re=s==null?void 0:s.name)!=null?re:"",arguments:(ae=s==null?void 0:s.arguments)!=null?ae:"",server_label:(ie=s==null?void 0:s.server_label)!=null?ie:""})):k==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(le=s==null?void 0:s.call_id)!=null?le:"",action:(ce=s==null?void 0:s.action)!=null?ce:{},status:(pe=s==null?void 0:s.status)!=null?pe:"completed"})):k==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(ue=s==null?void 0:s.call_id)!=null?ue:"",output:(de=s==null?void 0:s.output)!=null?de:[],status:(_e=s==null?void 0:s.status)!=null?_e:"completed"})):k==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(me=s==null?void 0:s.call_id)!=null?me:"",operation:(fe=s==null?void 0:s.operation)!=null?fe:{},status:(ge=s==null?void 0:s.status)!=null?ge:"completed"})):k==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(ye=s==null?void 0:s.call_id)!=null?ye:"",output:(he=s==null?void 0:s.output)!=null?he:"",status:(be=s==null?void 0:s.status)!=null?be:"completed"}))}else if(r==="response.code_interpreter_call_code.done")e.push(y({type:"code",item_id:(Re=t==null?void 0:t.item_id)!=null?Re:"",code:(xe=t==null?void 0:t.code)!=null?xe:"",container_id:(we=t==null?void 0:t.container_id)!=null?we:""}));else if(r==="response.code_interpreter_call.interpreting")e.push(y({type:"code",item_id:(Te=t==null?void 0:t.item_id)!=null?Te:"",code:(Ee=t==null?void 0:t.code)!=null?Ee:"",container_id:(Pe=t==null?void 0:t.container_id)!=null?Pe:""}));else if(r==="response.code_interpreter_call.completed")e.push(y({type:"code",item_id:(Ae=t==null?void 0:t.item_id)!=null?Ae:"",code:(Oe=t==null?void 0:t.code)!=null?Oe:"",container_id:(ke=t==null?void 0:t.container_id)!=null?ke:""}));else if(r==="response.image_generation_call.in_progress")e.push(y({type:"output_media",item_id:(Se=t==null?void 0:t.item_id)!=null?Se:"",url:"",mime_type:"image/png",media_type:"image"}));else if(r==="response.image_generation_call.generating")e.push(y({type:"output_media",item_id:(Ie=t==null?void 0:t.item_id)!=null?Ie:"",url:"",mime_type:"image/png",media_type:"image"}));else if(r==="response.image_generation_call.partial_image"){let k=((Ce=t==null?void 0:t.output_format)!=null?Ce:"png")==="webp"?"image/webp":"image/png",p={};for(let F of["background","size","quality","output_format"])(t==null?void 0:t[F])!=null&&(p[F]=t[F]);e.push(y(E({type:"output_media",item_id:(Ne=t==null?void 0:t.item_id)!=null?Ne:"",url:(Le=t==null?void 0:t.partial_image_b64)!=null?Le:"",mime_type:k,media_type:"image"},Object.keys(p).length?{provider_metadata:p}:{})))}else if(r==="response.shell_call_command.added")e.push(y({type:"shell_call",action:{command:(qe=t==null?void 0:t.command)!=null?qe:""}}));else if(r==="response.shell_call_command.delta")e.push(y({type:"shell_call",action:{command:(Me=t==null?void 0:t.delta)!=null?Me:""}}));else if(r==="response.shell_call_command.done")e.push(y({type:"shell_call",action:{command:(Ue=t==null?void 0:t.command)!=null?Ue:""}}));else if(r==="response.shell_call_output_content.delta")e.push(y({type:"shell_call_output",item_id:(We=t==null?void 0:t.item_id)!=null?We:"",output:[(je=t==null?void 0:t.delta)!=null?je:{}]}));else if(r==="response.shell_call_output_content.done")e.push(y({type:"shell_call_output",item_id:($e=t==null?void 0:t.item_id)!=null?$e:"",output:(Ke=t==null?void 0:t.output)!=null?Ke:[]}));else if(r==="response.apply_patch_call_operation_diff.delta")e.push(y({type:"apply_patch_call",item_id:(Ge=t==null?void 0:t.item_id)!=null?Ge:"",operation:{diff:(De=t==null?void 0:t.delta)!=null?De:""}}));else if(r==="response.apply_patch_call_operation_diff.done")e.push(y({type:"apply_patch_call",item_id:(Fe=t==null?void 0:t.item_id)!=null?Fe:"",operation:{diff:(Be=t==null?void 0:t.diff)!=null?Be:""}}));else if(r==="response.completed"){let s=(ze=t==null?void 0:t.response)!=null?ze:{},k=(Ve=s==null?void 0:s.output)!=null?Ve:[];for(let p of k){let F=p==null?void 0:p.type,K=(Je=p==null?void 0:p.id)!=null?Je:"";if(F==="reasoning"){let z=((Ye=p==null?void 0:p.summary)!=null?Ye:[]).map(mt=>{var Et;return(Et=mt==null?void 0:mt.text)!=null?Et:""}).join("");e.push(y({type:"thinking",item_id:K,thinking:z,signature:""}))}else if(F==="function_call")o.push(st((p==null?void 0:p.call_id)||"",(p==null?void 0:p.name)||"",(p==null?void 0:p.arguments)||"",K));else if(F==="message"){let pt=(A=p==null?void 0:p.content)!=null?A:[];for(let z of pt)(z==null?void 0:z.type)==="output_text"&&e.push(y({type:"text",item_id:K,text:(U=z==null?void 0:z.text)!=null?U:"",annotations:(z==null?void 0:z.annotations)||[]}))}else if(F==="code_interpreter_call")e.push(y({type:"code",item_id:K,code:(a=p==null?void 0:p.code)!=null?a:"",container_id:(c=p==null?void 0:p.container_id)!=null?c:""}));else if(F==="image_generation_call"){let pt=(O=p==null?void 0:p.result)!=null?O:"",mt=((ct=p==null?void 0:p.output_format)!=null?ct:"png")==="webp"?"image/webp":"image/png",Et={};for(let ln of["revised_prompt","background","size","quality","output_format"])(p==null?void 0:p[ln])!=null&&(Et[ln]=p[ln]);e.push(y(E({type:"output_media",item_id:K,url:pt,mime_type:mt,media_type:"image"},Object.keys(Et).length?{provider_metadata:Et}:{})))}else F==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:K,server_label:(xn=p==null?void 0:p.server_label)!=null?xn:"",tools:(wn=p==null?void 0:p.tools)!=null?wn:[],error:p==null?void 0:p.error})):F==="mcp_call"?e.push(y({type:"mcp_call",item_id:K,name:(Tn=p==null?void 0:p.name)!=null?Tn:"",server_label:(En=p==null?void 0:p.server_label)!=null?En:"",arguments:(Pn=p==null?void 0:p.arguments)!=null?Pn:"",output:p==null?void 0:p.output,error:p==null?void 0:p.error,approval_request_id:p==null?void 0:p.approval_request_id})):F==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:K,name:(An=p==null?void 0:p.name)!=null?An:"",arguments:(On=p==null?void 0:p.arguments)!=null?On:"",server_label:(kn=p==null?void 0:p.server_label)!=null?kn:""})):F==="shell_call"?e.push(y({type:"shell_call",item_id:K,call_id:(Sn=p==null?void 0:p.call_id)!=null?Sn:"",action:(In=p==null?void 0:p.action)!=null?In:{},status:(Cn=p==null?void 0:p.status)!=null?Cn:"completed"})):F==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:K,call_id:(Nn=p==null?void 0:p.call_id)!=null?Nn:"",output:(Ln=p==null?void 0:p.output)!=null?Ln:[],status:(qn=p==null?void 0:p.status)!=null?qn:"completed"})):F==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:K,call_id:(Mn=p==null?void 0:p.call_id)!=null?Mn:"",operation:(Un=p==null?void 0:p.operation)!=null?Un:{},status:(Wn=p==null?void 0:p.status)!=null?Wn:"completed"})):F==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:K,call_id:(jn=p==null?void 0:p.call_id)!=null?jn:"",output:($n=p==null?void 0:p.output)!=null?$n:"",status:(Kn=p==null?void 0:p.status)!=null?Kn:"completed"}))}}let i=Pt(e,o||[]);return At(i,n)},Xn=(t,n)=>{var i,l,d,u;let e=[],o=[];if("contentBlockDelta"in t){let _=((i=t.contentBlockDelta)==null?void 0:i.delta)||{};if("reasoningContent"in _){let m=((l=_.reasoningContent)==null?void 0:l.text)||"",b=((d=_.reasoningContent)==null?void 0:d.signature)||"";e.push(y({type:"thinking",thinking:m,signature:b}))}else if("text"in _)e.push(y({type:"text",text:_.text||""}));else if("toolUse"in _){let m=_.toolUse||{};o.push(st(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in t){let _=((u=t.contentBlockStart)==null?void 0:u.start)||{};if("toolUse"in _){let m=_.toolUse||{};o.push(st(m.toolUseId||"",m.name||"",""))}}let r=Pt(e,o);return At(r,n)},is=["size","quality","background","output_format"],Zn=(t,n)=>{var i,l,d,u,_,m,b;let e=[],o=(i=t==null?void 0:t.type)!=null?i:"";if(o==="image_generation.partial_image"){let R=(l=t==null?void 0:t.b64_json)!=null?l:"";if(R){let x=(d=t==null?void 0:t.output_format)!=null?d:"png",P=(u=Bn[x])!=null?u:"image/png",T={},h=t==null?void 0:t.partial_image_index;h!=null&&(T.partial_image_index=h),e.push(y(E({type:"output_media",url:R,mime_type:P,media_type:"image"},Object.keys(T).length?{provider_metadata:T}:{})))}}else if(o==="image_generation.completed"){let R=(_=t==null?void 0:t.b64_json)!=null?_:"",x=(m=t==null?void 0:t.output_format)!=null?m:"png",P=(b=Bn[x])!=null?b:"image/png",T={};for(let h of is)(t==null?void 0:t[h])!=null&&(T[h]=t[h]);e.push(y(E({type:"output_media",url:R,mime_type:P,media_type:"image"},Object.keys(T).length?{provider_metadata:T}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:n}};var no=["openai","openai.azure"],en=t=>{var r,i,l,d,u,_,m,b,R,x,P,T,h,w,f,g,C,M,W,I,N,j,L,B,$,X,G,Z,J,rt,at,D,nt,it,gt,yt,ht,bt,Rt,xt,wt,Tt,ot,q,V,v,lt,tt,et,kt,St,It,Ct,Nt,Lt,qt,Mt,Ut,Wt,jt,$t,Kt,Gt,Dt,Ft,Bt,zt,Vt,Jt,Yt,Ht,Xt,Zt,Qt,vt,te,ee,ne,oe,se,re,ae,ie,le,ce,pe,ue,de,_e,me,fe,ge,ye,he,be,Re,xe,we,Te,Ee,Pe,Ae,Oe,ke,Se,Ie,Ce,Ne,Le,qe,Me,Ue,We,je,$e,Ke,Ge,De,Fe,Be,ze,Ve,Je,Ye;let n={id:null,object:"response",created_at:null,status:null,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:null,output:[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{},store:!0,temperature:1,text:void 0,tool_choice:"auto",tools:[],top_p:1,truncation:"disabled",usage:null,user:null,metadata:{}},e={},o={};for(let A of t){let U=A==null?void 0:A.type;if(U==="response.created"){let a=A.response||{};n.id=(r=a.id)!=null?r:n.id,n.created_at=(i=a.created_at)!=null?i:n.created_at,n.model=(l=a.model)!=null?l:n.model,n.status=(d=a.status)!=null?d:n.status,n.parallel_tool_calls=(u=a.parallel_tool_calls)!=null?u:n.parallel_tool_calls,n.temperature=(_=a.temperature)!=null?_:n.temperature,n.tool_choice=(m=a.tool_choice)!=null?m:n.tool_choice,n.tools=(b=a.tools)!=null?b:n.tools,n.top_p=(R=a.top_p)!=null?R:n.top_p,n.truncation=(x=a.truncation)!=null?x:n.truncation,n.max_output_tokens=(P=a.max_output_tokens)!=null?P:n.max_output_tokens,n.previous_response_id=(T=a.previous_response_id)!=null?T:n.previous_response_id,n.store=(h=a.store)!=null?h:n.store,n.user=(w=a.user)!=null?w:n.user,n.metadata=(f=a.metadata)!=null?f:n.metadata;let c=a.text;c&&(n.text=c);let O=a.reasoning;O&&(n.reasoning=O);continue}if(U==="response.in_progress"){let a=A.response||{};n.status=(g=a.status)!=null?g:n.status;continue}if(U==="response.output_item.added"){let a=A.item||{},c=a.id,O=a.type,ct=A.output_index;ct!=null&&c&&(o[ct]=c),O==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(C=a.status)!=null?C:"in_progress"}:O==="function_call"?e[c]={type:"function_call",id:c,call_id:a.call_id,name:a.name,arguments:"",status:(M=a.status)!=null?M:"in_progress"}:O==="message"?e[c]={type:"message",id:c,role:(W=a.role)!=null?W:"assistant",content:[],status:(I=a.status)!=null?I:"in_progress"}:O==="code_interpreter_call"?e[c]={type:"code_interpreter_call",id:c,container_id:a.container_id,code:(N=a.code)!=null?N:"",status:(j=a.status)!=null?j:"in_progress"}:O==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(L=a.status)!=null?L:"in_progress",revised_prompt:(B=a.revised_prompt)!=null?B:"",result:($=a.result)!=null?$:"",background:a.background,size:a.size,quality:a.quality,output_format:a.output_format}:O==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(X=a.status)!=null?X:"in_progress"}:O==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(G=a.status)!=null?G:"in_progress"}:O==="mcp_list_tools"?e[c]={type:"mcp_list_tools",id:c,server_label:(Z=a.server_label)!=null?Z:"",tools:(J=a.tools)!=null?J:[],error:(rt=a.error)!=null?rt:null}:O==="mcp_call"?e[c]={type:"mcp_call",id:c,name:(at=a.name)!=null?at:"",server_label:(D=a.server_label)!=null?D:"",arguments:(nt=a.arguments)!=null?nt:"",output:(it=a.output)!=null?it:null,error:(gt=a.error)!=null?gt:null,approval_request_id:(yt=a.approval_request_id)!=null?yt:null,status:(ht=a.status)!=null?ht:"in_progress"}:O==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(bt=a.name)!=null?bt:"",arguments:(Rt=a.arguments)!=null?Rt:"",server_label:(xt=a.server_label)!=null?xt:""}:O==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(wt=a.call_id)!=null?wt:"",action:(Tt=a.action)!=null?Tt:{},status:(ot=a.status)!=null?ot:"in_progress"}:O==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(q=a.call_id)!=null?q:"",output:(V=a.output)!=null?V:[],status:(v=a.status)!=null?v:"in_progress"}:O==="apply_patch_call"?e[c]={type:"apply_patch_call",id:c,call_id:(lt=a.call_id)!=null?lt:"",operation:(tt=a.operation)!=null?tt:{},status:(et=a.status)!=null?et:"in_progress"}:O==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(kt=a.call_id)!=null?kt:"",output:(St=a.output)!=null?St:"",status:(It=a.status)!=null?It:"in_progress"});continue}if(U==="response.reasoning_summary_part.added"){let a=A.item_id,c=A.part||{};if(a in e&&e[a].type==="reasoning"){let O={type:(Ct=c.type)!=null?Ct:"summary_text",text:(Nt=c.text)!=null?Nt:""};e[a].summary.push(O)}continue}if(U==="response.reasoning_summary_text.delta"){let a=A.item_id,c=(Lt=A.delta)!=null?Lt:"",O=(qt=A.summary_index)!=null?qt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=O;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[O].text+=c}continue}if(U==="response.reasoning_summary_text.done"){let a=A.item_id,c=(Mt=A.text)!=null?Mt:"",O=(Ut=A.summary_index)!=null?Ut:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=O;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[O].text=c}continue}if(U==="response.reasoning_summary_part.done"){let a=A.item_id,c=A.part||{};if(a in e&&e[a].type==="reasoning"){let O=(Wt=A.summary_index)!=null?Wt:0;O<e[a].summary.length&&(e[a].summary[O]={type:(jt=c.type)!=null?jt:"summary_text",text:($t=c.text)!=null?$t:""})}continue}if(U==="response.function_call_arguments.delta"){let a=A.item_id,c=(Kt=A.delta)!=null?Kt:"";a in e&&(e[a].arguments=`${e[a].arguments||""}${c}`);continue}if(U==="response.function_call_arguments.done"){let a=A.item_id,c=(Gt=A.arguments)!=null?Gt:"";a in e&&(e[a].arguments=c);continue}if(U==="response.content_part.added"){let a=A.part||{},c=Object.values(e).find(O=>O.type==="message");if(c){let O={type:(Dt=a.type)!=null?Dt:"output_text",text:(Ft=a.text)!=null?Ft:"",annotations:(Bt=a.annotations)!=null?Bt:[]};c.content.push(O)}continue}if(U==="response.output_text.delta"){let a=(zt=A.delta)!=null?zt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let O=c.content[c.content.length-1];O&&O.type==="output_text"&&(O.text=`${O.text||""}${a}`);break}continue}if(U==="response.output_text.done"){let a=(Vt=A.text)!=null?Vt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let O=c.content[c.content.length-1];O&&O.type==="output_text"&&(O.text=a);break}continue}if(U==="response.output_item.done"){let a=A.item||{},c=a.id;c in e&&(e[c].status=(Jt=a.status)!=null?Jt:"completed",a.type==="reasoning"?e[c].summary=(Yt=a.summary)!=null?Yt:e[c].summary:a.type==="function_call"?(e[c].arguments=(Ht=a.arguments)!=null?Ht:e[c].arguments,e[c].call_id=(Xt=a.call_id)!=null?Xt:e[c].call_id,e[c].name=(Zt=a.name)!=null?Zt:e[c].name):a.type==="message"?(e[c].content=(Qt=a.content)!=null?Qt:e[c].content,e[c].role=(vt=a.role)!=null?vt:e[c].role):a.type==="image_generation_call"?(e[c].result=(te=a.result)!=null?te:e[c].result,e[c].revised_prompt=(ee=a.revised_prompt)!=null?ee:e[c].revised_prompt,e[c].background=(ne=a.background)!=null?ne:e[c].background,e[c].size=(oe=a.size)!=null?oe:e[c].size,e[c].quality=(se=a.quality)!=null?se:e[c].quality,e[c].output_format=(re=a.output_format)!=null?re:e[c].output_format):a.type==="code_interpreter_call"?(e[c].code=(ae=a.code)!=null?ae:e[c].code,e[c].container_id=(ie=a.container_id)!=null?ie:e[c].container_id):a.type==="mcp_list_tools"?(e[c].tools=(le=a.tools)!=null?le:e[c].tools,e[c].error=(ce=a.error)!=null?ce:e[c].error):a.type==="mcp_call"?(e[c].name=(pe=a.name)!=null?pe:e[c].name,e[c].arguments=(ue=a.arguments)!=null?ue:e[c].arguments,e[c].output=(de=a.output)!=null?de:e[c].output,e[c].error=(_e=a.error)!=null?_e:e[c].error,e[c].server_label=(me=a.server_label)!=null?me:e[c].server_label):a.type==="mcp_approval_request"?(e[c].name=(fe=a.name)!=null?fe:e[c].name,e[c].arguments=(ge=a.arguments)!=null?ge:e[c].arguments,e[c].server_label=(ye=a.server_label)!=null?ye:e[c].server_label):a.type==="shell_call"?(e[c].action=(he=a.action)!=null?he:e[c].action,e[c].call_id=(be=a.call_id)!=null?be:e[c].call_id):a.type==="shell_call_output"?(e[c].output=(Re=a.output)!=null?Re:e[c].output,e[c].call_id=(xe=a.call_id)!=null?xe:e[c].call_id):a.type==="apply_patch_call"?(e[c].operation=(we=a.operation)!=null?we:e[c].operation,e[c].call_id=(Te=a.call_id)!=null?Te:e[c].call_id):a.type==="apply_patch_call_output"?(e[c].output=(Ee=a.output)!=null?Ee:e[c].output,e[c].call_id=(Pe=a.call_id)!=null?Pe:e[c].call_id):(a.type==="web_search_call"||a.type==="file_search_call")&&(e[c].action=a.action),n.output.push(e[c]));continue}if(U==="response.image_generation_call.in_progress"){let a=A.item_id;a in e&&(e[a].status="in_progress");continue}if(U==="response.image_generation_call.generating"){let a=A.item_id;a in e&&(e[a].status="generating");continue}if(U==="response.image_generation_call.partial_image"){let a=A.item_id;a in e&&(e[a].result=(Ae=A.partial_image_b64)!=null?Ae:e[a].result,e[a].background=(Oe=A.background)!=null?Oe:e[a].background,e[a].size=(ke=A.size)!=null?ke:e[a].size,e[a].quality=(Se=A.quality)!=null?Se:e[a].quality,e[a].output_format=(Ie=A.output_format)!=null?Ie:e[a].output_format);continue}if(U==="response.shell_call_command.added"){let a=o[A.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[A.command_index]=(Ce=A.command)!=null?Ce:"",e[a].action=c}continue}if(U==="response.shell_call_command.delta"){let a=o[A.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]);let O=(Ne=A.command_index)!=null?Ne:0;c.commands[O]=((Le=c.commands[O])!=null?Le:"")+((qe=A.delta)!=null?qe:""),e[a].action=c}continue}if(U==="response.shell_call_command.done"){let a=o[A.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[A.command_index]=(Me=A.command)!=null?Me:"",e[a].action=c}continue}if(U==="response.shell_call_output_content.delta"){let a=A.item_id;if(a&&a in e){e[a].output||(e[a].output=[]);let c=(Ue=A.command_index)!=null?Ue:0,O=(We=e[a].output[c])!=null?We:{stdout:"",stderr:""},ct=(je=A.delta)!=null?je:{};ct.stdout&&(O.stdout=(($e=O.stdout)!=null?$e:"")+ct.stdout),ct.stderr&&(O.stderr=((Ke=O.stderr)!=null?Ke:"")+ct.stderr),e[a].output[c]=O}continue}if(U==="response.shell_call_output_content.done"){let a=A.item_id;a&&a in e&&(e[a].output=(Ge=A.output)!=null?Ge:e[a].output);continue}if(U==="response.apply_patch_call_operation_diff.delta"){let a=A.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=((De=c.diff)!=null?De:"")+((Fe=A.delta)!=null?Fe:""),e[a].operation=c}continue}if(U==="response.apply_patch_call_operation_diff.done"){let a=A.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=(Be=A.diff)!=null?Be:c.diff,e[a].operation=c}continue}if(U==="response.completed"){let a=A.response||{};n.status=(Ve=(ze=a.status)!=null?ze:n.status)!=null?Ve:"completed",n.usage=(Je=a.usage)!=null?Je:n.usage,n.output=(Ye=a.output)!=null?Ye:n.output,a.reasoning&&(n.reasoning=a.reasoning);continue}}return n},dn=t=>{var d,u,_,m,b,R,x,P,T,h;let n=null,e,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=t.at(-1);if(!r)return o;let i;for(let w of t){if(w.choices.length===0)continue;let f=w.choices[0].delta;f.content&&(n=`${n||""}${f.content||""}`),f.function_call&&(e={name:`${e?e.name:""}${f.function_call.name||""}`,arguments:`${e?e.arguments:""}${f.function_call.arguments||""}`});let g=(d=f.tool_calls)==null?void 0:d[0];if(g){i=i||[];let C=i.at(-1);if(!C||g.id){i.push({id:g.id||"",type:g.type||"function",function:{name:((u=g.function)==null?void 0:u.name)||"",arguments:((_=g.function)==null?void 0:_.arguments)||""}});continue}C.function.name=`${C.function.name}${((m=g.function)==null?void 0:m.name)||""}`,C.function.arguments=`${C.function.arguments}${((b=g.function)==null?void 0:b.arguments)||""}`}}let l=t[0].choices.at(0);return o.choices.push({finish_reason:(R=l==null?void 0:l.finish_reason)!=null?R:"stop",index:(x=l==null?void 0:l.index)!=null?x:0,logprobs:(P=l==null?void 0:l.logprobs)!=null?P:null,message:{role:"assistant",content:n,function_call:e||void 0,tool_calls:i||void 0,refusal:(T=l==null?void 0:l.delta.refusal)!=null?T:null}}),o.id=r.id,o.model=r.model,o.created=r.created,o.system_fingerprint=r.system_fingerprint,o.usage=(h=r.usage)!=null?h:void 0,o},Qn=t=>{let n={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},e=t.at(-1);if(!e)return n;let o="";for(let r of t)r.choices.length>0&&r.choices[0].text&&(o=`${o}${r.choices[0].text}`);return n.choices[0].text=o,n.id=e.id,n.created=e.created,n.model=e.model,n.system_fingerprint=e.system_fingerprint,n.usage=e.usage,n},_n=t=>{var m,b,R,x,P,T;let n={id:"",model:"",content:[],role:"assistant",type:"message",stop_reason:"stop_sequence",stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:null,service_tier:null}};if(!t.at(-1))return n;let o=null,r=null,i="",l="",d="",u="",_={};for(let h of t)if(h.type==="message_start")n=E({},h.message);else if(h.type==="content_block_start")o=E({},h.content_block),r="index"in h&&typeof h.index=="number"?h.index:null,o.type==="thinking"?(i="",l=""):o.type==="text"?d="":(o.type==="tool_use"||o.type==="server_tool_use")&&(u="");else if(h.type==="content_block_delta"){let w=h.delta,f="index"in h&&typeof h.index=="number"?h.index:null;if((w==null?void 0:w.type)==="citations_delta"){let g=w.citation;if(g&&typeof g=="object"&&g.type==="web_search_result_location"&&f!==null){let C=E(E({type:"url_citation",url:(m=g.url)!=null?m:"",title:(b=g.title)!=null?b:"",start_index:(R=g.start_index)!=null?R:0,end_index:(x=g.end_index)!=null?x:0},g.cited_text!=null?{cited_text:g.cited_text}:{}),g.encrypted_index!=null?{encrypted_index:g.encrypted_index}:{});_[f]||(_[f]=[]),_[f].push(C)}}else o!==null&&(o.type==="thinking"?(w&&"signature"in w&&(i=w.signature||""),w&&"thinking"in w&&(l+=w.thinking||"")):o.type==="text"?w&&"text"in w&&(d+=w.text||""):(o.type==="tool_use"||o.type==="server_tool_use")&&(w==null?void 0:w.type)==="input_json_delta"&&(u+=w.partial_json||""))}else if(h.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=i,o.thinking=l;else if(o.type==="text")o.text=d,o.citations=null,r!==null&&((P=_[r])!=null&&P.length)&&(o.annotations=_[r]);else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=u?JSON.parse(u):{}}catch(w){o.input={}}n.content.push(o),o=null,r=null,i="",l="",d="",u=""}else h.type==="message_delta"&&("usage"in h&&h.usage&&(n.usage=Y(E({},n.usage),{output_tokens:(T=h.usage.output_tokens)!=null?T:0})),"delta"in h&&h.delta&&("stop_reason"in h.delta&&h.delta.stop_reason!==void 0&&(n.stop_reason=h.delta.stop_reason),"stop_sequence"in h.delta&&h.delta.stop_sequence!==void 0&&(n.stop_sequence=h.delta.stop_sequence)));return n},vn=t=>{let n={completion:"",id:"",model:"",stop_reason:"",type:"completion"},e=t.at(-1);if(!e)return n;let o="";for(let r of t)o=`${o}${r.completion}`;return n.completion=o,n.id=e.id,n.model=e.model,n.stop_reason=e.stop_reason,n},ls=t=>{var l,d,u,_,m,b,R,x,P,T;let n=null,e={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=t.at(-1).data;if(!o)return e;let r;for(let h of t){if(h.data.choices.length===0)continue;let w=h.data.choices[0].delta;w.content&&(n=`${n||""}${w.content||""}`);let f=(l=w.toolCalls)==null?void 0:l[0];if(f){r=r||[];let g=r.at(-1);if(!g||f.id){r.push({id:f.id||"",type:f.type||"function",function:{name:((d=f.function)==null?void 0:d.name)||"",arguments:((u=f.function)==null?void 0:u.arguments)||""}});continue}g.function.name=`${g.function.name}${((_=f.function)==null?void 0:_.name)||""}`,g.function.arguments=`${g.function.arguments}${((m=f.function)==null?void 0:m.arguments)||""}`}}let i=t[0].data.choices.at(0);return e.choices.push({finish_reason:(b=i==null?void 0:i.finish_reason)!=null?b:"stop",index:(R=i==null?void 0:i.index)!=null?R:0,logprobs:(x=i==null?void 0:i.logprobs)!=null?x:null,message:{role:"assistant",content:n,tool_calls:r||void 0,refusal:(P=i==null?void 0:i.delta.refusal)!=null?P:null}}),e.id=o.id,e.model=o.model,e.created=o.created,e.usage=(T=o.usage)!=null?T:void 0,e},to=t=>{let n={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},e=[],o=null,r="",i="",l="",d="";for(let u of t)if("contentBlockStart"in u){let _=u.contentBlockStart;if("start"in _&&"toolUse"in _.start){let m=_.start.toolUse;o={toolUse:{toolUseId:m.toolUseId,name:m.name}},r=""}}else if("contentBlockDelta"in u){let _=u.contentBlockDelta.delta;if("text"in _)i+=_.text;else if("reasoningContent"in _){let m=_.reasoningContent;"text"in m?d+=m.text:"signature"in m&&(l+=m.signature)}else if("toolUse"in _&&"input"in _.toolUse){let m=_.toolUse.input;if(r+=m,!m.trim())continue}}else if("contentBlockStop"in u)if(o&&r){try{o.toolUse.input=JSON.parse(r)}catch(_){o.toolUse.input={}}e.push(o),o=null,r=""}else i?(e.push({text:i}),i=""):d&&l&&(e.push({reasoningContent:{reasoningText:{text:d,signature:l}}}),d="",l="");else if("messageStop"in u)n.stopReason=u.messageStop.stopReason;else if("metadata"in u){let _=u.metadata;n.usage=(_==null?void 0:_.usage)||{},n.metrics=(_==null?void 0:_.metrics)||{}}return n.output.message={role:"assistant",content:e},n},cs=(t,n,e,o,r,i,l,d,u)=>{var R,x,P;let _=E({},l),m=[];if(t){let T={text:t,thought:!0};d&&(T.thoughtSignature=d),m.push(T)}if(n){let T={text:n,thought:null};u&&(T.thoughtSignature=u),m.push(T)}for(let T of r)m.push({executableCode:T});for(let T of i)m.push({codeExecutionResult:T});for(let T of o)m.push({inlineData:T});for(let T of e)m.push({functionCall:T});m.length>0&&((x=(R=_.candidates)==null?void 0:R[0])!=null&&x.content)&&(_.candidates[0].content.parts=m);let b=(P=l==null?void 0:l.candidates)==null?void 0:P[0];return b&&(_.candidates||(_.candidates=[]),_.candidates[0]||(_.candidates[0]={content:{parts:[]}}),b.groundingMetadata!=null&&(_.candidates[0].groundingMetadata=b.groundingMetadata),b.urlContextMetadata!=null&&(_.candidates[0].urlContextMetadata=b.urlContextMetadata),b.citationMetadata!=null&&(_.candidates[0].citationMetadata=b.citationMetadata)),_},oo=t=>{var m,b,R,x,P,T,h;let{GenerateContentResponse:n}=require("@google/genai");if(!t.length)return new n;let e="",o="",r=[],i=[],l=[],d=[],u=null,_=null;for(let w of t)if(w.candidates&&((b=(m=w.candidates[0])==null?void 0:m.content)!=null&&b.parts))for(let f of w.candidates[0].content.parts)if(f.text!=null)f.thought===!0?(e+=f.text,f.thoughtSignature&&(u=f.thoughtSignature)):(o+=f.text,f.thoughtSignature&&(_=f.thoughtSignature));else if(f.functionCall)r.push(f.functionCall);else if(f.inlineData){let g=f.inlineData;i.push({data:(R=g.data)!=null?R:"",mimeType:(x=g.mimeType)!=null?x:"image/png"})}else f.executableCode?l.push({code:(P=f.executableCode.code)!=null?P:"",language:f.executableCode.language}):f.codeExecutionResult&&d.push({output:(T=f.codeExecutionResult.output)!=null?T:"",outcome:(h=f.codeExecutionResult.outcome)!=null?h:"OUTCOME_OK"});return cs(e,o,r,i,l,d,t[t.length-1],u,_)},ps=t=>oo(t),us=t=>oo(t),ds=["size","quality","background","output_format"],mn=t=>{var i,l,d,u,_;let n={created:null,data:[],usage:null},e={},o="png";for(let m of t){let b=(i=m==null?void 0:m.type)!=null?i:"";if(b==="image_generation.partial_image"){let R=m.b64_json;if(R!=null){let x=(l=m.partial_image_index)!=null?l:0;e[x]=R}}else if(b==="image_generation.completed"){let R=m.b64_json;if(R!=null){let x=(d=m.partial_image_index)!=null?d:0;e[x]=R}n.created=(u=m.created_at)!=null?u:n.created,n.usage=(_=m.usage)!=null?_:n.usage;for(let x of ds)m[x]!=null&&(n[x]=m[x]);m.output_format&&(o=m.output_format)}}n.output_format||(n.output_format=o);let r=Object.keys(e).map(Number).sort((m,b)=>m-b);return r.length>0&&(n.data=r.map(m=>({b64_json:e[m]}))),n},so=(t,n="openai.chat.completions.create")=>{if(n==="openai.responses.create"||n==="openai.AzureOpenAI.responses.create")return en(t);if(n==="openai.images.generate"||n==="openai.AzureOpenAI.images.generate")return mn(t);if("completion"in t[0])return t.reduce((e,o)=>Y(E({},o),{completion:`${e.completion}${o.completion}`}),{});if(n==="anthropic.messages.create")return _n(t);if("text"in t[0].choices[0]){let e="";for(let r of t)e=`${e}${r.choices[0].text}`;let o=structuredClone(t.at(-1));return o.choices[0].text=e,o}if("delta"in t[0].choices[0]){let e=dn(t);return e.choices[0]=E(E({},e.choices[0]),e.choices[0].message),e}return""},eo=(t,n,e)=>{let o=n.model.provider,r=n.model.name;if(o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&r.startsWith("claude"))return Jn(t,n,e==null?void 0:e.anthropicBlockTypeByIndex);if(o==="google"||o==="vertexai"&&r.startsWith("gemini"))return Yn(t,n);if(o==="amazon.bedrock")return Xn(t,n);if(o==="mistral")return un(t.data,n);if(o==="openai"||o==="openai.azure"){let i=n.model.api_type||"chat-completions";return i==="responses"?Hn(t,n):i==="images"?Zn(t,n):un(t,n)}return null};function ro(t,n,e,o){return ve(this,null,function*(){var R,x,P;let r={request_id:null,raw_response:null,prompt_blueprint:null},i={},l=o.model.provider;l=="amazon.bedrock"&&(i=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let d=[],u=l==="anthropic"||l==="anthropic.bedrock"||l==="vertexai"&&((P=(x=(R=o.model)==null?void 0:R.name)==null?void 0:x.startsWith)==null?void 0:P.call(x,"claude")),_={};try{for(var T=tn(t),h,w,f;h=!(w=yield new ft(T.next())).done;h=!1){let g=w.value;d.push(g),u&&(g==null?void 0:g.type)==="content_block_start"&&g.content_block&&(_[g.index]=g.content_block.type),r.raw_response=g,r.prompt_blueprint=eo(g,o,{anthropicBlockTypeByIndex:_}),yield r}}catch(w){f=[w]}finally{try{h&&(w=T.return)&&(yield new ft(w.call(T)))}finally{if(f)throw f[0]}}let m=e(d);l==="amazon.bedrock"&&(m.ResponseMetadata=i),r.raw_response=m,r.prompt_blueprint=eo(m,o),yield r;let b=yield new ft(n({request_response:m}));r.request_id=b.request_id,r.prompt_blueprint=b.prompt_blueprint,yield r})}var ao={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:dn},completion:{function_name:"openai.completions.create",stream_function:Qn}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:en}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:mn}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:_n},completion:{function_name:"anthropic.completions.create",stream_function:vn}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:dn},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:Qn}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:en},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:en}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:mn}},google:{chat:{function_name:"google.convo.send_message",stream_function:ps},completion:{function_name:"google.model.generate_content",stream_function:us}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:to},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:to}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:_n},completion:{function_name:"anthropic.completions.create",stream_function:vn}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:ls},completion:{function_name:"",stream_function:null}}};var uo="1.2.2",_s=()=>{var t;if(typeof process!="undefined"&&((t=process.versions)!=null&&t.node)){let n=process.versions.node.split(".");return`${n[0]}.${n[1]}`}return"unknown"},ms=_s(),fs=`promptlayer-js/${uo} (node ${ms})`,Q=()=>({"User-Agent":fs,"X-SDK-Version":uo}),fn="SET_WORKFLOW_COMPLETE";function gs(t,n,e,o){return S(this,null,function*(){let r=yield H(`${t}/workflow-version-execution-results?workflow_version_execution_id=${n}&return_all_outputs=${e}`,E({headers:o},Q()));if(!r.ok)throw new Error("Failed to fetch final output");return r.json()})}function _o(t,n,e,o,r){return function(i){return S(this,null,function*(){if(i.name===fn)try{let l=JSON.parse(i.data),d=l.result_code,u;if(d==="OK"||d==null)u=l.final_output;else if(d==="EXCEEDS_SIZE_LIMIT")u=yield gs(t,e,o,r),n.resolve(u);else throw new Error(`Unsupported final output code: ${d}`);n.resolve(u)}catch(l){n.reject(l)}})}}function ys(d){return S(this,arguments,function*({token:t,channelName:n,executionId:e,returnAllOutputs:o,headers:r,timeout:i,baseURL:l}){let u=new lo.default.Realtime(t),_=u.channels.get(n),m={},b=new Promise((x,P)=>{m.resolve=x,m.reject=P}),R=_o(l,m,e,o,r);yield _.subscribe(fn,R);try{return yield new Promise((x,P)=>{let T=setTimeout(()=>{P(new Error("Workflow execution did not complete properly (timeout)"))},i);b.then(h=>{clearTimeout(T),x(h)}).catch(h=>{clearTimeout(T),P(h)})})}finally{console.log("Closing client"),_.unsubscribe(fn,R),u.close(),console.log("Closed client")}})}var H=(t,n)=>S(null,null,function*(){return(0,po.default)(()=>S(null,null,function*(){let e=yield fetch(t,n);if(e.status>=500&&e.status<600||e.status===429)throw new Error(`Server error: ${e.status} ${e.statusText}`);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})}),mo=(t,n,e,o=!0)=>S(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?bs(t,n,e.request_response,e,o):yield fo(t,n,e,o)}),fo=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/track-request`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(e)}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);dt(i,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(i&&e.return_pl_id)return[e.request_response,i.request_id]}catch(r){if(o)throw r;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${r}`)}return e.request_response}),go=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/library-track-metadata`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track metadata";if(o)throw new Error(l);return dt(i,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),yo=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/library-track-score`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track score";if(o)throw new Error(l);return dt(i,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${r}`),!1}return!0}),ho=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/library-track-prompt`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track prompt";if(o)throw new Error(l);return dt(i,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${r}`),!1}return!0}),bo=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/track-group`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(Y(E({},e),{api_key:t}))}),i=yield r.json();if(r.status!==200){let l=i.message||i.error||"Failed to track group";if(o)throw new Error(l);return dt(i,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(r){if(o)throw r;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${r}`),!1}return!0}),Ro=(t,n,e=!0)=>S(null,null,function*(){try{let o=yield H(`${n}/create-group`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify({api_key:t})}),r=yield o.json();if(o.status!==200){let i=r.message||r.error||"Failed to create group";if(e)throw new Error(i);return dt(r,"WARNING: While creating a group PromptLayer had the following error"),!1}return r.id}catch(o){if(e)throw o;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${o}`),!1}}),xo=(t,n,e,o,r=!0)=>S(null,null,function*(){try{let i=new URL(`${n}/prompt-templates/${e}`),l=yield H(i,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":t},Q()),body:JSON.stringify(o)}),d=yield l.json();if(l.status!==200){let u=d.message||d.error||"Failed to fetch prompt template";if(r)throw new Error(u);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${u}`),null}return d.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${d.warning}`),d}catch(i){if(r)throw i;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${i}`),null}}),wo=(t,n,e,o=!0)=>S(null,null,function*(){let r=yield H(`${n}/rest/prompt-templates`,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":t},Q()),body:JSON.stringify({prompt_template:E({},e),prompt_version:E({},e),release_labels:e.release_labels?e.release_labels:void 0})}),i=yield r.json();if(r.status!==200&&r.status!==201){let l=i.message||i.error||"Failed to publish prompt template";if(o)throw new Error(l);dt(i,"WARNING: While publishing a prompt template PromptLayer had the following error")}return i}),To=(t,n,e,o=!0)=>S(null,null,function*(){var d;let r=new URL(`${n}/prompt-templates`);Object.entries(e||{}).forEach(([u,_])=>r.searchParams.append(u,_.toString()));let i=yield H(r,{headers:E({"Content-Type":"application/json","X-API-KEY":t},Q())}),l=yield i.json();if(i.status!==200){let u=l.message||l.error||"Failed to fetch prompt templates";if(o)throw new Error(u);return dt(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(d=l.items)!=null?d:[]}),hs=t=>S(null,null,function*(){let n=new URL(`${t.baseURL}/connection/websocket`);n.protocol=n.protocol==="https:"?"wss:":"ws:";let e=new co.Centrifuge(n.toString(),{token:t.token}),o=e.newSubscription(t.channelName);return new Promise((r,i)=>{let l=m=>{_(),r(m)},d=_o(t.baseURL,{resolve:l,reject:i},t.executionId,t.returnAllOutputs,t.headers);o.on("publication",m=>{d({name:m.data.message_name,data:m.data.data})});let u=setTimeout(()=>{i(new Error("Workflow execution did not complete properly (timeout)"))},t.timeout),_=()=>{clearTimeout(u),o.unsubscribe(),e.disconnect()};o.on("error",m=>{_(),i(`Centrifugo subscription error: ${m}`)}),e.on("error",m=>{_(),i(`Centrifugo client error: ${m}`)}),o.subscribe(),e.connect()})}),Eo=_=>S(null,[_],function*({workflow_name:t,input_variables:n,metadata:e={},workflow_label_name:o=null,workflow_version_number:r=null,return_all_outputs:i=!1,api_key:l,timeout:d=36e5,baseURL:u}){let m={input_variables:n,metadata:e,workflow_label_name:o,workflow_version_number:r,return_all_outputs:i},b=E({"Content-Type":"application/json","X-API-KEY":l},Q());try{let R=yield H(`${u}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:b,body:JSON.stringify(m)});if(R.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield R.json().catch(()=>({}))).error||R.statusText}`};let x=yield R.json();x.warning&&console.warn(`WARNING: ${x.warning}`);let P=x.workflow_version_execution_id;if(!P)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let T=`workflow_updates:${P}`,w=yield(yield H(`${u}/ws-token-request-library?capability=${T}`,{method:"POST",headers:b})).json(),g={token:w.token_details.token,channelName:T,executionId:P,returnAllOutputs:i,headers:b,timeout:d,baseURL:u};return w.messaging_backend==="centrifugo"?hs(g):yield ys(g)}catch(R){throw console.error(`Failed to run workflow: ${R instanceof Error?R.message:R}`),R}});function bs(t,n,e,o,r=!0){return ve(this,null,function*(){let i=[];try{for(var u=tn(e),_,m,b;_=!(m=yield new ft(u.next())).done;_=!1){let R=m.value;yield o.return_pl_id?[R,null]:R,i.push(R)}}catch(m){b=[m]}finally{try{_&&(m=u.return)&&(yield new ft(m.call(u)))}finally{if(b)throw b[0]}}let l=so(i,o.function_name),d=yield new ft(fo(t,n,Y(E({},o),{request_response:l,request_end_time:new Date().toISOString()}),r));if(d&&o.return_pl_id){let R=d[1];yield[i.at(-1),R]}})}var dt=(t,n)=>{try{console.warn(`${n}: ${t.message}`)}catch(e){console.warn(`${n}: ${t}`)}},Po=(t,n,e=!0)=>S(null,null,function*(){try{let o=yield H(`${t}/track-request`,{method:"POST",headers:E({"Content-Type":"application/json"},Q()),body:JSON.stringify(n)}),r=yield o.json();if(o.status!==200){let i=r.message||r.error||"Failed to track request";if(e)throw new Error(i);dt(r,"WARNING: While logging your request, PromptLayer experienced the following error:")}return r}catch(o){if(e)throw o;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${o}`)}return{}}),Rs=(t,n)=>S(null,null,function*(){return yield t.chat.completions.create(n)}),xs=(t,n)=>S(null,null,function*(){return yield t.completions.create(n)}),Ao={chat:Rs,completion:xs},Oo=(t,n)=>S(null,null,function*(){var i,l;let e=require("openai").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey});n==null||delete n.apiKey,n==null||delete n.baseURL;let r=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(r==="chat-completions"){let d=Ao[t.prompt_template.type];return yield d(o,n)}else return r==="images"?yield o.images.generate(n):yield o.responses.create(n)}),ko=(t,n)=>S(null,null,function*(){var i,l;let{AzureOpenAI:e}=require("openai"),o=new e({endpoint:process.env.AZURE_OPENAI_ENDPOINT||n.baseURL,apiVersion:process.env.OPENAI_API_VERSION||n.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||n.apiKey});n==null||delete n.baseURL,n==null||delete n.apiVersion,n==null||delete n.apiKey;let r=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(r==="chat-completions"){let d=Ao[t.prompt_template.type];return yield d(o,n)}else return r==="images"?yield o.images.generate(n):yield o.responses.create(n)}),So=(t,n)=>S(null,null,function*(){return t.messages.create(n)}),ws=(t,n)=>S(null,null,function*(){return t.completions.create(n)}),Io={chat:So,completion:ws},Co=(t,n)=>S(null,null,function*(){let e=require("@anthropic-ai/sdk").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey}),r=Io[t.prompt_template.type];return r(o,n)}),No=(t,n,e,o=!0)=>S(null,null,function*(){try{let r=yield H(`${n}/log-request`,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":t},Q()),body:JSON.stringify(e)}),i=yield r.json();if(r.status!==201){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);return dt(i,"WARNING: While logging your request PromptLayer had the following error"),null}return i}catch(r){if(o)throw r;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${r}`),null}}),Ts=(t,n)=>S(null,null,function*(){var l,d;let e=n==null?void 0:n.history,o=n==null?void 0:n.generationConfig,r=e.length>0?(l=e[e.length-1])==null?void 0:l.parts:"",i=t.chats.create({model:n==null?void 0:n.model,history:(d=e.slice(0,-1))!=null?d:[],config:o});return n!=null&&n.stream?yield i.sendMessageStream({message:r}):yield i.sendMessage({message:r})}),Es=(t,o)=>S(null,null,function*(){var r=o,{stream:n}=r,e=Qe(r,["stream"]);return n?yield t.generateContentStream(E({},e)):yield t.generateContent(E({},e))}),Ps={chat:Ts,completion:Es},gn=(t,n)=>S(null,null,function*(){let{GoogleGenAI:e}=yield import("@google/genai"),o=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,r=process.env.VERTEX_AI_PROJECT_ID||process.env.GOOGLE_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT,i=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,l={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:r,scopes:["https://www.googleapis.com/auth/cloud-platform"]},d=o?new e({apiKey:o}):new e({vertexai:!0,project:r,location:i,googleAuthOptions:l}),u=Ps[t.prompt_template.type];return yield u(d,n)}),io=t=>t.replace(/_([a-z])/g,(n,e)=>e.toUpperCase()),nn=(t,n=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>nn(e,n)):Object.fromEntries(Object.entries(t).map(([e,o])=>n.has(e)?[io(e),o]:[io(e),nn(o,n)])),Lo=(t,n,e={},o=!1)=>{var u,_,m,b,R,x,P,T,h;let r=(m=n==null?void 0:n.client)!=null?m:(_=(u=t.metadata)==null?void 0:u.model)==null?void 0:_.provider,i=(R=(b=t.metadata)==null?void 0:b.model)==null?void 0:R.api_type;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let l=Y(E({},t.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(r)&&((P=(x=t.metadata)==null?void 0:x.model)!=null&&P.name.startsWith("gemini"))&&(l=nn(l,new Set(["function_declarations","properties"])));let d={baseURL:(h=n==null?void 0:n.base_url)!=null?h:(T=t.provider_base_url)==null?void 0:T.url,apiKey:n==null?void 0:n.api_key};return Object.entries(d).forEach(([w,f])=>{f!==void 0&&(l[w]=f)}),o&&no.includes(r)&&i==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:r,kwargs:l}},qo=(t,n)=>{let e=ao[t];if(!e)throw new Error(`Unsupported provider type: ${t}`);let o=n.type,r=e[o];if(!r)throw new Error(`Unsupported template type '${n.type}' for provider '${t}'`);return r},Mo=(t,n)=>S(null,null,function*(){var o;let e=(o=t.metadata)==null?void 0:o.model;if(!e)throw new Error("Model metadata not found in prompt blueprint");if(e.name.startsWith("gemini"))return gn(t,n);if(e.name.startsWith("claude")){let{AnthropicVertex:r}=yield import("@anthropic-ai/vertex-sdk"),i=new r({baseURL:n.baseURL});if(t.prompt_template.type==="chat")return So(i,n);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${e.name}' for Vertex AI request`)}),Uo=(t,n)=>S(null,null,function*(){let{BedrockRuntimeClient:e,ConverseCommand:o,ConverseStreamCommand:r}=yield import("@aws-sdk/client-bedrock-runtime"),i=new e({credentials:{accessKeyId:(n==null?void 0:n.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(n==null?void 0:n.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(n==null?void 0:n.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(n==null?void 0:n.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(n!=null&&n.stream){delete n.stream;let l=new r(E({},n));return yield i.send(l)}else{n==null||delete n.stream;let l=new o(E({},n));return yield i.send(l)}}),Wo=(t,n)=>S(null,null,function*(){let{AnthropicBedrock:e}=yield import("@anthropic-ai/bedrock-sdk"),o=new e({awsAccessKey:n.aws_access_key,awsSecretKey:n.aws_secret_key,awsRegion:n.aws_region,awsSessionToken:n.aws_session_token,baseURL:n.base_url}),r=Io[t.prompt_template.type];return r(o,n)}),jo=(t,n)=>S(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),o=new e({apiKey:process.env.MISTRAL_API_KEY});return n=nn(n,new Set),n!=null&&n.stream?(delete n.stream,yield o.chat.stream(n)):(delete n.stream,yield o.chat.complete(n))}),yn=t=>{var n,e,o,r,i,l;if(typeof globalThis.process!="undefined")return(o=(e=(n=globalThis.process.env)==null?void 0:n[t])==null?void 0:e.trim())!=null?o:void 0;if(typeof globalThis.Deno!="undefined")return(l=(i=(r=globalThis.Deno.env)==null?void 0:r.get)==null?void 0:i.call(r,t))==null?void 0:l.trim()};var on=class{constructor(n,e,o=!0){this.create=()=>Ro(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var _t=require("@opentelemetry/api"),Xe=require("@opentelemetry/core");var hn=class{constructor(n,e,o){this.apiKey=e,this.baseURL=o,this.enableTracing=n,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(n){return n?Object.fromEntries(Object.entries(n)):{}}spanKindToString(n){return{[_t.SpanKind.INTERNAL]:"SpanKind.INTERNAL",[_t.SpanKind.SERVER]:"SpanKind.SERVER",[_t.SpanKind.CLIENT]:"SpanKind.CLIENT",[_t.SpanKind.PRODUCER]:"SpanKind.PRODUCER",[_t.SpanKind.CONSUMER]:"SpanKind.CONSUMER"}[n]||"SpanKind.INTERNAL"}statusCodeToString(n){return{[_t.SpanStatusCode.ERROR]:"StatusCode.ERROR",[_t.SpanStatusCode.OK]:"StatusCode.OK",[_t.SpanStatusCode.UNSET]:"StatusCode.UNSET"}[n]||"StatusCode.UNSET"}toNanoseconds(n){return(BigInt(n[0])*BigInt(1e9)+BigInt(n[1])).toString()}export(n){if(!this.enableTracing)return Promise.resolve(Xe.ExportResultCode.SUCCESS);let e=n.map(o=>{var r;return{name:o.name,context:{trace_id:o.spanContext().traceId,span_id:o.spanContext().spanId,trace_state:((r=o.spanContext().traceState)==null?void 0:r.serialize())||""},kind:this.spanKindToString(o.kind),parent_id:o.parentSpanId||null,start_time:this.toNanoseconds(o.startTime),end_time:this.toNanoseconds(o.endTime),status:{status_code:this.statusCodeToString(o.status.code),description:o.status.message},attributes:this.attributesToObject(o.attributes),events:o.events.map(i=>({name:i.name,timestamp:this.toNanoseconds(i.time),attributes:this.attributesToObject(i.attributes)})),links:o.links.map(i=>({context:i.context,attributes:this.attributesToObject(i.attributes)})),resource:{attributes:Y(E({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return H(this.url,{method:"POST",headers:E({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},Q()),body:JSON.stringify({spans:e})}).then(o=>o.ok?Xe.ExportResultCode.SUCCESS:(console.error(`Error exporting spans
2
- HTTP error! status: ${o.status}`),Xe.ExportResultCode.FAILED)).catch(o=>(console.error("Error exporting spans:",o),Xe.ExportResultCode.FAILED))}shutdown(){return Promise.resolve()}},$o=hn;var Ko=ut(require("@opentelemetry/api")),Go=require("@opentelemetry/sdk-trace-base"),Do=require("@opentelemetry/sdk-trace-node"),Ot=(t="promptlayer-tracer")=>Ko.trace.getTracer(t),Fo=(t,n,e)=>{let o=new Do.NodeTracerProvider,r=new $o(t,n,e),i=new Go.SimpleSpanProcessor(r);o.addSpanProcessor(i),o.register()};var As=Ot(),bn=(t,n,e,o="",r="openai")=>{let i={construct:(l,d)=>{let u=Reflect.construct(l,d);return Object.defineProperties(u,{function_name:{value:o,writable:!0},provider:{value:r}}),new Proxy(u,i)},get:(l,d,u)=>{let _=l[d],m=`${Reflect.get(l,"function_name")}.${d.toString()}`;return typeof _=="object"?(Object.defineProperties(_,{function_name:{value:m,writable:!0},provider:{value:r}}),new Proxy(_,i)):typeof _=="function"?(...b)=>{var w,f,g,C,M,W;let R=new Date().toISOString(),x=Reflect.get(l,"provider"),P=(w=b[0])==null?void 0:w.return_pl_id,T=(f=b[0])==null?void 0:f.pl_tags,h=(g=b[0])==null?void 0:g.pl_warn_on_error;return(C=b[0])==null||delete C.return_pl_id,(M=b[0])==null||delete M.pl_tags,(W=b[0])==null||delete W.pl_warn_on_error,As.startActiveSpan(`${x}.${m}`,I=>S(null,null,function*(){try{I.setAttribute("function_input",JSON.stringify(b));let N=Reflect.apply(_,l,b),j=I.spanContext().spanId;return N instanceof Promise?new Promise((L,B)=>{N.then($=>S(null,null,function*(){let X=yield mo(t,n,{api_key:t,provider_type:x,function_name:m,request_start_time:R,request_end_time:new Date().toISOString(),request_response:$,kwargs:b[0],return_pl_id:P,tags:T,span_id:j},!h);I.setAttribute("function_output",JSON.stringify(X)),I.setAttribute("response_status","success"),I.end(),L(X)})).catch($=>{I.recordException($),I.setAttribute("response_status","error"),I.end(),B($)})}):(I.setAttribute("function_output",JSON.stringify(N)),I.setAttribute("response_status","success"),I.end(),N)}catch(N){throw I.recordException(N),I.setAttribute("response_status","error"),I.end(),N}}))}:Reflect.get(l,d,u)}};return new Proxy(e,i)};var sn=ut(require("@opentelemetry/api"));var zo=(t,n,e)=>function(...o){let r=Ot(),i=l=>{try{e&&Object.entries(e).forEach(([u,_])=>{l.setAttribute(u,_)}),l.setAttribute("function_input",JSON.stringify(o));let d=n(...o);return d instanceof Promise?d.then(u=>(l.setAttribute("function_output",JSON.stringify(u)),l.setStatus({code:sn.SpanStatusCode.OK}),u)).catch(u=>{throw Bo(l,u,o),u}).finally(()=>l.end()):(l.setAttribute("function_output",JSON.stringify(d)),l.setStatus({code:sn.SpanStatusCode.OK}),l.end(),d)}catch(d){throw Bo(l,d,o),d}};return r.startActiveSpan(t,i)},Bo=(t,n,e)=>{t.setAttribute("function_input",JSON.stringify(e)),t.setStatus({code:sn.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),t.end()};var rn=class{constructor(n,e,o=!0){this.get=(n,e)=>xo(this.apiKey,this.baseURL,n,e,this.throwOnError);this.publish=n=>wo(this.apiKey,this.baseURL,n,this.throwOnError);this.all=n=>To(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var Os=(t,n,e,o=!0)=>{if(!(e.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[r,i]of Object.entries(e.metadata))if(typeof r!="string"||typeof i!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return go(t,n,e,o)},ks=(t,n,e,o=!0)=>{if(typeof e.score!="number")throw new Error("Score must be a number");if(e.score<0||e.score>100)throw new Error("Score must be a number between 0 and 100.");return yo(t,n,e,o)},Ss=(t,n,e,o=!0)=>{if(!(e.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return ho(t,n,e,o)},Is=(t,n,e,o=!0)=>bo(t,n,e,o),an=class{constructor(n,e,o=!0){this.group=n=>Is(this.apiKey,this.baseURL,n,this.throwOnError);this.metadata=n=>Os(this.apiKey,this.baseURL,n,this.throwOnError);this.prompt=n=>Ss(this.apiKey,this.baseURL,n,this.throwOnError);this.score=n=>ks(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};function Cs(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function Ns(t){return t&&typeof t=="object"&&t.constructor?t.constructor.name:""}function Vo(t){let n=Cs(t),e=Ns(t),o=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return n===429||/ratelimit/i.test(e)?"PROVIDER_RATE_LIMIT":/timeout/i.test(e)?"PROVIDER_TIMEOUT":n===401||/authentication/i.test(e)?"PROVIDER_AUTH_ERROR":o.includes("quota")?"PROVIDER_QUOTA_LIMIT":o.includes("timeout")||o.includes("timed out")?"PROVIDER_TIMEOUT":n!==void 0?"PROVIDER_ERROR":"UNKNOWN_ERROR"}var Jo=ut(require("@opentelemetry/api"));var Ls={openai:Oo,anthropic:Co,"openai.azure":ko,google:gn,vertexai:Mo,"amazon.bedrock":Uo,"anthropic.bedrock":Wo,mistral:jo},qs=t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(t).every(o=>typeof o!="object"||o===null?!1:n.every(r=>r in o))},Rn=class{constructor({apiKey:n=yn("PROMPTLAYER_API_KEY"),baseURL:e=yn("PROMPTLAYER_BASE_URL"),enableTracing:o=!1,throwOnError:r=!0}={}){if(n===void 0)throw new Error("PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter.");this.apiKey=n,this.baseURL=e||"https://api.promptlayer.com",this.enableTracing=o,this.throwOnError=r,this.templates=new rn(n,this.baseURL,this.throwOnError),this.group=new on(n,this.baseURL,this.throwOnError),this.track=new an(n,this.baseURL,this.throwOnError),this.wrapWithSpan=zo,o&&Fo(o,n,this.baseURL)}get Anthropic(){try{let n=require("@anthropic-ai/sdk").default;return bn(this.apiKey,this.baseURL,n,"anthropic","anthropic")}catch(n){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let n=require("openai").default;return bn(this.apiKey,this.baseURL,n,"openai","openai")}catch(n){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(R){return S(this,arguments,function*({promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:r,tags:i,metadata:l,groupId:d,modelParameterOverrides:u,stream:_=!1,provider:m,model:b}){return Ot().startActiveSpan("PromptLayer Run",P=>S(this,null,function*(){try{let T={promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:r,tags:i,metadata:l,groupId:d,modelParameterOverrides:u,stream:_};P.setAttribute("function_input",JSON.stringify(T));let h=r,w={label:o,version:e,metadata_filters:l,provider:m,model:b,model_parameter_overrides:u};r&&(w.input_variables=r);let f=yield this.templates.get(n,w);if(!f)throw new Error(`Cannot proceed: prompt template '${n}' could not be fetched. Check the warnings above for the actual error.`);let g=f.prompt_template;if(!f.llm_kwargs){let D=`Prompt '${n}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashboard.`;if(this.throwOnError)throw new Error(D);console.warn(`WARNING: ${D}`)}let C=f.metadata;if(!C)throw new Error(`Prompt '${n}' does not have any metadata associated with it.`);let M=C.model;if(!M)throw new Error(`Prompt '${n}' does not have a model parameters associated with it.`);let W=f.custom_provider,I=new Date().toISOString(),{provider_type:N,kwargs:j}=Lo(f,W,u,_),L=N;if(N==="openai"||N==="openai.azure"){let D=M.api_type;L=`${N}:${D}`}M.name.startsWith("gemini")?L="google":M.name.startsWith("claude")&&(L="anthropic");let B=qo(L,g),{function_name:$,stream_function:X}=B,G=Ls[N];if(!G)throw new Error(`No request function found for provider: ${N}`);let Z=D=>{let nt=new Date().toISOString();return Po(this.baseURL,E({function_name:$,provider_type:N,args:[],kwargs:j,tags:i,request_start_time:I,request_end_time:nt,api_key:this.apiKey,metadata:l,prompt_id:f.id,prompt_version:f.version,prompt_input_variables:h,group_id:d,return_prompt_blueprint:!0,span_id:P.spanContext().spanId},D),this.throwOnError)},J;try{J=yield G(f,j)}catch(D){let nt=Vo(D),it=D instanceof Error?D.message:String(D);throw yield Z({request_response:{},status:"ERROR",error_type:nt,error_message:it}),D}if(_)return ro(J,Z,X,l||f.metadata);let rt=yield Z({request_response:J}),at={request_id:rt.request_id,raw_response:J,prompt_blueprint:rt.prompt_blueprint};return P.setAttribute("function_output",JSON.stringify(at)),at}catch(T){throw P.setStatus({code:Jo.SpanStatusCode.ERROR,message:T instanceof Error?T.message:"Unknown error"}),T}finally{P.end()}}))})}runWorkflow(d){return S(this,arguments,function*({workflowName:n,inputVariables:e={},metadata:o={},workflowLabelName:r=null,workflowVersion:i=null,returnAllOutputs:l=!1}){try{let u=yield Eo({workflow_name:n,input_variables:e,metadata:o,workflow_label_name:r,workflow_version_number:i,return_all_outputs:l,api_key:this.apiKey,baseURL:this.baseURL});if(!l&&qs(u)){let m=Object.values(u).filter(R=>R.is_output_node===!0);if(m.length===0)throw new Error(JSON.stringify(u,null,2));if(!m.some(R=>R.status==="SUCCESS"))throw new Error(JSON.stringify(u,null,2))}return u}catch(u){throw u instanceof Error?(console.error("Error running workflow:",u.message),new Error(`Error running workflow: ${u.message}`)):(console.error("Unknown error running workflow:",u),new Error("Unknown error running workflow"))}})}logRequest(n){return S(this,null,function*(){return No(this.apiKey,this.baseURL,n,this.throwOnError)})}};0&&(module.exports={PromptLayer});
1
+ "use strict";var cs=Object.create;var Xe=Object.defineProperty,ps=Object.defineProperties,us=Object.getOwnPropertyDescriptor,ds=Object.getOwnPropertyDescriptors,_s=Object.getOwnPropertyNames,ve=Object.getOwnPropertySymbols,ms=Object.getPrototypeOf,fo=Object.prototype.hasOwnProperty,Xo=Object.prototype.propertyIsEnumerable;var mo=(t,o)=>(o=Symbol[t])?o:Symbol.for("Symbol."+t);var Yo=(t,o,e)=>o in t?Xe(t,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[o]=e,S=(t,o)=>{for(var e in o||(o={}))fo.call(o,e)&&Yo(t,e,o[e]);if(ve)for(var e of ve(o))Xo.call(o,e)&&Yo(t,e,o[e]);return t},Y=(t,o)=>ps(t,ds(o));var to=(t,o)=>{var e={};for(var n in t)fo.call(t,n)&&o.indexOf(n)<0&&(e[n]=t[n]);if(t!=null&&ve)for(var n of ve(t))o.indexOf(n)<0&&Xo.call(t,n)&&(e[n]=t[n]);return e};var fs=(t,o)=>{for(var e in o)Xe(t,e,{get:o[e],enumerable:!0})},Zo=(t,o,e,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let s of _s(o))!fo.call(t,s)&&s!==e&&Xe(t,s,{get:()=>o[s],enumerable:!(n=us(o,s))||n.enumerable});return t};var dt=(t,o,e)=>(e=t!=null?cs(ms(t)):{},Zo(o||!t||!t.__esModule?Xe(e,"default",{value:t,enumerable:!0}):e,t)),gs=t=>Zo(Xe({},"__esModule",{value:!0}),t);var T=(t,o,e)=>new Promise((n,s)=>{var a=d=>{try{u(e.next(d))}catch(_){s(_)}},l=d=>{try{u(e.throw(d))}catch(_){s(_)}},u=d=>d.done?n(d.value):Promise.resolve(d.value).then(a,l);u((e=e.apply(t,o)).next())}),ft=function(t,o){this[0]=t,this[1]=o},eo=(t,o,e)=>{var n=(l,u,d,_)=>{try{var m=e[l](u),R=(u=m.value)instanceof ft,k=m.done;Promise.resolve(R?u[0]:u).then(g=>R?n(l==="return"?l:"next",u[1]?{done:g.done,value:g.value}:g,d,_):d({value:g,done:k})).catch(g=>n("throw",g,d,_))}catch(g){_(g)}},s=l=>a[l]=u=>new Promise((d,_)=>n(l,u,d,_)),a={};return e=e.apply(t,o),a[mo("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a};var oo=(t,o,e)=>(o=t[mo("asyncIterator")])?o.call(t):(t=t[mo("iterator")](),o={},e=(n,s)=>(s=t[n])&&(o[n]=a=>new Promise((l,u,d)=>(a=s.call(t,a),d=a.done,Promise.resolve(a.value).then(_=>l({value:_,done:d}),u)))),e("next"),e("return"),o);var Qs={};fs(Qs,{PromptLayer:()=>Eo});module.exports=gs(Qs);var gn=dt(require("ably")),hn=require("centrifuge"),yn=dt(require("p-retry"));var Ho={png:"image/png",webp:"image/webp",jpeg:"image/jpeg",jpg:"image/jpeg",gif:"image/gif",url:"image/png"},rt=(t,o,e,n)=>S({id:t,type:"function",function:{name:o,arguments:typeof e=="string"?e:JSON.stringify(e)}},n?{tool_id:n}:{}),y=n=>{var s=n,{type:t,item_id:o}=s,e=to(s,["type","item_id"]);let a=S({type:t},e);return o&&(a.id=o),a},Ct=(t,o)=>({role:"assistant",input_variables:[],template_format:"f-string",content:t,tool_calls:o}),Pt=(t,o)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:o});function Qo(t){var o,e,n,s;return S(S({type:"url_citation",url:(o=t.url)!=null?o:"",title:(e=t.title)!=null?e:"",start_index:(n=t.start_index)!=null?n:0,end_index:(s=t.end_index)!=null?s:0},t.cited_text!=null?{cited_text:t.cited_text}:{}),t.encrypted_index!=null?{encrypted_index:t.encrypted_index}:{})}var tn=(t,o,e)=>{var l,u,d,_,m,R,k,g,C,x,b,w,f,h,I,q,j,A,L,W,U,z,$,H,F,Q,Z,it,at,D,nt,lt,gt,ht,yt,bt,Rt,kt,wt,St;let n=[],s=[];if(Array.isArray(t.content)){for(let N of t.content){if(!N||typeof N!="object")continue;let X=N.type;if(X==="text"){let tt=(l=N.text)!=null?l:"",ct=(d=(u=N.citations)!=null?u:N.annotations)!=null?d:[],et=[];for(let ot of ct)ot&&typeof ot=="object"&&et.push(Qo(ot));n.push(y(S({type:"text",text:tt},et.length>0?{annotations:et}:{})))}else if(X==="thinking")n.push(y({type:"thinking",thinking:(_=N.thinking)!=null?_:"",signature:(m=N.signature)!=null?m:""}));else if(X==="tool_use")s.push(rt((R=N.id)!=null?R:"",(k=N.name)!=null?k:"",(g=N.input)!=null?g:{}));else if(X==="server_tool_use")n.push(y({type:"server_tool_use",id:(C=N.id)!=null?C:"",name:(x=N.name)!=null?x:"",input:(b=N.input)!=null?b:{}}));else if(X==="web_search_tool_result"){let tt=(w=N.content)!=null?w:[],ct=[];for(let et of tt)if(et&&typeof et=="object"&&et.type==="web_search_result"){let ot=et;ct.push({type:"web_search_result",url:ot.url,title:ot.title,encrypted_content:ot.encrypted_content,page_age:ot.page_age})}n.push(y({type:"web_search_tool_result",tool_use_id:(f=N.tool_use_id)!=null?f:"",content:ct}))}else X==="bash_code_execution_tool_result"&&n.push(y({type:"bash_code_execution_tool_result",tool_use_id:(h=N.tool_use_id)!=null?h:"",content:(I=N.content)!=null?I:{}}))}let st=Ct(n,s);return Pt(st,o)}if(t.type==="content_block_start")if(((q=t.content_block)==null?void 0:q.type)==="thinking")n.push(y({type:"thinking",thinking:"",signature:""}));else if(((j=t.content_block)==null?void 0:j.type)==="text")n.push(y({type:"text",text:""}));else if(((A=t.content_block)==null?void 0:A.type)==="tool_use")s.push(rt((L=t.content_block.id)!=null?L:"",(W=t.content_block.name)!=null?W:"",{}));else if(((U=t.content_block)==null?void 0:U.type)==="server_tool_use")n.push(y({type:"server_tool_use",id:(z=t.content_block.id)!=null?z:"",name:($=t.content_block.name)!=null?$:"",input:(H=t.content_block.input)!=null?H:{}}));else if(((F=t.content_block)==null?void 0:F.type)==="web_search_tool_result"){let st=(Q=t.content_block.content)!=null?Q:[],N=[];for(let X of st)if(X&&typeof X=="object"&&X.type==="web_search_result"){let tt=X;N.push({type:"web_search_result",url:tt.url,title:tt.title,encrypted_content:tt.encrypted_content,page_age:tt.page_age})}n.push(y({type:"web_search_tool_result",tool_use_id:(Z=t.content_block.tool_use_id)!=null?Z:"",content:N}))}else((it=t.content_block)==null?void 0:it.type)==="bash_code_execution_tool_result"&&n.push(y({type:"bash_code_execution_tool_result",tool_use_id:(at=t.content_block.tool_use_id)!=null?at:"",content:(D=t.content_block.content)!=null?D:{}}));else if(t.type==="content_block_delta"){if(((nt=t.delta)==null?void 0:nt.type)==="thinking_delta")n.push(y({type:"thinking",thinking:(lt=t.delta.thinking)!=null?lt:"",signature:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="text_delta")n.push(y({type:"text",text:(ht=t.delta.text)!=null?ht:""}));else if(((yt=t.delta)==null?void 0:yt.type)==="signature_delta")n.push(y({type:"thinking",thinking:"",signature:(bt=t.delta.signature)!=null?bt:""}));else if(((Rt=t.delta)==null?void 0:Rt.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?n.push(y({type:"server_tool_use",id:"",name:"",input:(kt=t.delta.partial_json)!=null?kt:{}})):s.push(rt("","",(wt=t.delta.partial_json)!=null?wt:""));else if(((St=t.delta)==null?void 0:St.type)==="citations_delta"&&t.delta.citation){let st=t.delta.citation,N=[Qo(st)];n.push(y({type:"text",text:"",annotations:N}))}}let a=Ct(n,s);return Pt(a,o)},hs=t=>typeof t=="string"&&t.startsWith("image/");function vo(t){var e,n,s,a;let o=t.web;return o&&typeof o=="object"?{uri:(e=o.uri)!=null?e:"",title:(n=o.title)!=null?n:""}:{uri:(s=t.uri)!=null?s:"",title:(a=t.title)!=null?a:""}}function ys(t){if(!t||typeof t!="object")return;let o=t.content,e=o==null?void 0:o.parts;if(!Array.isArray(e))return;let n=[];for(let s of e)s&&typeof s=="object"&&typeof s.text=="string"&&n.push(s.text);return n.length>0?n.join(""):void 0}function bs(t){var n,s,a,l;if(!t||typeof t!="object")return[];let o=(n=t.citations)!=null?n:[],e=[];for(let u of o){if(!u||typeof u!="object")continue;let d=(s=u.uri)!=null?s:"";if(!d)continue;let _=(a=u.startIndex)!=null?a:0,m=(l=u.endIndex)!=null?l:0;e.push({type:"url_citation",url:d,title:d,start_index:_,end_index:m})}return e}function Rs(t,o){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,n=t.citationMetadata,s=ks(e,o),a=bs(n);return[...s,...a]}function ks(t,o){var u,d,_,m,R,k,g,C,x;let e=t&&typeof t=="object"?(u=t.groundingChunks)!=null?u:[]:[],n=t&&typeof t=="object"?(d=t.groundingSupports)!=null?d:[]:[];function s(b,w,f){let h=b.text;if(h!=null&&h!=="")return h;if(o!=null&&f>w)return o.slice(w,f)||void 0}if(n.length>0&&e.length>0){let b=[],w=new Set;for(let f of n){if(!f||typeof f!="object")continue;let h=(_=f.segment)!=null?_:{},I=(m=f.groundingChunkIndices)!=null?m:[],q=(R=h.startIndex)!=null?R:0,j=(k=h.endIndex)!=null?k:0,A=s(h,q,j);for(let L of I){if(typeof L!="number"||L>=e.length)continue;let W=e[L];if(!W||typeof W!="object")continue;let U=W.maps;if(U&&typeof U=="object"){let F=(g=U.uri)!=null?g:"",Q=(C=U.title)!=null?C:"",Z=U.placeId;(F||Q)&&b.push(S(Y(S({type:"map_citation",url:F,title:Q||F},Z!=null?{place_id:Z}:{}),{start_index:q,end_index:j}),A!=null?{cited_text:A}:{}));continue}let z=W.retrievedContext;if(z&&typeof z=="object"){let F=(x=z.title)!=null?x:"";F&&!w.has(F)&&(w.add(F),b.push({type:"file_citation",file_id:F,filename:F,index:L}));continue}let{uri:$,title:H}=vo(W);$&&b.push(S({type:"url_citation",url:$,title:H||$,start_index:q,end_index:j},A!=null?{cited_text:A}:{}))}}return b}if(!t||typeof t!="object")return[];let a=[],l=new Set;return e.forEach((b,w)=>{var A,L,W;if(!b||typeof b!="object")return;let f=b,h=f.maps;if(h&&typeof h=="object"){let U=(A=h.uri)!=null?A:"",z=(L=h.title)!=null?L:"",$=h.placeId;(U||z)&&a.push(Y(S({type:"map_citation",url:U,title:z||U},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let I=f.retrievedContext;if(I&&typeof I=="object"){let U=(W=I.title)!=null?W:"";U&&!l.has(U)&&(l.add(U),a.push({type:"file_citation",file_id:U,filename:U,index:w}));return}let{uri:q,title:j}=vo(f);q&&a.push({type:"url_citation",url:q,title:j||q,start_index:0,end_index:0})}),a}var en=(t,o)=>{var d,_,m,R,k,g,C,x,b;let e=[],n=[];for(let w of(d=t.candidates)!=null?d:[])if(w.content&&w.content.parts&&Array.isArray(w.content.parts))for(let f of w.content.parts)if(f.text!=null)f.thought===!0?e.push(y({type:"thinking",thinking:f.text,signature:(_=f.thoughtSignature)!=null?_:""})):e.push(y(S({type:"text",text:f.text},f.thoughtSignature?{thought_signature:f.thoughtSignature}:{})));else if(f.functionCall)n.push(rt(f.functionCall.id||"",f.functionCall.name||"",f.functionCall.args||{}));else if(f.executableCode){let h=f.executableCode;e.push(y(S({type:"code",code:(m=h.code)!=null?m:""},h.language!=null?{language:h.language}:{})))}else if(f.codeExecutionResult){let h=f.codeExecutionResult;e.push(y({type:"code_execution_result",output:(R=h.output)!=null?R:"",outcome:(k=h.outcome)!=null?k:"OUTCOME_OK"}))}else{let h=f.inlineData;if(h&&f.thought!==!0){let I=(g=h.mimeType)!=null?g:"image/png",q=(C=h.data)!=null?C:"";if(hs(I)&&q){let j={};f.thoughtSignature&&(j.thought_signature=f.thoughtSignature),f.aspectRatio!=null&&(j.aspect_ratio=f.aspectRatio),f.imageSize!=null&&(j.image_size=f.imageSize),e.push(y(S({type:"output_media",url:q,mime_type:I,media_type:"image"},Object.keys(j).length?{provider_metadata:j}:{})))}}}let s=(x=t.candidates)==null?void 0:x[0],a=ys(s),l=Rs(s,a);if(l.length>0)for(let w=0;w<e.length;w++){let f=e[w];if(f&&typeof f=="object"&&f.type==="text"){let h=(b=f.annotations)!=null?b:[];e[w]=Y(S({},f),{annotations:[...h,...l]})}}let u=Ct(e,n);return Pt(u,o)},go=(t,o)=>{let e=[],n=[];for(let a of t.choices)if(a.delta){a.delta.content&&e.push(y({type:"text",text:a.delta.content}));let l=a.delta.tool_calls||a.delta.toolCalls;if(l&&Array.isArray(l))for(let u of l)u.function&&n.push(rt(u.id||"",u.function.name||"",u.function.arguments||""))}let s=Ct(e,n);return Pt(s,o)},on=(t,o)=>{var l,u,d,_,m,R,k,g,C,x,b,w,f,h,I,q,j,A,L,W,U,z,$,H,F,Q,Z,it,at,D,nt,lt,gt,ht,yt,bt,Rt,kt,wt,St,st,N,X,tt,ct,et,ot,Tt,Ot,At,It,Lt,Ut,Nt,qt,Mt,jt,Wt,$t,Kt,Gt,Ft,Dt,Bt,Vt,zt,Jt,Yt,Xt,Zt,Ht,Qt,vt,te,ee,oe,ne,se,re,ie,ae,le,ce,pe,ue,de,_e,me,fe,ge,he,ye,be,Re,ke,we,Se,xe,Ce,Pe,Ee,Te,Oe,Ae,Ie,Le,Ue,Ne,qe,Me,je,We,$e,Ke,Ge,Fe,De,Be,Ve,ze,Je,Ye,P,M,i,c,E,pt,To,Oo,Ao,Io,Lo,Uo,No,qo,Mo,jo,Wo,$o,Ko,Go,Fo,Do,Bo,Vo,zo,Jo;let e=[],n=[],s=t==null?void 0:t.type;if(s==="response.reasoning_summary_text.delta"){let r=(l=t==null?void 0:t.delta)!=null?l:"",O=(u=t==null?void 0:t.item_id)!=null?u:"";r&&e.push(y({type:"thinking",item_id:O,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_text.done"){let r=(d=t==null?void 0:t.text)!=null?d:"",O=(_=t==null?void 0:t.item_id)!=null?_:"";r&&e.push(y({type:"thinking",item_id:O,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_part.added"){let r=(m=t==null?void 0:t.part)!=null?m:{},O=(R=t==null?void 0:t.item_id)!=null?R:"";if((r==null?void 0:r.type)==="summary_text"){let p=(k=r==null?void 0:r.text)!=null?k:"";e.push(y({type:"thinking",item_id:O,thinking:p,signature:""}))}}else if(s==="response.reasoning_summary_part.done"){let r=(g=t==null?void 0:t.part)!=null?g:{},O=(C=t==null?void 0:t.item_id)!=null?C:"";if((r==null?void 0:r.type)==="summary_text"){let p=(x=r==null?void 0:r.text)!=null?x:"";p&&e.push(y({type:"thinking",item_id:O,thinking:p,signature:""}))}}else if(s==="response.function_call_arguments.delta"){let r=(b=t==null?void 0:t.item_id)!=null?b:"",O=(w=t==null?void 0:t.delta)!=null?w:"";O&&n.push(rt("","",O,r))}else if(s==="response.function_call_arguments.done"){let r=(f=t==null?void 0:t.item_id)!=null?f:"",O=(h=t==null?void 0:t.arguments)!=null?h:"";O&&n.push(rt("","",O,r))}else if(s==="response.output_item.added"){let r=(I=t==null?void 0:t.item)!=null?I:{},O=r==null?void 0:r.type,p=(q=r==null?void 0:r.id)!=null?q:"";O==="reasoning"?e.push(y({type:"thinking",thinking:"",signature:"",item_id:p})):O==="function_call"?n.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"","",p)):O==="message"?e.push(y({type:"text",item_id:p,text:""})):O==="code_interpreter_call"?e.push(y({type:"code",item_id:p,code:(j=r==null?void 0:r.code)!=null?j:"",container_id:(A=r==null?void 0:r.container_id)!=null?A:""})):O==="image_generation_call"?e.push(y({type:"output_media",item_id:p,url:"",mime_type:"image/png",media_type:"image"})):O==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:p,server_label:(L=r==null?void 0:r.server_label)!=null?L:"",tools:(W=r==null?void 0:r.tools)!=null?W:[]})):O==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(U=r==null?void 0:r.name)!=null?U:"",server_label:(z=r==null?void 0:r.server_label)!=null?z:"",arguments:($=r==null?void 0:r.arguments)!=null?$:"",output:r==null?void 0:r.output,error:r==null?void 0:r.error,approval_request_id:r==null?void 0:r.approval_request_id})):O==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:p,name:(H=r==null?void 0:r.name)!=null?H:"",arguments:(F=r==null?void 0:r.arguments)!=null?F:"",server_label:(Q=r==null?void 0:r.server_label)!=null?Q:""})):O==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(Z=r==null?void 0:r.call_id)!=null?Z:"",action:(it=r==null?void 0:r.action)!=null?it:{},status:(at=r==null?void 0:r.status)!=null?at:"in_progress"})):O==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(D=r==null?void 0:r.call_id)!=null?D:"",output:(nt=r==null?void 0:r.output)!=null?nt:[],status:(lt=r==null?void 0:r.status)!=null?lt:"in_progress"})):O==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(gt=r==null?void 0:r.call_id)!=null?gt:"",operation:(ht=r==null?void 0:r.operation)!=null?ht:{},status:(yt=r==null?void 0:r.status)!=null?yt:"in_progress"})):O==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(bt=r==null?void 0:r.call_id)!=null?bt:"",output:(Rt=r==null?void 0:r.output)!=null?Rt:"",status:(kt=r==null?void 0:r.status)!=null?kt:"in_progress"}))}else if(s==="response.content_part.added"){let r=(wt=t==null?void 0:t.part)!=null?wt:{},O=(St=r==null?void 0:r.type)!=null?St:"output_text",p=(st=t==null?void 0:t.item_id)!=null?st:"";O==="output_text"&&e.push(y({type:"text",item_id:p,text:(N=r==null?void 0:r.text)!=null?N:"",annotations:(r==null?void 0:r.annotations)||[]}))}else if(s==="response.content_part.done"){let r=(X=t==null?void 0:t.part)!=null?X:{},O=(tt=r==null?void 0:r.type)!=null?tt:"output_text",p=(ct=t==null?void 0:t.item_id)!=null?ct:"";O==="output_text"&&e.push(y({type:"text",item_id:p,text:(et=r==null?void 0:r.text)!=null?et:"",annotations:(r==null?void 0:r.annotations)||[]}))}else if(s==="response.output_text.annotation.added"){let r=(t==null?void 0:t.annotation)||{},O=r==null?void 0:r.type,p=null;O==="url_citation"?p={type:"url_citation",title:(ot=r==null?void 0:r.title)!=null?ot:"",url:(Tt=r==null?void 0:r.url)!=null?Tt:"",start_index:(Ot=r==null?void 0:r.start_index)!=null?Ot:0,end_index:(At=r==null?void 0:r.end_index)!=null?At:0}:O==="file_citation"?p={type:"file_citation",index:(It=r==null?void 0:r.index)!=null?It:0,file_id:(Lt=r==null?void 0:r.file_id)!=null?Lt:"",filename:(Ut=r==null?void 0:r.filename)!=null?Ut:""}:p=r,e.push(y({type:"text",item_id:(Nt=t==null?void 0:t.item_id)!=null?Nt:"",text:"",annotations:[p]}))}else if(s==="response.code_interpreter_call.in_progress")e.push(y({type:"code",item_id:(qt=t==null?void 0:t.item_id)!=null?qt:"",code:(Mt=t==null?void 0:t.code)!=null?Mt:"",container_id:(jt=t==null?void 0:t.container_id)!=null?jt:""}));else if(s==="response.code_interpreter_call_code.delta")e.push(y({type:"code",item_id:(Wt=t==null?void 0:t.item_id)!=null?Wt:"",code:($t=t==null?void 0:t.delta)!=null?$t:"",container_id:(Kt=t==null?void 0:t.container_id)!=null?Kt:""}));else if(s==="response.output_text.delta"){let r=(Gt=t==null?void 0:t.delta)!=null?Gt:"";r&&e.push(y({type:"text",item_id:(Ft=t==null?void 0:t.item_id)!=null?Ft:"",text:r}))}else if(s==="response.output_text.done")e.push(y({type:"text",item_id:(Dt=t==null?void 0:t.item_id)!=null?Dt:"",text:(Bt=t==null?void 0:t.text)!=null?Bt:""}));else if(s==="response.output_item.done"){let r=(Vt=t==null?void 0:t.item)!=null?Vt:{},O=r==null?void 0:r.type,p=(zt=r==null?void 0:r.id)!=null?zt:"";if(O==="reasoning"){let K=((Jt=r==null?void 0:r.summary)!=null?Jt:[]).map(ut=>{var J;return(J=ut==null?void 0:ut.text)!=null?J:""}).join("");e.push(y({type:"thinking",item_id:p,thinking:K,signature:""}))}else if(O==="function_call")n.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"",(r==null?void 0:r.arguments)||"",p));else if(O==="message"){let B=(Yt=r==null?void 0:r.content)!=null?Yt:[];for(let K of B)(K==null?void 0:K.type)==="output_text"&&e.push(y({type:"text",item_id:p,text:(Xt=K==null?void 0:K.text)!=null?Xt:""}))}else if(O==="code_interpreter_call")e.push(y({type:"code",item_id:p,code:(Zt=r==null?void 0:r.code)!=null?Zt:"",container_id:(Ht=r==null?void 0:r.container_id)!=null?Ht:""}));else if(O==="image_generation_call"){let B=(Qt=r==null?void 0:r.result)!=null?Qt:"",ut=((vt=r==null?void 0:r.output_format)!=null?vt:"png")==="webp"?"image/webp":"image/png",J={};for(let mt of["revised_prompt","background","size","quality","output_format"])(r==null?void 0:r[mt])!=null&&(J[mt]=r[mt]);e.push(y(S({type:"output_media",item_id:p,url:B,mime_type:ut,media_type:"image"},Object.keys(J).length?{provider_metadata:J}:{})))}else O==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:p,server_label:(te=r==null?void 0:r.server_label)!=null?te:"",tools:(ee=r==null?void 0:r.tools)!=null?ee:[],error:r==null?void 0:r.error})):O==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(oe=r==null?void 0:r.name)!=null?oe:"",server_label:(ne=r==null?void 0:r.server_label)!=null?ne:"",arguments:(se=r==null?void 0:r.arguments)!=null?se:"",output:r==null?void 0:r.output,error:r==null?void 0:r.error,approval_request_id:r==null?void 0:r.approval_request_id})):O==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:p,name:(re=r==null?void 0:r.name)!=null?re:"",arguments:(ie=r==null?void 0:r.arguments)!=null?ie:"",server_label:(ae=r==null?void 0:r.server_label)!=null?ae:""})):O==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(le=r==null?void 0:r.call_id)!=null?le:"",action:(ce=r==null?void 0:r.action)!=null?ce:{},status:(pe=r==null?void 0:r.status)!=null?pe:"completed"})):O==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(ue=r==null?void 0:r.call_id)!=null?ue:"",output:(de=r==null?void 0:r.output)!=null?de:[],status:(_e=r==null?void 0:r.status)!=null?_e:"completed"})):O==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(me=r==null?void 0:r.call_id)!=null?me:"",operation:(fe=r==null?void 0:r.operation)!=null?fe:{},status:(ge=r==null?void 0:r.status)!=null?ge:"completed"})):O==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(he=r==null?void 0:r.call_id)!=null?he:"",output:(ye=r==null?void 0:r.output)!=null?ye:"",status:(be=r==null?void 0:r.status)!=null?be:"completed"}))}else if(s==="response.code_interpreter_call_code.done")e.push(y({type:"code",item_id:(Re=t==null?void 0:t.item_id)!=null?Re:"",code:(ke=t==null?void 0:t.code)!=null?ke:"",container_id:(we=t==null?void 0:t.container_id)!=null?we:""}));else if(s==="response.code_interpreter_call.interpreting")e.push(y({type:"code",item_id:(Se=t==null?void 0:t.item_id)!=null?Se:"",code:(xe=t==null?void 0:t.code)!=null?xe:"",container_id:(Ce=t==null?void 0:t.container_id)!=null?Ce:""}));else if(s==="response.code_interpreter_call.completed")e.push(y({type:"code",item_id:(Pe=t==null?void 0:t.item_id)!=null?Pe:"",code:(Ee=t==null?void 0:t.code)!=null?Ee:"",container_id:(Te=t==null?void 0:t.container_id)!=null?Te:""}));else if(s==="response.image_generation_call.in_progress")e.push(y({type:"output_media",item_id:(Oe=t==null?void 0:t.item_id)!=null?Oe:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.generating")e.push(y({type:"output_media",item_id:(Ae=t==null?void 0:t.item_id)!=null?Ae:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.partial_image"){let O=((Ie=t==null?void 0:t.output_format)!=null?Ie:"png")==="webp"?"image/webp":"image/png",p={};for(let B of["background","size","quality","output_format"])(t==null?void 0:t[B])!=null&&(p[B]=t[B]);e.push(y(S({type:"output_media",item_id:(Le=t==null?void 0:t.item_id)!=null?Le:"",url:(Ue=t==null?void 0:t.partial_image_b64)!=null?Ue:"",mime_type:O,media_type:"image"},Object.keys(p).length?{provider_metadata:p}:{})))}else if(s==="response.shell_call_command.added")e.push(y({type:"shell_call",action:{command:(Ne=t==null?void 0:t.command)!=null?Ne:""}}));else if(s==="response.shell_call_command.delta")e.push(y({type:"shell_call",action:{command:(qe=t==null?void 0:t.delta)!=null?qe:""}}));else if(s==="response.shell_call_command.done")e.push(y({type:"shell_call",action:{command:(Me=t==null?void 0:t.command)!=null?Me:""}}));else if(s==="response.shell_call_output_content.delta")e.push(y({type:"shell_call_output",item_id:(je=t==null?void 0:t.item_id)!=null?je:"",output:[(We=t==null?void 0:t.delta)!=null?We:{}]}));else if(s==="response.shell_call_output_content.done")e.push(y({type:"shell_call_output",item_id:($e=t==null?void 0:t.item_id)!=null?$e:"",output:(Ke=t==null?void 0:t.output)!=null?Ke:[]}));else if(s==="response.apply_patch_call_operation_diff.delta")e.push(y({type:"apply_patch_call",item_id:(Ge=t==null?void 0:t.item_id)!=null?Ge:"",operation:{diff:(Fe=t==null?void 0:t.delta)!=null?Fe:""}}));else if(s==="response.apply_patch_call_operation_diff.done")e.push(y({type:"apply_patch_call",item_id:(De=t==null?void 0:t.item_id)!=null?De:"",operation:{diff:(Be=t==null?void 0:t.diff)!=null?Be:""}}));else if(s==="response.completed"){let r=(Ve=t==null?void 0:t.response)!=null?Ve:{},O=(ze=r==null?void 0:r.output)!=null?ze:[];for(let p of O){let B=p==null?void 0:p.type,K=(Je=p==null?void 0:p.id)!=null?Je:"";if(B==="reasoning"){let J=((Ye=p==null?void 0:p.summary)!=null?Ye:[]).map(mt=>{var xt;return(xt=mt==null?void 0:mt.text)!=null?xt:""}).join("");e.push(y({type:"thinking",item_id:K,thinking:J,signature:""}))}else if(B==="function_call")n.push(rt((p==null?void 0:p.call_id)||"",(p==null?void 0:p.name)||"",(p==null?void 0:p.arguments)||"",K));else if(B==="message"){let ut=(P=p==null?void 0:p.content)!=null?P:[];for(let J of ut)(J==null?void 0:J.type)==="output_text"&&e.push(y({type:"text",item_id:K,text:(M=J==null?void 0:J.text)!=null?M:"",annotations:(J==null?void 0:J.annotations)||[]}))}else if(B==="code_interpreter_call")e.push(y({type:"code",item_id:K,code:(i=p==null?void 0:p.code)!=null?i:"",container_id:(c=p==null?void 0:p.container_id)!=null?c:""}));else if(B==="image_generation_call"){let ut=(E=p==null?void 0:p.result)!=null?E:"",mt=((pt=p==null?void 0:p.output_format)!=null?pt:"png")==="webp"?"image/webp":"image/png",xt={};for(let _o of["revised_prompt","background","size","quality","output_format"])(p==null?void 0:p[_o])!=null&&(xt[_o]=p[_o]);e.push(y(S({type:"output_media",item_id:K,url:ut,mime_type:mt,media_type:"image"},Object.keys(xt).length?{provider_metadata:xt}:{})))}else B==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:K,server_label:(To=p==null?void 0:p.server_label)!=null?To:"",tools:(Oo=p==null?void 0:p.tools)!=null?Oo:[],error:p==null?void 0:p.error})):B==="mcp_call"?e.push(y({type:"mcp_call",item_id:K,name:(Ao=p==null?void 0:p.name)!=null?Ao:"",server_label:(Io=p==null?void 0:p.server_label)!=null?Io:"",arguments:(Lo=p==null?void 0:p.arguments)!=null?Lo:"",output:p==null?void 0:p.output,error:p==null?void 0:p.error,approval_request_id:p==null?void 0:p.approval_request_id})):B==="mcp_approval_request"?e.push(y({type:"mcp_approval_request",item_id:K,name:(Uo=p==null?void 0:p.name)!=null?Uo:"",arguments:(No=p==null?void 0:p.arguments)!=null?No:"",server_label:(qo=p==null?void 0:p.server_label)!=null?qo:""})):B==="shell_call"?e.push(y({type:"shell_call",item_id:K,call_id:(Mo=p==null?void 0:p.call_id)!=null?Mo:"",action:(jo=p==null?void 0:p.action)!=null?jo:{},status:(Wo=p==null?void 0:p.status)!=null?Wo:"completed"})):B==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:K,call_id:($o=p==null?void 0:p.call_id)!=null?$o:"",output:(Ko=p==null?void 0:p.output)!=null?Ko:[],status:(Go=p==null?void 0:p.status)!=null?Go:"completed"})):B==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:K,call_id:(Fo=p==null?void 0:p.call_id)!=null?Fo:"",operation:(Do=p==null?void 0:p.operation)!=null?Do:{},status:(Bo=p==null?void 0:p.status)!=null?Bo:"completed"})):B==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:K,call_id:(Vo=p==null?void 0:p.call_id)!=null?Vo:"",output:(zo=p==null?void 0:p.output)!=null?zo:"",status:(Jo=p==null?void 0:p.status)!=null?Jo:"completed"}))}}let a=Ct(e,n||[]);return Pt(a,o)},nn=(t,o)=>{var a,l,u,d;let e=[],n=[];if("contentBlockDelta"in t){let _=((a=t.contentBlockDelta)==null?void 0:a.delta)||{};if("reasoningContent"in _){let m=((l=_.reasoningContent)==null?void 0:l.text)||"",R=((u=_.reasoningContent)==null?void 0:u.signature)||"";e.push(y({type:"thinking",thinking:m,signature:R}))}else if("text"in _)e.push(y({type:"text",text:_.text||""}));else if("toolUse"in _){let m=_.toolUse||{};n.push(rt(m.toolUseId||"",m.name||"",m.input||""))}}else if("contentBlockStart"in t){let _=((d=t.contentBlockStart)==null?void 0:d.start)||{};if("toolUse"in _){let m=_.toolUse||{};n.push(rt(m.toolUseId||"",m.name||"",""))}}let s=Ct(e,n);return Pt(s,o)},ws=["size","quality","background","output_format"],sn=(t,o)=>{var a,l,u,d,_,m,R;let e=[],n=(a=t==null?void 0:t.type)!=null?a:"";if(n==="image_generation.partial_image"){let k=(l=t==null?void 0:t.b64_json)!=null?l:"";if(k){let g=(u=t==null?void 0:t.output_format)!=null?u:"png",C=(d=Ho[g])!=null?d:"image/png",x={},b=t==null?void 0:t.partial_image_index;b!=null&&(x.partial_image_index=b),e.push(y(S({type:"output_media",url:k,mime_type:C,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}}else if(n==="image_generation.completed"){let k=(_=t==null?void 0:t.b64_json)!=null?_:"",g=(m=t==null?void 0:t.output_format)!=null?m:"png",C=(R=Ho[g])!=null?R:"image/png",x={};for(let b of ws)(t==null?void 0:t[b])!=null&&(x[b]=t[b]);e.push(y(S({type:"output_media",url:k,mime_type:C,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:o}};var pn=["openai","openai.azure"],no=t=>{var s,a,l,u,d,_,m,R,k,g,C,x,b,w,f,h,I,q,j,A,L,W,U,z,$,H,F,Q,Z,it,at,D,nt,lt,gt,ht,yt,bt,Rt,kt,wt,St,st,N,X,tt,ct,et,ot,Tt,Ot,At,It,Lt,Ut,Nt,qt,Mt,jt,Wt,$t,Kt,Gt,Ft,Dt,Bt,Vt,zt,Jt,Yt,Xt,Zt,Ht,Qt,vt,te,ee,oe,ne,se,re,ie,ae,le,ce,pe,ue,de,_e,me,fe,ge,he,ye,be,Re,ke,we,Se,xe,Ce,Pe,Ee,Te,Oe,Ae,Ie,Le,Ue,Ne,qe,Me,je,We,$e,Ke,Ge,Fe,De,Be,Ve,ze,Je,Ye;let o={id:null,object:"response",created_at:null,status:null,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:null,output:[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{},store:!0,temperature:1,text:void 0,tool_choice:"auto",tools:[],top_p:1,truncation:"disabled",usage:null,user:null,metadata:{}},e={},n={};for(let P of t){let M=P==null?void 0:P.type;if(M==="response.created"){let i=P.response||{};o.id=(s=i.id)!=null?s:o.id,o.created_at=(a=i.created_at)!=null?a:o.created_at,o.model=(l=i.model)!=null?l:o.model,o.status=(u=i.status)!=null?u:o.status,o.parallel_tool_calls=(d=i.parallel_tool_calls)!=null?d:o.parallel_tool_calls,o.temperature=(_=i.temperature)!=null?_:o.temperature,o.tool_choice=(m=i.tool_choice)!=null?m:o.tool_choice,o.tools=(R=i.tools)!=null?R:o.tools,o.top_p=(k=i.top_p)!=null?k:o.top_p,o.truncation=(g=i.truncation)!=null?g:o.truncation,o.max_output_tokens=(C=i.max_output_tokens)!=null?C:o.max_output_tokens,o.previous_response_id=(x=i.previous_response_id)!=null?x:o.previous_response_id,o.store=(b=i.store)!=null?b:o.store,o.user=(w=i.user)!=null?w:o.user,o.metadata=(f=i.metadata)!=null?f:o.metadata;let c=i.text;c&&(o.text=c);let E=i.reasoning;E&&(o.reasoning=E);continue}if(M==="response.in_progress"){let i=P.response||{};o.status=(h=i.status)!=null?h:o.status;continue}if(M==="response.output_item.added"){let i=P.item||{},c=i.id,E=i.type,pt=P.output_index;pt!=null&&c&&(n[pt]=c),E==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(I=i.status)!=null?I:"in_progress"}:E==="function_call"?e[c]={type:"function_call",id:c,call_id:i.call_id,name:i.name,arguments:"",status:(q=i.status)!=null?q:"in_progress"}:E==="message"?e[c]={type:"message",id:c,role:(j=i.role)!=null?j:"assistant",content:[],status:(A=i.status)!=null?A:"in_progress"}:E==="code_interpreter_call"?e[c]={type:"code_interpreter_call",id:c,container_id:i.container_id,code:(L=i.code)!=null?L:"",status:(W=i.status)!=null?W:"in_progress"}:E==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(U=i.status)!=null?U:"in_progress",revised_prompt:(z=i.revised_prompt)!=null?z:"",result:($=i.result)!=null?$:"",background:i.background,size:i.size,quality:i.quality,output_format:i.output_format}:E==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(H=i.status)!=null?H:"in_progress"}:E==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(F=i.status)!=null?F:"in_progress"}:E==="mcp_list_tools"?e[c]={type:"mcp_list_tools",id:c,server_label:(Q=i.server_label)!=null?Q:"",tools:(Z=i.tools)!=null?Z:[],error:(it=i.error)!=null?it:null}:E==="mcp_call"?e[c]={type:"mcp_call",id:c,name:(at=i.name)!=null?at:"",server_label:(D=i.server_label)!=null?D:"",arguments:(nt=i.arguments)!=null?nt:"",output:(lt=i.output)!=null?lt:null,error:(gt=i.error)!=null?gt:null,approval_request_id:(ht=i.approval_request_id)!=null?ht:null,status:(yt=i.status)!=null?yt:"in_progress"}:E==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(bt=i.name)!=null?bt:"",arguments:(Rt=i.arguments)!=null?Rt:"",server_label:(kt=i.server_label)!=null?kt:""}:E==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(wt=i.call_id)!=null?wt:"",action:(St=i.action)!=null?St:{},status:(st=i.status)!=null?st:"in_progress"}:E==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(N=i.call_id)!=null?N:"",output:(X=i.output)!=null?X:[],status:(tt=i.status)!=null?tt:"in_progress"}:E==="apply_patch_call"?e[c]={type:"apply_patch_call",id:c,call_id:(ct=i.call_id)!=null?ct:"",operation:(et=i.operation)!=null?et:{},status:(ot=i.status)!=null?ot:"in_progress"}:E==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(Tt=i.call_id)!=null?Tt:"",output:(Ot=i.output)!=null?Ot:"",status:(At=i.status)!=null?At:"in_progress"});continue}if(M==="response.reasoning_summary_part.added"){let i=P.item_id,c=P.part||{};if(i in e&&e[i].type==="reasoning"){let E={type:(It=c.type)!=null?It:"summary_text",text:(Lt=c.text)!=null?Lt:""};e[i].summary.push(E)}continue}if(M==="response.reasoning_summary_text.delta"){let i=P.item_id,c=(Ut=P.delta)!=null?Ut:"",E=(Nt=P.summary_index)!=null?Nt:0;if(i in e&&e[i].type==="reasoning"){for(;e[i].summary.length<=E;)e[i].summary.push({type:"summary_text",text:""});e[i].summary[E].text+=c}continue}if(M==="response.reasoning_summary_text.done"){let i=P.item_id,c=(qt=P.text)!=null?qt:"",E=(Mt=P.summary_index)!=null?Mt:0;if(i in e&&e[i].type==="reasoning"){for(;e[i].summary.length<=E;)e[i].summary.push({type:"summary_text",text:""});e[i].summary[E].text=c}continue}if(M==="response.reasoning_summary_part.done"){let i=P.item_id,c=P.part||{};if(i in e&&e[i].type==="reasoning"){let E=(jt=P.summary_index)!=null?jt:0;E<e[i].summary.length&&(e[i].summary[E]={type:(Wt=c.type)!=null?Wt:"summary_text",text:($t=c.text)!=null?$t:""})}continue}if(M==="response.function_call_arguments.delta"){let i=P.item_id,c=(Kt=P.delta)!=null?Kt:"";i in e&&(e[i].arguments=`${e[i].arguments||""}${c}`);continue}if(M==="response.function_call_arguments.done"){let i=P.item_id,c=(Gt=P.arguments)!=null?Gt:"";i in e&&(e[i].arguments=c);continue}if(M==="response.content_part.added"){let i=P.part||{},c=Object.values(e).find(E=>E.type==="message");if(c){let E={type:(Ft=i.type)!=null?Ft:"output_text",text:(Dt=i.text)!=null?Dt:"",annotations:(Bt=i.annotations)!=null?Bt:[]};c.content.push(E)}continue}if(M==="response.output_text.delta"){let i=(Vt=P.delta)!=null?Vt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let E=c.content[c.content.length-1];E&&E.type==="output_text"&&(E.text=`${E.text||""}${i}`);break}continue}if(M==="response.output_text.done"){let i=(zt=P.text)!=null?zt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let E=c.content[c.content.length-1];E&&E.type==="output_text"&&(E.text=i);break}continue}if(M==="response.output_item.done"){let i=P.item||{},c=i.id;c in e&&(e[c].status=(Jt=i.status)!=null?Jt:"completed",i.type==="reasoning"?e[c].summary=(Yt=i.summary)!=null?Yt:e[c].summary:i.type==="function_call"?(e[c].arguments=(Xt=i.arguments)!=null?Xt:e[c].arguments,e[c].call_id=(Zt=i.call_id)!=null?Zt:e[c].call_id,e[c].name=(Ht=i.name)!=null?Ht:e[c].name):i.type==="message"?(e[c].content=(Qt=i.content)!=null?Qt:e[c].content,e[c].role=(vt=i.role)!=null?vt:e[c].role):i.type==="image_generation_call"?(e[c].result=(te=i.result)!=null?te:e[c].result,e[c].revised_prompt=(ee=i.revised_prompt)!=null?ee:e[c].revised_prompt,e[c].background=(oe=i.background)!=null?oe:e[c].background,e[c].size=(ne=i.size)!=null?ne:e[c].size,e[c].quality=(se=i.quality)!=null?se:e[c].quality,e[c].output_format=(re=i.output_format)!=null?re:e[c].output_format):i.type==="code_interpreter_call"?(e[c].code=(ie=i.code)!=null?ie:e[c].code,e[c].container_id=(ae=i.container_id)!=null?ae:e[c].container_id):i.type==="mcp_list_tools"?(e[c].tools=(le=i.tools)!=null?le:e[c].tools,e[c].error=(ce=i.error)!=null?ce:e[c].error):i.type==="mcp_call"?(e[c].name=(pe=i.name)!=null?pe:e[c].name,e[c].arguments=(ue=i.arguments)!=null?ue:e[c].arguments,e[c].output=(de=i.output)!=null?de:e[c].output,e[c].error=(_e=i.error)!=null?_e:e[c].error,e[c].server_label=(me=i.server_label)!=null?me:e[c].server_label):i.type==="mcp_approval_request"?(e[c].name=(fe=i.name)!=null?fe:e[c].name,e[c].arguments=(ge=i.arguments)!=null?ge:e[c].arguments,e[c].server_label=(he=i.server_label)!=null?he:e[c].server_label):i.type==="shell_call"?(e[c].action=(ye=i.action)!=null?ye:e[c].action,e[c].call_id=(be=i.call_id)!=null?be:e[c].call_id):i.type==="shell_call_output"?(e[c].output=(Re=i.output)!=null?Re:e[c].output,e[c].call_id=(ke=i.call_id)!=null?ke:e[c].call_id):i.type==="apply_patch_call"?(e[c].operation=(we=i.operation)!=null?we:e[c].operation,e[c].call_id=(Se=i.call_id)!=null?Se:e[c].call_id):i.type==="apply_patch_call_output"?(e[c].output=(xe=i.output)!=null?xe:e[c].output,e[c].call_id=(Ce=i.call_id)!=null?Ce:e[c].call_id):(i.type==="web_search_call"||i.type==="file_search_call")&&(e[c].action=i.action),o.output.push(e[c]));continue}if(M==="response.image_generation_call.in_progress"){let i=P.item_id;i in e&&(e[i].status="in_progress");continue}if(M==="response.image_generation_call.generating"){let i=P.item_id;i in e&&(e[i].status="generating");continue}if(M==="response.image_generation_call.partial_image"){let i=P.item_id;i in e&&(e[i].result=(Pe=P.partial_image_b64)!=null?Pe:e[i].result,e[i].background=(Ee=P.background)!=null?Ee:e[i].background,e[i].size=(Te=P.size)!=null?Te:e[i].size,e[i].quality=(Oe=P.quality)!=null?Oe:e[i].quality,e[i].output_format=(Ae=P.output_format)!=null?Ae:e[i].output_format);continue}if(M==="response.shell_call_command.added"){let i=n[P.output_index];if(i&&i in e){let c=e[i].action||{commands:[]};c.commands||(c.commands=[]),c.commands[P.command_index]=(Ie=P.command)!=null?Ie:"",e[i].action=c}continue}if(M==="response.shell_call_command.delta"){let i=n[P.output_index];if(i&&i in e){let c=e[i].action||{commands:[]};c.commands||(c.commands=[]);let E=(Le=P.command_index)!=null?Le:0;c.commands[E]=((Ue=c.commands[E])!=null?Ue:"")+((Ne=P.delta)!=null?Ne:""),e[i].action=c}continue}if(M==="response.shell_call_command.done"){let i=n[P.output_index];if(i&&i in e){let c=e[i].action||{commands:[]};c.commands||(c.commands=[]),c.commands[P.command_index]=(qe=P.command)!=null?qe:"",e[i].action=c}continue}if(M==="response.shell_call_output_content.delta"){let i=P.item_id;if(i&&i in e){e[i].output||(e[i].output=[]);let c=(Me=P.command_index)!=null?Me:0,E=(je=e[i].output[c])!=null?je:{stdout:"",stderr:""},pt=(We=P.delta)!=null?We:{};pt.stdout&&(E.stdout=(($e=E.stdout)!=null?$e:"")+pt.stdout),pt.stderr&&(E.stderr=((Ke=E.stderr)!=null?Ke:"")+pt.stderr),e[i].output[c]=E}continue}if(M==="response.shell_call_output_content.done"){let i=P.item_id;i&&i in e&&(e[i].output=(Ge=P.output)!=null?Ge:e[i].output);continue}if(M==="response.apply_patch_call_operation_diff.delta"){let i=P.item_id;if(i&&i in e){let c=e[i].operation||{};c.diff=((Fe=c.diff)!=null?Fe:"")+((De=P.delta)!=null?De:""),e[i].operation=c}continue}if(M==="response.apply_patch_call_operation_diff.done"){let i=P.item_id;if(i&&i in e){let c=e[i].operation||{};c.diff=(Be=P.diff)!=null?Be:c.diff,e[i].operation=c}continue}if(M==="response.completed"){let i=P.response||{};o.status=(ze=(Ve=i.status)!=null?Ve:o.status)!=null?ze:"completed",o.usage=(Je=i.usage)!=null?Je:o.usage,o.output=(Ye=i.output)!=null?Ye:o.output,i.reasoning&&(o.reasoning=i.reasoning);continue}}return o},ho=t=>{var u,d,_,m,R,k,g,C,x,b;let o=null,e,n={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},s=t.at(-1);if(!s)return n;let a;for(let w of t){if(w.choices.length===0)continue;let f=w.choices[0].delta;f.content&&(o=`${o||""}${f.content||""}`),f.function_call&&(e={name:`${e?e.name:""}${f.function_call.name||""}`,arguments:`${e?e.arguments:""}${f.function_call.arguments||""}`});let h=(u=f.tool_calls)==null?void 0:u[0];if(h){a=a||[];let I=a.at(-1);if(!I||h.id){a.push({id:h.id||"",type:h.type||"function",function:{name:((d=h.function)==null?void 0:d.name)||"",arguments:((_=h.function)==null?void 0:_.arguments)||""}});continue}I.function.name=`${I.function.name}${((m=h.function)==null?void 0:m.name)||""}`,I.function.arguments=`${I.function.arguments}${((R=h.function)==null?void 0:R.arguments)||""}`}}let l=t[0].choices.at(0);return n.choices.push({finish_reason:(k=l==null?void 0:l.finish_reason)!=null?k:"stop",index:(g=l==null?void 0:l.index)!=null?g:0,logprobs:(C=l==null?void 0:l.logprobs)!=null?C:null,message:{role:"assistant",content:o,function_call:e||void 0,tool_calls:a||void 0,refusal:(x=l==null?void 0:l.delta.refusal)!=null?x:null}}),n.id=s.id,n.model=s.model,n.created=s.created,n.system_fingerprint=s.system_fingerprint,n.usage=(b=s.usage)!=null?b:void 0,n},rn=t=>{let o={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},e=t.at(-1);if(!e)return o;let n="";for(let s of t)s.choices.length>0&&s.choices[0].text&&(n=`${n}${s.choices[0].text}`);return o.choices[0].text=n,o.id=e.id,o.created=e.created,o.model=e.model,o.system_fingerprint=e.system_fingerprint,o.usage=e.usage,o},yo=t=>{var m,R,k,g,C,x;let o={id:"",model:"",content:[],role:"assistant",type:"message",stop_reason:"stop_sequence",stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:null,service_tier:null}};if(!t.at(-1))return o;let n=null,s=null,a="",l="",u="",d="",_={};for(let b of t)if(b.type==="message_start")o=S({},b.message);else if(b.type==="content_block_start")n=S({},b.content_block),s="index"in b&&typeof b.index=="number"?b.index:null,n.type==="thinking"?(a="",l=""):n.type==="text"?u="":(n.type==="tool_use"||n.type==="server_tool_use")&&(d="");else if(b.type==="content_block_delta"){let w=b.delta,f="index"in b&&typeof b.index=="number"?b.index:null;if((w==null?void 0:w.type)==="citations_delta"){let h=w.citation;if(h&&typeof h=="object"&&h.type==="web_search_result_location"&&f!==null){let I=S(S({type:"url_citation",url:(m=h.url)!=null?m:"",title:(R=h.title)!=null?R:"",start_index:(k=h.start_index)!=null?k:0,end_index:(g=h.end_index)!=null?g:0},h.cited_text!=null?{cited_text:h.cited_text}:{}),h.encrypted_index!=null?{encrypted_index:h.encrypted_index}:{});_[f]||(_[f]=[]),_[f].push(I)}}else n!==null&&(n.type==="thinking"?(w&&"signature"in w&&(a=w.signature||""),w&&"thinking"in w&&(l+=w.thinking||"")):n.type==="text"?w&&"text"in w&&(u+=w.text||""):(n.type==="tool_use"||n.type==="server_tool_use")&&(w==null?void 0:w.type)==="input_json_delta"&&(d+=w.partial_json||""))}else if(b.type==="content_block_stop"&&n!==null){if(n.type==="thinking")n.signature=a,n.thinking=l;else if(n.type==="text")n.text=u,n.citations=null,s!==null&&((C=_[s])!=null&&C.length)&&(n.annotations=_[s]);else if(n.type==="tool_use"||n.type==="server_tool_use")try{n.input=d?JSON.parse(d):{}}catch(w){n.input={}}o.content.push(n),n=null,s=null,a="",l="",u="",d=""}else b.type==="message_delta"&&("usage"in b&&b.usage&&(o.usage=Y(S({},o.usage),{output_tokens:(x=b.usage.output_tokens)!=null?x:0})),"delta"in b&&b.delta&&("stop_reason"in b.delta&&b.delta.stop_reason!==void 0&&(o.stop_reason=b.delta.stop_reason),"stop_sequence"in b.delta&&b.delta.stop_sequence!==void 0&&(o.stop_sequence=b.delta.stop_sequence)));return o},an=t=>{let o={completion:"",id:"",model:"",stop_reason:"",type:"completion"},e=t.at(-1);if(!e)return o;let n="";for(let s of t)n=`${n}${s.completion}`;return o.completion=n,o.id=e.id,o.model=e.model,o.stop_reason=e.stop_reason,o},Ss=t=>{var l,u,d,_,m,R,k,g,C,x;let o=null,e={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},n=t.at(-1).data;if(!n)return e;let s;for(let b of t){if(b.data.choices.length===0)continue;let w=b.data.choices[0].delta;w.content&&(o=`${o||""}${w.content||""}`);let f=(l=w.toolCalls)==null?void 0:l[0];if(f){s=s||[];let h=s.at(-1);if(!h||f.id){s.push({id:f.id||"",type:f.type||"function",function:{name:((u=f.function)==null?void 0:u.name)||"",arguments:((d=f.function)==null?void 0:d.arguments)||""}});continue}h.function.name=`${h.function.name}${((_=f.function)==null?void 0:_.name)||""}`,h.function.arguments=`${h.function.arguments}${((m=f.function)==null?void 0:m.arguments)||""}`}}let a=t[0].data.choices.at(0);return e.choices.push({finish_reason:(R=a==null?void 0:a.finish_reason)!=null?R:"stop",index:(k=a==null?void 0:a.index)!=null?k:0,logprobs:(g=a==null?void 0:a.logprobs)!=null?g:null,message:{role:"assistant",content:o,tool_calls:s||void 0,refusal:(C=a==null?void 0:a.delta.refusal)!=null?C:null}}),e.id=n.id,e.model=n.model,e.created=n.created,e.usage=(x=n.usage)!=null?x:void 0,e},ln=t=>{let o={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},e=[],n=null,s="",a="",l="",u="";for(let d of t)if("contentBlockStart"in d){let _=d.contentBlockStart;if("start"in _&&"toolUse"in _.start){let m=_.start.toolUse;n={toolUse:{toolUseId:m.toolUseId,name:m.name}},s=""}}else if("contentBlockDelta"in d){let _=d.contentBlockDelta.delta;if("text"in _)a+=_.text;else if("reasoningContent"in _){let m=_.reasoningContent;"text"in m?u+=m.text:"signature"in m&&(l+=m.signature)}else if("toolUse"in _&&"input"in _.toolUse){let m=_.toolUse.input;if(s+=m,!m.trim())continue}}else if("contentBlockStop"in d)if(n&&s){try{n.toolUse.input=JSON.parse(s)}catch(_){n.toolUse.input={}}e.push(n),n=null,s=""}else a?(e.push({text:a}),a=""):u&&l&&(e.push({reasoningContent:{reasoningText:{text:u,signature:l}}}),u="",l="");else if("messageStop"in d)o.stopReason=d.messageStop.stopReason;else if("metadata"in d){let _=d.metadata;o.usage=(_==null?void 0:_.usage)||{},o.metrics=(_==null?void 0:_.metrics)||{}}return o.output.message={role:"assistant",content:e},o},xs=(t,o,e,n,s,a,l,u,d)=>{var k,g,C;let _=S({},l),m=[];if(t){let x={text:t,thought:!0};u&&(x.thoughtSignature=u),m.push(x)}if(o){let x={text:o,thought:null};d&&(x.thoughtSignature=d),m.push(x)}for(let x of s)m.push({executableCode:x});for(let x of a)m.push({codeExecutionResult:x});for(let x of n)m.push({inlineData:x});for(let x of e)m.push({functionCall:x});m.length>0&&((g=(k=_.candidates)==null?void 0:k[0])!=null&&g.content)&&(_.candidates[0].content.parts=m);let R=(C=l==null?void 0:l.candidates)==null?void 0:C[0];return R&&(_.candidates||(_.candidates=[]),_.candidates[0]||(_.candidates[0]={content:{parts:[]}}),R.groundingMetadata!=null&&(_.candidates[0].groundingMetadata=R.groundingMetadata),R.urlContextMetadata!=null&&(_.candidates[0].urlContextMetadata=R.urlContextMetadata),R.citationMetadata!=null&&(_.candidates[0].citationMetadata=R.citationMetadata)),_},un=t=>{var m,R,k,g,C,x,b;let{GenerateContentResponse:o}=require("@google/genai");if(!t.length)return new o;let e="",n="",s=[],a=[],l=[],u=[],d=null,_=null;for(let w of t)if(w.candidates&&((R=(m=w.candidates[0])==null?void 0:m.content)!=null&&R.parts))for(let f of w.candidates[0].content.parts)if(f.text!=null)f.thought===!0?(e+=f.text,f.thoughtSignature&&(d=f.thoughtSignature)):(n+=f.text,f.thoughtSignature&&(_=f.thoughtSignature));else if(f.functionCall)s.push(f.functionCall);else if(f.inlineData){let h=f.inlineData;a.push({data:(k=h.data)!=null?k:"",mimeType:(g=h.mimeType)!=null?g:"image/png"})}else f.executableCode?l.push({code:(C=f.executableCode.code)!=null?C:"",language:f.executableCode.language}):f.codeExecutionResult&&u.push({output:(x=f.codeExecutionResult.output)!=null?x:"",outcome:(b=f.codeExecutionResult.outcome)!=null?b:"OUTCOME_OK"});return xs(e,n,s,a,l,u,t[t.length-1],d,_)},Cs=t=>un(t),Ps=t=>un(t),Es=["size","quality","background","output_format"],bo=t=>{var a,l,u,d,_;let o={created:null,data:[],usage:null},e={},n="png";for(let m of t){let R=(a=m==null?void 0:m.type)!=null?a:"";if(R==="image_generation.partial_image"){let k=m.b64_json;if(k!=null){let g=(l=m.partial_image_index)!=null?l:0;e[g]=k}}else if(R==="image_generation.completed"){let k=m.b64_json;if(k!=null){let g=(u=m.partial_image_index)!=null?u:0;e[g]=k}o.created=(d=m.created_at)!=null?d:o.created,o.usage=(_=m.usage)!=null?_:o.usage;for(let g of Es)m[g]!=null&&(o[g]=m[g]);m.output_format&&(n=m.output_format)}}o.output_format||(o.output_format=n);let s=Object.keys(e).map(Number).sort((m,R)=>m-R);return s.length>0&&(o.data=s.map(m=>({b64_json:e[m]}))),o},dn=(t,o="openai.chat.completions.create")=>{if(o==="openai.responses.create"||o==="openai.AzureOpenAI.responses.create")return no(t);if(o==="openai.images.generate"||o==="openai.AzureOpenAI.images.generate")return bo(t);if("completion"in t[0])return t.reduce((e,n)=>Y(S({},n),{completion:`${e.completion}${n.completion}`}),{});if(o==="anthropic.messages.create")return yo(t);if("text"in t[0].choices[0]){let e="";for(let s of t)e=`${e}${s.choices[0].text}`;let n=structuredClone(t.at(-1));return n.choices[0].text=e,n}if("delta"in t[0].choices[0]){let e=ho(t);return e.choices[0]=S(S({},e.choices[0]),e.choices[0].message),e}return""},cn=(t,o,e)=>{let n=o.model.provider,s=o.model.name;if(n==="anthropic"||n==="anthropic.bedrock"||n==="vertexai"&&s.startsWith("claude"))return tn(t,o,e==null?void 0:e.anthropicBlockTypeByIndex);if(n==="google"||n==="vertexai"&&s.startsWith("gemini"))return en(t,o);if(n==="amazon.bedrock")return nn(t,o);if(n==="mistral")return go(t.data,o);if(n==="openai"||n==="openai.azure"){let a=o.model.api_type||"chat-completions";return a==="responses"?on(t,o):a==="images"?sn(t,o):go(t,o)}return null};function _n(t,o,e,n){return eo(this,null,function*(){var k,g,C;let s={request_id:null,raw_response:null,prompt_blueprint:null},a={},l=n.model.provider;l=="amazon.bedrock"&&(a=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let u=[],d=l==="anthropic"||l==="anthropic.bedrock"||l==="vertexai"&&((C=(g=(k=n.model)==null?void 0:k.name)==null?void 0:g.startsWith)==null?void 0:C.call(g,"claude")),_={};try{for(var x=oo(t),b,w,f;b=!(w=yield new ft(x.next())).done;b=!1){let h=w.value;u.push(h),d&&(h==null?void 0:h.type)==="content_block_start"&&h.content_block&&(_[h.index]=h.content_block.type),s.raw_response=h,s.prompt_blueprint=cn(h,n,{anthropicBlockTypeByIndex:_}),yield s}}catch(w){f=[w]}finally{try{b&&(w=x.return)&&(yield new ft(w.call(x)))}finally{if(f)throw f[0]}}let m=e(u);l==="amazon.bedrock"&&(m.ResponseMetadata=a),s.raw_response=m,s.prompt_blueprint=cn(m,n),yield s;let R=yield new ft(o({request_response:m}));s.request_id=R.request_id,s.prompt_blueprint=R.prompt_blueprint,yield s})}var mn={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:ho},completion:{function_name:"openai.completions.create",stream_function:rn}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:no}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:bo}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:yo},completion:{function_name:"anthropic.completions.create",stream_function:an}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:ho},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:rn}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:no},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:no}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:bo}},google:{chat:{function_name:"google.convo.send_message",stream_function:Cs},completion:{function_name:"google.model.generate_content",stream_function:Ps}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:ln},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:ln}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:yo},completion:{function_name:"anthropic.completions.create",stream_function:an}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:Ss},completion:{function_name:"",stream_function:null}}};var bn="1.3.0",Ts=()=>{var t;if(typeof process!="undefined"&&((t=process.versions)!=null&&t.node)){let o=process.versions.node.split(".");return`${o[0]}.${o[1]}`}return"unknown"},Os=Ts(),As=`promptlayer-js/${bn} (node ${Os})`,V=()=>({"User-Agent":As,"X-SDK-Version":bn}),Ro="SET_WORKFLOW_COMPLETE";function Is(t,o,e,n){return T(this,null,function*(){let s=yield G(`${t}/workflow-version-execution-results?workflow_version_execution_id=${o}&return_all_outputs=${e}`,S({headers:n},V()));if(!s.ok)throw new Error("Failed to fetch final output");return s.json()})}function Rn(t,o,e,n,s){return function(a){return T(this,null,function*(){if(a.name===Ro)try{let l=JSON.parse(a.data),u=l.result_code,d;if(u==="OK"||u==null)d=l.final_output;else if(u==="EXCEEDS_SIZE_LIMIT")d=yield Is(t,e,n,s),o.resolve(d);else throw new Error(`Unsupported final output code: ${u}`);o.resolve(d)}catch(l){o.reject(l)}})}}function Ls(u){return T(this,arguments,function*({token:t,channelName:o,executionId:e,returnAllOutputs:n,headers:s,timeout:a,baseURL:l}){let d=new gn.default.Realtime(t),_=d.channels.get(o),m={},R=new Promise((g,C)=>{m.resolve=g,m.reject=C}),k=Rn(l,m,e,n,s);yield _.subscribe(Ro,k);try{return yield new Promise((g,C)=>{let x=setTimeout(()=>{C(new Error("Workflow execution did not complete properly (timeout)"))},a);R.then(b=>{clearTimeout(x),g(b)}).catch(b=>{clearTimeout(x),C(b)})})}finally{console.log("Closing client"),_.unsubscribe(Ro,k),d.close(),console.log("Closed client")}})}var G=(t,o)=>T(null,null,function*(){return(0,yn.default)(()=>T(null,null,function*(){let e=yield fetch(t,o);if(e.status>=500&&e.status<600||e.status===429)throw new Error(`Server error: ${e.status} ${e.statusText}`);return e}),{retries:3,factor:2,minTimeout:2e3,maxTimeout:15e3,randomize:!0,onFailedAttempt:e=>{console.info(`PromptLayer API request attempt ${e.attemptNumber} failed. ${e.retriesLeft} retries left.`)}})}),kn=(t,o,e,n=!0)=>T(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?Ns(t,o,e.request_response,e,n):yield wn(t,o,e,n)}),wn=(t,o,e,n=!0)=>T(null,null,function*(){try{let s=yield G(`${o}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify(e)}),a=yield s.json();if(s.status!==200){let l=a.message||a.error||"Failed to log request";if(n)throw new Error(l);v(a,"WARNING: While logging your request, PromptLayer experienced the following error:")}if(a&&e.return_pl_id)return[e.request_response,a.request_id]}catch(s){if(n)throw s;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${s}`)}return e.request_response}),Sn=(t,o,e,n=!0)=>T(null,null,function*(){try{let s=yield G(`${o}/library-track-metadata`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),a=yield s.json();if(s.status!==200){let l=a.message||a.error||"Failed to track metadata";if(n)throw new Error(l);return v(a,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(s){if(n)throw s;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),xn=(t,o,e,n=!0)=>T(null,null,function*(){try{let s=yield G(`${o}/library-track-score`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),a=yield s.json();if(s.status!==200){let l=a.message||a.error||"Failed to track score";if(n)throw new Error(l);return v(a,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(s){if(n)throw s;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),Cn=(t,o,e,n=!0)=>T(null,null,function*(){try{let s=yield G(`${o}/library-track-prompt`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),a=yield s.json();if(s.status!==200){let l=a.message||a.error||"Failed to track prompt";if(n)throw new Error(l);return v(a,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(s){if(n)throw s;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${s}`),!1}return!0}),Pn=(t,o,e,n=!0)=>T(null,null,function*(){try{let s=yield G(`${o}/track-group`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),a=yield s.json();if(s.status!==200){let l=a.message||a.error||"Failed to track group";if(n)throw new Error(l);return v(a,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(s){if(n)throw s;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${s}`),!1}return!0}),En=(t,o,e=!0)=>T(null,null,function*(){try{let n=yield G(`${o}/create-group`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify({api_key:t})}),s=yield n.json();if(n.status!==200){let a=s.message||s.error||"Failed to create group";if(e)throw new Error(a);return v(s,"WARNING: While creating a group PromptLayer had the following error"),!1}return s.id}catch(n){if(e)throw n;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${n}`),!1}}),Tn=(t,o,e,n,s=!0)=>T(null,null,function*(){try{let a=new URL(`${o}/prompt-templates/${e}`),l=yield G(a,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},V()),body:JSON.stringify(n)}),u=yield l.json();if(l.status!==200){let d=u.message||u.error||"Failed to fetch prompt template";if(s)throw new Error(d);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${d}`),null}return u.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${u.warning}`),u}catch(a){if(s)throw a;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${a}`),null}}),On=(t,o,e,n=!0)=>T(null,null,function*(){let s=yield G(`${o}/rest/prompt-templates`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},V()),body:JSON.stringify({prompt_template:S({},e),prompt_version:S({},e),release_labels:e.release_labels?e.release_labels:void 0})}),a=yield s.json();if(s.status!==200&&s.status!==201){let l=a.message||a.error||"Failed to publish prompt template";if(n)throw new Error(l);v(a,"WARNING: While publishing a prompt template PromptLayer had the following error")}return a}),An=(t,o,e,n=!0)=>T(null,null,function*(){var u;let s=new URL(`${o}/prompt-templates`);Object.entries(e||{}).forEach(([d,_])=>s.searchParams.append(d,_.toString()));let a=yield G(s,{headers:S({"Content-Type":"application/json","X-API-KEY":t},V())}),l=yield a.json();if(a.status!==200){let d=l.message||l.error||"Failed to fetch prompt templates";if(n)throw new Error(d);return v(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(u=l.items)!=null?u:[]}),Us=t=>T(null,null,function*(){let o=new URL(`${t.baseURL}/connection/websocket`);o.protocol=o.protocol==="https:"?"wss:":"ws:";let e=new hn.Centrifuge(o.toString(),{token:t.token}),n=e.newSubscription(t.channelName);return new Promise((s,a)=>{let l=m=>{_(),s(m)},u=Rn(t.baseURL,{resolve:l,reject:a},t.executionId,t.returnAllOutputs,t.headers);n.on("publication",m=>{u({name:m.data.message_name,data:m.data.data})});let d=setTimeout(()=>{a(new Error("Workflow execution did not complete properly (timeout)"))},t.timeout),_=()=>{clearTimeout(d),n.unsubscribe(),e.disconnect()};n.on("error",m=>{_(),a(`Centrifugo subscription error: ${m}`)}),e.on("error",m=>{_(),a(`Centrifugo client error: ${m}`)}),n.subscribe(),e.connect()})}),In=_=>T(null,[_],function*({workflow_name:t,input_variables:o,metadata:e={},workflow_label_name:n=null,workflow_version_number:s=null,return_all_outputs:a=!1,api_key:l,timeout:u=36e5,baseURL:d}){let m={input_variables:o,metadata:e,workflow_label_name:n,workflow_version_number:s,return_all_outputs:a},R=S({"Content-Type":"application/json","X-API-KEY":l},V());try{let k=yield G(`${d}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:R,body:JSON.stringify(m)});if(k.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield k.json().catch(()=>({}))).error||k.statusText}`};let g=yield k.json();g.warning&&console.warn(`WARNING: ${g.warning}`);let C=g.workflow_version_execution_id;if(!C)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let x=`workflow_updates:${C}`,w=yield(yield G(`${d}/ws-token-request-library?capability=${x}`,{method:"POST",headers:R})).json(),h={token:w.token_details.token,channelName:x,executionId:C,returnAllOutputs:a,headers:R,timeout:u,baseURL:d};return w.messaging_backend==="centrifugo"?Us(h):yield Ls(h)}catch(k){throw console.error(`Failed to run workflow: ${k instanceof Error?k.message:k}`),k}});function Ns(t,o,e,n,s=!0){return eo(this,null,function*(){let a=[];try{for(var d=oo(e),_,m,R;_=!(m=yield new ft(d.next())).done;_=!1){let k=m.value;yield n.return_pl_id?[k,null]:k,a.push(k)}}catch(m){R=[m]}finally{try{_&&(m=d.return)&&(yield new ft(m.call(d)))}finally{if(R)throw R[0]}}let l=dn(a,n.function_name),u=yield new ft(wn(t,o,Y(S({},n),{request_response:l,request_end_time:new Date().toISOString()}),s));if(u&&n.return_pl_id){let k=u[1];yield[a.at(-1),k]}})}var v=(t,o)=>{try{console.warn(`${o}: ${t.message}`)}catch(e){console.warn(`${o}: ${t}`)}},Ln=(t,o,e=!0)=>T(null,null,function*(){try{let n=yield G(`${t}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},V()),body:JSON.stringify(o)}),s=yield n.json();if(n.status!==200){let a=s.message||s.error||"Failed to track request";if(e)throw new Error(a);v(s,"WARNING: While logging your request, PromptLayer experienced the following error:")}return s}catch(n){if(e)throw n;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${n}`)}return{}}),qs=(t,o)=>T(null,null,function*(){return yield t.chat.completions.create(o)}),Ms=(t,o)=>T(null,null,function*(){return yield t.completions.create(o)}),Un={chat:qs,completion:Ms},Nn=(t,o)=>T(null,null,function*(){var a,l;let e=require("openai").default,n=new e({baseURL:o.baseURL,apiKey:o.apiKey});o==null||delete o.apiKey,o==null||delete o.baseURL;let s=(l=(a=t.metadata)==null?void 0:a.model)==null?void 0:l.api_type;if(s==="chat-completions"){let u=Un[t.prompt_template.type];return yield u(n,o)}else return s==="images"?yield n.images.generate(o):yield n.responses.create(o)}),qn=(t,o)=>T(null,null,function*(){var a,l;let{AzureOpenAI:e}=require("openai"),n=new e({endpoint:process.env.AZURE_OPENAI_ENDPOINT||o.baseURL,apiVersion:process.env.OPENAI_API_VERSION||o.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||o.apiKey});o==null||delete o.baseURL,o==null||delete o.apiVersion,o==null||delete o.apiKey;let s=(l=(a=t.metadata)==null?void 0:a.model)==null?void 0:l.api_type;if(s==="chat-completions"){let u=Un[t.prompt_template.type];return yield u(n,o)}else return s==="images"?yield n.images.generate(o):yield n.responses.create(o)}),Mn=(t,o)=>T(null,null,function*(){return t.messages.create(o)}),js=(t,o)=>T(null,null,function*(){return t.completions.create(o)}),jn={chat:Mn,completion:js},Wn=(t,o)=>T(null,null,function*(){let e=require("@anthropic-ai/sdk").default,n=new e({baseURL:o.baseURL,apiKey:o.apiKey}),s=jn[t.prompt_template.type];return s(n,o)}),$n=(t,o,e,n=!0)=>T(null,null,function*(){try{let s=yield G(`${o}/log-request`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},V()),body:JSON.stringify(e)}),a=yield s.json();if(s.status!==201){let l=a.message||a.error||"Failed to log request";if(n)throw new Error(l);return v(a,"WARNING: While logging your request PromptLayer had the following error"),null}return a}catch(s){if(n)throw s;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${s}`),null}}),Ws=(t,o)=>T(null,null,function*(){var l,u;let e=o==null?void 0:o.history,n=o==null?void 0:o.generationConfig,s=e.length>0?(l=e[e.length-1])==null?void 0:l.parts:"",a=t.chats.create({model:o==null?void 0:o.model,history:(u=e.slice(0,-1))!=null?u:[],config:n});return o!=null&&o.stream?yield a.sendMessageStream({message:s}):yield a.sendMessage({message:s})}),$s=(t,n)=>T(null,null,function*(){var s=n,{stream:o}=s,e=to(s,["stream"]);return o?yield t.generateContentStream(S({},e)):yield t.generateContent(S({},e))}),Ks={chat:Ws,completion:$s},ko=(t,o)=>T(null,null,function*(){let{GoogleGenAI:e}=yield import("@google/genai"),n=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,s=process.env.VERTEX_AI_PROJECT_ID||process.env.GOOGLE_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT,a=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,l={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:s,scopes:["https://www.googleapis.com/auth/cloud-platform"]},u=n?new e({apiKey:n}):new e({vertexai:!0,project:s,location:a,googleAuthOptions:l}),d=Ks[t.prompt_template.type];return yield d(u,o)}),fn=t=>t.replace(/_([a-z])/g,(o,e)=>e.toUpperCase()),so=(t,o=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>so(e,o)):Object.fromEntries(Object.entries(t).map(([e,n])=>o.has(e)?[fn(e),n]:[fn(e),so(n,o)])),Kn=(t,o,e={},n=!1)=>{var d,_,m,R,k,g,C,x,b;let s=(m=o==null?void 0:o.client)!=null?m:(_=(d=t.metadata)==null?void 0:d.model)==null?void 0:_.provider,a=(k=(R=t.metadata)==null?void 0:R.model)==null?void 0:k.api_type;if(!s)throw new Error("Provider type not found in prompt blueprint or custom provider");let l=Y(S({},t.llm_kwargs||{}),{stream:n});["google","vertexai"].includes(s)&&((C=(g=t.metadata)==null?void 0:g.model)!=null&&C.name.startsWith("gemini"))&&(l=so(l,new Set(["function_declarations","properties"])));let u={baseURL:(b=o==null?void 0:o.base_url)!=null?b:(x=t.provider_base_url)==null?void 0:x.url,apiKey:o==null?void 0:o.api_key};return Object.entries(u).forEach(([w,f])=>{f!==void 0&&(l[w]=f)}),n&&pn.includes(s)&&a==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:s,kwargs:l}},Gn=(t,o)=>{let e=mn[t];if(!e)throw new Error(`Unsupported provider type: ${t}`);let n=o.type,s=e[n];if(!s)throw new Error(`Unsupported template type '${o.type}' for provider '${t}'`);return s},Fn=(t,o)=>T(null,null,function*(){var n;let e=(n=t.metadata)==null?void 0:n.model;if(!e)throw new Error("Model metadata not found in prompt blueprint");if(e.name.startsWith("gemini"))return ko(t,o);if(e.name.startsWith("claude")){let{AnthropicVertex:s}=yield import("@anthropic-ai/vertex-sdk"),a=new s({baseURL:o.baseURL});if(t.prompt_template.type==="chat")return Mn(a,o);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${e.name}' for Vertex AI request`)}),Dn=(t,o)=>T(null,null,function*(){let{BedrockRuntimeClient:e,ConverseCommand:n,ConverseStreamCommand:s}=yield import("@aws-sdk/client-bedrock-runtime"),a=new e({credentials:{accessKeyId:(o==null?void 0:o.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(o==null?void 0:o.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(o==null?void 0:o.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(o==null?void 0:o.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(o!=null&&o.stream){delete o.stream;let l=new s(S({},o));return yield a.send(l)}else{o==null||delete o.stream;let l=new n(S({},o));return yield a.send(l)}}),Bn=(t,o)=>T(null,null,function*(){let{AnthropicBedrock:e}=yield import("@anthropic-ai/bedrock-sdk"),n=new e({awsAccessKey:o.aws_access_key,awsSecretKey:o.aws_secret_key,awsRegion:o.aws_region,awsSessionToken:o.aws_session_token,baseURL:o.base_url}),s=jn[t.prompt_template.type];return s(n,o)}),Vn=(t,o)=>T(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),n=new e({apiKey:process.env.MISTRAL_API_KEY});return o=so(o,new Set),o!=null&&o.stream?(delete o.stream,yield n.chat.stream(o)):(delete o.stream,yield n.chat.complete(o))}),wo=t=>{var o,e,n,s,a,l;if(typeof globalThis.process!="undefined")return(n=(e=(o=globalThis.process.env)==null?void 0:o[t])==null?void 0:e.trim())!=null?n:void 0;if(typeof globalThis.Deno!="undefined")return(l=(a=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:a.call(s,t))==null?void 0:l.trim()};var ro=class{constructor(o,e,n=!0){this.create=()=>En(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=o,this.baseURL=e,this.throwOnError=n}};var _t=require("@opentelemetry/api"),Ze=require("@opentelemetry/core");var So=class{constructor(o,e,n){this.apiKey=e,this.baseURL=n,this.enableTracing=o,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(o){return o?Object.fromEntries(Object.entries(o)):{}}spanKindToString(o){return{[_t.SpanKind.INTERNAL]:"SpanKind.INTERNAL",[_t.SpanKind.SERVER]:"SpanKind.SERVER",[_t.SpanKind.CLIENT]:"SpanKind.CLIENT",[_t.SpanKind.PRODUCER]:"SpanKind.PRODUCER",[_t.SpanKind.CONSUMER]:"SpanKind.CONSUMER"}[o]||"SpanKind.INTERNAL"}statusCodeToString(o){return{[_t.SpanStatusCode.ERROR]:"StatusCode.ERROR",[_t.SpanStatusCode.OK]:"StatusCode.OK",[_t.SpanStatusCode.UNSET]:"StatusCode.UNSET"}[o]||"StatusCode.UNSET"}toNanoseconds(o){return(BigInt(o[0])*BigInt(1e9)+BigInt(o[1])).toString()}export(o){if(!this.enableTracing)return Promise.resolve(Ze.ExportResultCode.SUCCESS);let e=o.map(n=>{var s;return{name:n.name,context:{trace_id:n.spanContext().traceId,span_id:n.spanContext().spanId,trace_state:((s=n.spanContext().traceState)==null?void 0:s.serialize())||""},kind:this.spanKindToString(n.kind),parent_id:n.parentSpanId||null,start_time:this.toNanoseconds(n.startTime),end_time:this.toNanoseconds(n.endTime),status:{status_code:this.statusCodeToString(n.status.code),description:n.status.message},attributes:this.attributesToObject(n.attributes),events:n.events.map(a=>({name:a.name,timestamp:this.toNanoseconds(a.time),attributes:this.attributesToObject(a.attributes)})),links:n.links.map(a=>({context:a.context,attributes:this.attributesToObject(a.attributes)})),resource:{attributes:Y(S({},n.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return G(this.url,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},V()),body:JSON.stringify({spans:e})}).then(n=>n.ok?Ze.ExportResultCode.SUCCESS:(console.error(`Error exporting spans
2
+ HTTP error! status: ${n.status}`),Ze.ExportResultCode.FAILED)).catch(n=>(console.error("Error exporting spans:",n),Ze.ExportResultCode.FAILED))}shutdown(){return Promise.resolve()}},zn=So;var Jn=dt(require("@opentelemetry/api")),Yn=require("@opentelemetry/sdk-trace-base"),Xn=require("@opentelemetry/sdk-trace-node"),Et=(t="promptlayer-tracer")=>Jn.trace.getTracer(t),Zn=(t,o,e)=>{let n=new Xn.NodeTracerProvider,s=new zn(t,o,e),a=new Yn.SimpleSpanProcessor(s);n.addSpanProcessor(a),n.register()};var Gs=Et(),xo=(t,o,e,n="",s="openai")=>{let a={construct:(l,u)=>{let d=Reflect.construct(l,u);return Object.defineProperties(d,{function_name:{value:n,writable:!0},provider:{value:s}}),new Proxy(d,a)},get:(l,u,d)=>{let _=l[u],m=`${Reflect.get(l,"function_name")}.${u.toString()}`;return typeof _=="object"?(Object.defineProperties(_,{function_name:{value:m,writable:!0},provider:{value:s}}),new Proxy(_,a)):typeof _=="function"?(...R)=>{var w,f,h,I,q,j;let k=new Date().toISOString(),g=Reflect.get(l,"provider"),C=(w=R[0])==null?void 0:w.return_pl_id,x=(f=R[0])==null?void 0:f.pl_tags,b=(h=R[0])==null?void 0:h.pl_warn_on_error;return(I=R[0])==null||delete I.return_pl_id,(q=R[0])==null||delete q.pl_tags,(j=R[0])==null||delete j.pl_warn_on_error,Gs.startActiveSpan(`${g}.${m}`,A=>T(null,null,function*(){try{A.setAttribute("function_input",JSON.stringify(R));let L=Reflect.apply(_,l,R),W=A.spanContext().spanId;return L instanceof Promise?new Promise((U,z)=>{L.then($=>T(null,null,function*(){let H=yield kn(t,o,{api_key:t,provider_type:g,function_name:m,request_start_time:k,request_end_time:new Date().toISOString(),request_response:$,kwargs:R[0],return_pl_id:C,tags:x,span_id:W},!b);A.setAttribute("function_output",JSON.stringify(H)),A.setAttribute("response_status","success"),A.end(),U(H)})).catch($=>{A.recordException($),A.setAttribute("response_status","error"),A.end(),z($)})}):(A.setAttribute("function_output",JSON.stringify(L)),A.setAttribute("response_status","success"),A.end(),L)}catch(L){throw A.recordException(L),A.setAttribute("response_status","error"),A.end(),L}}))}:Reflect.get(l,u,d)}};return new Proxy(e,a)};var He=t=>Object.fromEntries(Object.entries(t).filter(([,o])=>o!==void 0)),Qe=t=>T(null,null,function*(){var n;if(((n=t.headers.get("content-type"))!=null?n:"").includes("application/json"))return t.json();let e=yield t.text();if(!e)return{};try{return JSON.parse(e)}catch(s){return{message:e}}}),Hn=t=>t instanceof Blob?t:t instanceof Uint8Array?new Blob([t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)],{type:"application/zip"}):new Blob([t],{type:"application/zip"});var io=t=>`${t}/api/public/v2/skill-collections`,ao=(t,o)=>`${io(t)}/${encodeURIComponent(o)}`,Qn=(t,o)=>`${ao(t,o)}/versions`;var Co=t=>"zipFile"in t;var vn=["claude_code","openai","openclaw"],ts=(t,o)=>{if(!t){if(o==="publishing")throw new Error("provider is required when publishing a skill collection.");return}if(!vn.includes(t))throw new Error(`provider must be one of: ${vn.join(", ")}.`)},es=(t,o,e,n,s=!0)=>T(null,null,function*(){let a=new URL(ao(o,e));Object.entries(n||{}).forEach(([u,d])=>{d!==void 0&&a.searchParams.append(u,String(d))});let l=yield G(a,{headers:S({"X-API-KEY":t},V())});if(l.status!==200){let u=yield Qe(l),d=u.message||u.error||"Failed to pull skill collection";if(s)throw new Error(d);return v(u,"WARNING: While pulling a skill collection PromptLayer had the following error"),null}return(n==null?void 0:n.format)==="zip"?l.arrayBuffer():yield l.json()}),os=(t,o,e,n=!0)=>T(null,null,function*(){ts(e.provider,"publishing");let s=Co(e)?(()=>{var _;let u=new FormData,d=He({name:e.name,folder_id:e.folderId,provider:e.provider,commit_message:e.commitMessage});return u.append("files",Hn(e.zipFile),(_=e.fileName)!=null?_:"skill-collection.zip"),u.append("json",JSON.stringify(d)),u})():JSON.stringify(He({name:e.name,folder_id:e.folderId,provider:e.provider,files:e.files,commit_message:e.commitMessage})),a=Co(e)?yield G(io(o),{method:"POST",headers:S({"X-API-KEY":t},V()),body:s}):yield G(io(o),{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},V()),body:s}),l=yield Qe(a);if(a.status!==201){let u=l.message||l.error||"Failed to publish skill collection";if(n)throw new Error(u);return v(l,"WARNING: While publishing a skill collection PromptLayer had the following error"),null}return l}),ns=(t,o,e,n,s=!0)=>T(null,null,function*(){let a=yield G(ao(o,e),{method:"PATCH",headers:S({"Content-Type":"application/json","X-API-KEY":t},V()),body:JSON.stringify(He(n))}),l=yield Qe(a);if(a.status!==200){let u=l.message||l.error||"Failed to update skill collection";if(s)throw new Error(u);return v(l,"WARNING: While updating a skill collection PromptLayer had the following error"),null}return l}),ss=(t,o,e,n,s=!0)=>T(null,null,function*(){ts(n.provider,"updating");let a=He({file_updates:n.fileUpdates,moves:n.moves,deletes:n.deletes,commit_message:n.commitMessage,release_label:n.releaseLabel,provider:n.provider}),l=yield G(Qn(o,e),{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},V()),body:JSON.stringify(a)}),u=yield Qe(l);if(l.status!==201){let d=u.message||u.error||"Failed to save skill collection version";if(s)throw new Error(d);return v(u,"WARNING: While saving a skill collection version PromptLayer had the following error"),null}return u});var Po=t=>Array.isArray(t)&&t.length>0,Fs=t=>Po(t.fileUpdates)||Po(t.moves)||Po(t.deletes)||t.commitMessage!==void 0||t.releaseLabel!==void 0||t.provider!==void 0,Ds=(t,o,e)=>{var n;return Y(S({},t!=null?t:{}),{success:(n=t==null?void 0:t.success)!=null?n:!0,skill_collection:o,version:e})},lo=class{constructor(o,e,n=!0){this.pull=(o,e)=>es(this.apiKey,this.baseURL,o,e,this.throwOnError);this.publish=o=>os(this.apiKey,this.baseURL,o,this.throwOnError);this.update=(o,e)=>T(this,null,function*(){var _,m,R,k;let n=e.name!==void 0,s=Fs(e);if(!n&&!s)throw new Error("At least one of name, fileUpdates, moves, deletes, commitMessage, releaseLabel, or provider must be provided.");let a=o,l=null,u,d=null;if(n){let g=yield ns(this.apiKey,this.baseURL,o,{name:e.name},this.throwOnError);if(!g)return null;l=g,u=g.skill_collection,d=(_=g.version)!=null?_:null,a=String(g.skill_collection.id)}if(s){let g=yield ss(this.apiKey,this.baseURL,a,{fileUpdates:e.fileUpdates,moves:e.moves,deletes:e.deletes,commitMessage:e.commitMessage,releaseLabel:e.releaseLabel,provider:e.provider},this.throwOnError);if(!g)return null;l=g,u=(m=g.skill_collection)!=null?m:u,d=(R=g.version)!=null?R:d}if(!u){let g=yield this.pull(a);if(!g)return null;if(g instanceof ArrayBuffer)throw new Error("Expected JSON skill collection response but received binary data.");l=g,u=g.skill_collection,d=(k=g.version)!=null?k:d}return Ds(l,u,d)});this.apiKey=o,this.baseURL=e,this.throwOnError=n}};var co=dt(require("@opentelemetry/api"));var is=(t,o,e)=>function(...n){let s=Et(),a=l=>{try{e&&Object.entries(e).forEach(([d,_])=>{l.setAttribute(d,_)}),l.setAttribute("function_input",JSON.stringify(n));let u=o(...n);return u instanceof Promise?u.then(d=>(l.setAttribute("function_output",JSON.stringify(d)),l.setStatus({code:co.SpanStatusCode.OK}),d)).catch(d=>{throw rs(l,d,n),d}).finally(()=>l.end()):(l.setAttribute("function_output",JSON.stringify(u)),l.setStatus({code:co.SpanStatusCode.OK}),l.end(),u)}catch(u){throw rs(l,u,n),u}};return s.startActiveSpan(t,a)},rs=(t,o,e)=>{t.setAttribute("function_input",JSON.stringify(e)),t.setStatus({code:co.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),t.end()};var po=class{constructor(o,e,n=!0){this.get=(o,e)=>Tn(this.apiKey,this.baseURL,o,e,this.throwOnError);this.publish=o=>On(this.apiKey,this.baseURL,o,this.throwOnError);this.all=o=>An(this.apiKey,this.baseURL,o,this.throwOnError);this.apiKey=o,this.baseURL=e,this.throwOnError=n}};var Bs=(t,o,e,n=!0)=>{if(!(e.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[s,a]of Object.entries(e.metadata))if(typeof s!="string"||typeof a!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return Sn(t,o,e,n)},Vs=(t,o,e,n=!0)=>{if(typeof e.score!="number")throw new Error("Score must be a number");if(e.score<0||e.score>100)throw new Error("Score must be a number between 0 and 100.");return xn(t,o,e,n)},zs=(t,o,e,n=!0)=>{if(!(e.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return Cn(t,o,e,n)},Js=(t,o,e,n=!0)=>Pn(t,o,e,n),uo=class{constructor(o,e,n=!0){this.group=o=>Js(this.apiKey,this.baseURL,o,this.throwOnError);this.metadata=o=>Bs(this.apiKey,this.baseURL,o,this.throwOnError);this.prompt=o=>zs(this.apiKey,this.baseURL,o,this.throwOnError);this.score=o=>Vs(this.apiKey,this.baseURL,o,this.throwOnError);this.apiKey=o,this.baseURL=e,this.throwOnError=n}};function Ys(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function Xs(t){return t&&typeof t=="object"&&t.constructor?t.constructor.name:""}function as(t){let o=Ys(t),e=Xs(t),n=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();return o===429||/ratelimit/i.test(e)?"PROVIDER_RATE_LIMIT":/timeout/i.test(e)?"PROVIDER_TIMEOUT":o===401||/authentication/i.test(e)?"PROVIDER_AUTH_ERROR":n.includes("quota")?"PROVIDER_QUOTA_LIMIT":n.includes("timeout")||n.includes("timed out")?"PROVIDER_TIMEOUT":o!==void 0?"PROVIDER_ERROR":"UNKNOWN_ERROR"}var ls=dt(require("@opentelemetry/api"));var Zs={openai:Nn,anthropic:Wn,"openai.azure":qn,google:ko,vertexai:Fn,"amazon.bedrock":Dn,"anthropic.bedrock":Bn,mistral:Vn},Hs=t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let o=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(t).every(n=>typeof n!="object"||n===null?!1:o.every(s=>s in n))},Eo=class{constructor({apiKey:o=wo("PROMPTLAYER_API_KEY"),baseURL:e=wo("PROMPTLAYER_BASE_URL"),enableTracing:n=!1,throwOnError:s=!0}={}){if(o===void 0)throw new Error("PromptLayer API key not provided. Please set the PROMPTLAYER_API_KEY environment variable or pass the api_key parameter.");this.apiKey=o,this.baseURL=e||"https://api.promptlayer.com",this.enableTracing=n,this.throwOnError=s,this.templates=new po(o,this.baseURL,this.throwOnError),this.skills=new lo(o,this.baseURL,this.throwOnError),this.group=new ro(o,this.baseURL,this.throwOnError),this.track=new uo(o,this.baseURL,this.throwOnError),this.wrapWithSpan=is,n&&Zn(n,o,this.baseURL)}get Anthropic(){try{let o=require("@anthropic-ai/sdk").default;return xo(this.apiKey,this.baseURL,o,"anthropic","anthropic")}catch(o){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let o=require("openai").default;return xo(this.apiKey,this.baseURL,o,"openai","openai")}catch(o){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(k){return T(this,arguments,function*({promptName:o,promptVersion:e,promptReleaseLabel:n,inputVariables:s,tags:a,metadata:l,groupId:u,modelParameterOverrides:d,stream:_=!1,provider:m,model:R}){return Et().startActiveSpan("PromptLayer Run",C=>T(this,null,function*(){try{let x={promptName:o,promptVersion:e,promptReleaseLabel:n,inputVariables:s,tags:a,metadata:l,groupId:u,modelParameterOverrides:d,stream:_};C.setAttribute("function_input",JSON.stringify(x));let b=s,w={label:n,version:e,metadata_filters:l,provider:m,model:R,model_parameter_overrides:d};s&&(w.input_variables=s);let f=yield this.templates.get(o,w);if(!f)throw new Error(`Cannot proceed: prompt template '${o}' could not be fetched. Check the warnings above for the actual error.`);let h=f.prompt_template;if(!f.llm_kwargs){let D=`Prompt '${o}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashboard.`;if(this.throwOnError)throw new Error(D);console.warn(`WARNING: ${D}`)}let I=f.metadata;if(!I)throw new Error(`Prompt '${o}' does not have any metadata associated with it.`);let q=I.model;if(!q)throw new Error(`Prompt '${o}' does not have a model parameters associated with it.`);let j=f.custom_provider,A=new Date().toISOString(),{provider_type:L,kwargs:W}=Kn(f,j,d,_),U=L;if(L==="openai"||L==="openai.azure"){let D=q.api_type;U=`${L}:${D}`}q.name.startsWith("gemini")?U="google":q.name.startsWith("claude")&&(U="anthropic");let z=Gn(U,h),{function_name:$,stream_function:H}=z,F=Zs[L];if(!F)throw new Error(`No request function found for provider: ${L}`);let Q=D=>{let nt=new Date().toISOString();return Ln(this.baseURL,S({function_name:$,provider_type:L,args:[],kwargs:W,tags:a,request_start_time:A,request_end_time:nt,api_key:this.apiKey,metadata:l,prompt_id:f.id,prompt_version:f.version,prompt_input_variables:b,group_id:u,return_prompt_blueprint:!0,span_id:C.spanContext().spanId},D),this.throwOnError)},Z;try{Z=yield F(f,W)}catch(D){let nt=as(D),lt=D instanceof Error?D.message:String(D);throw yield Q({request_response:{},status:"ERROR",error_type:nt,error_message:lt}),D}if(_)return _n(Z,Q,H,l||f.metadata);let it=yield Q({request_response:Z}),at={request_id:it.request_id,raw_response:Z,prompt_blueprint:it.prompt_blueprint};return C.setAttribute("function_output",JSON.stringify(at)),at}catch(x){throw C.setStatus({code:ls.SpanStatusCode.ERROR,message:x instanceof Error?x.message:"Unknown error"}),x}finally{C.end()}}))})}runWorkflow(u){return T(this,arguments,function*({workflowName:o,inputVariables:e={},metadata:n={},workflowLabelName:s=null,workflowVersion:a=null,returnAllOutputs:l=!1}){try{let d=yield In({workflow_name:o,input_variables:e,metadata:n,workflow_label_name:s,workflow_version_number:a,return_all_outputs:l,api_key:this.apiKey,baseURL:this.baseURL});if(!l&&Hs(d)){let m=Object.values(d).filter(k=>k.is_output_node===!0);if(m.length===0)throw new Error(JSON.stringify(d,null,2));if(!m.some(k=>k.status==="SUCCESS"))throw new Error(JSON.stringify(d,null,2))}return d}catch(d){throw d instanceof Error?(console.error("Error running workflow:",d.message),new Error(`Error running workflow: ${d.message}`)):(console.error("Unknown error running workflow:",d),new Error("Unknown error running workflow"))}})}logRequest(o){return T(this,null,function*(){return $n(this.apiKey,this.baseURL,o,this.throwOnError)})}};0&&(module.exports={PromptLayer});
3
3
  //# sourceMappingURL=index.js.map