promptlayer 1.2.2 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claude-agents.js +1 -1
- package/dist/claude-agents.js.map +1 -1
- package/dist/esm/{chunk-7Y65WGSZ.js → chunk-S3PZHCUA.js} +2 -2
- package/dist/esm/chunk-S3PZHCUA.js.map +1 -0
- package/dist/esm/claude-agents.js +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/openai-agents.js +1 -1
- package/dist/esm/openai-agents.js.map +1 -1
- package/dist/index.d.mts +152 -3
- package/dist/index.d.ts +152 -3
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/openai-agents.js +2 -2
- package/dist/openai-agents.js.map +1 -1
- package/package.json +3 -1
- package/dist/esm/chunk-7Y65WGSZ.js.map +0 -1
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 ks=Object.create;var Ze=Object.defineProperty,ws=Object.defineProperties,xs=Object.getOwnPropertyDescriptor,Ss=Object.getOwnPropertyDescriptors,Ps=Object.getOwnPropertyNames,on=Object.getOwnPropertySymbols,Cs=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty,so=Object.prototype.propertyIsEnumerable;var bn=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t);var oo=(t,n,e)=>n in t?Ze(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e,S=(t,n)=>{for(var e in n||(n={}))kn.call(n,e)&&oo(t,e,n[e]);if(on)for(var e of on(n))so.call(n,e)&&oo(t,e,n[e]);return t},Y=(t,n)=>ws(t,Ss(n));var sn=(t,n)=>{var e={};for(var o in t)kn.call(t,o)&&n.indexOf(o)<0&&(e[o]=t[o]);if(t!=null&&on)for(var o of on(t))n.indexOf(o)<0&&so.call(t,o)&&(e[o]=t[o]);return e};var Ts=(t,n)=>{for(var e in n)Ze(t,e,{get:n[e],enumerable:!0})},ro=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Ps(n))!kn.call(t,s)&&s!==e&&Ze(t,s,{get:()=>n[s],enumerable:!(o=xs(n,s))||o.enumerable});return t};var lt=(t,n,e)=>(e=t!=null?ks(Cs(t)):{},ro(n||!t||!t.__esModule?Ze(e,"default",{value:t,enumerable:!0}):e,t)),Es=t=>ro(Ze({},"__esModule",{value:!0}),t);var T=(t,n,e)=>new Promise((o,s)=>{var i=u=>{try{p(e.next(u))}catch(_){s(_)}},l=u=>{try{p(e.throw(u))}catch(_){s(_)}},p=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,l);p((e=e.apply(t,n)).next())}),ft=function(t,n){this[0]=t,this[1]=n},rn=(t,n,e)=>{var o=(l,p,u,_)=>{try{var m=e[l](p),y=(p=m.value)instanceof ft,k=m.done;Promise.resolve(y?p[0]:p).then(h=>y?o(l==="return"?l:"next",p[1]?{done:h.done,value:h.value}:h,u,_):u({value:h,done:k})).catch(h=>o("throw",h,u,_))}catch(h){_(h)}},s=l=>i[l]=p=>new Promise((u,_)=>o(l,p,u,_)),i={};return e=e.apply(t,n),i[bn("asyncIterator")]=()=>i,s("next"),s("throw"),s("return"),i};var an=(t,n,e)=>(n=t[bn("asyncIterator")])?n.call(t):(t=t[bn("iterator")](),n={},e=(o,s)=>(s=t[o])&&(n[o]=i=>new Promise((l,p,u)=>(i=s.call(t,i),u=i.done,Promise.resolve(i.value).then(_=>l({value:_,done:u}),p)))),e("next"),e("return"),n);var wr={};Ts(wr,{PromptLayer:()=>Mn});module.exports=Es(wr);var Po=lt(require("ably")),Co=require("centrifuge"),To=lt(require("p-retry"));var io={png:"image/png",webp:"image/webp",jpeg:"image/jpeg",jpg:"image/jpeg",gif:"image/gif",url:"image/png"},rt=(t,n,e,o)=>S({id:t,type:"function",function:{name:n,arguments:typeof e=="string"?e:JSON.stringify(e)}},o?{tool_id:o}:{}),b=o=>{var s=o,{type:t,item_id:n}=s,e=sn(s,["type","item_id"]);let i=S({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}),Ct=(t,n)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:n});function ao(t){var n,e,o,s;return S(S({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:(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 co=(t,n,e)=>{var l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt;let o=[],s=[];if(Array.isArray(t.content)){for(let U of t.content){if(!U||typeof U!="object")continue;let X=U.type;if(X==="text"){let tt=(l=U.text)!=null?l:"",ut=(u=(p=U.citations)!=null?p:U.annotations)!=null?u:[],et=[];for(let nt of ut)nt&&typeof nt=="object"&&et.push(ao(nt));o.push(b(S({type:"text",text:tt},et.length>0?{annotations:et}:{})))}else if(X==="thinking")o.push(b({type:"thinking",thinking:(_=U.thinking)!=null?_:"",signature:(m=U.signature)!=null?m:""}));else if(X==="tool_use")s.push(rt((y=U.id)!=null?y:"",(k=U.name)!=null?k:"",(h=U.input)!=null?h:{}));else if(X==="server_tool_use")o.push(b({type:"server_tool_use",id:(P=U.id)!=null?P:"",name:(x=U.name)!=null?x:"",input:(g=U.input)!=null?g:{}}));else if(X==="web_search_tool_result"){let tt=(w=U.content)!=null?w:[],ut=[];for(let et of tt)if(et&&typeof et=="object"&&et.type==="web_search_result"){let nt=et;ut.push({type:"web_search_result",url:nt.url,title:nt.title,encrypted_content:nt.encrypted_content,page_age:nt.page_age})}o.push(b({type:"web_search_tool_result",tool_use_id:(f=U.tool_use_id)!=null?f:"",content:ut}))}else X==="bash_code_execution_tool_result"&&o.push(b({type:"bash_code_execution_tool_result",tool_use_id:(R=U.tool_use_id)!=null?R:"",content:(I=U.content)!=null?I:{}}))}let st=Pt(o,s);return Ct(st,n)}if(t.type==="content_block_start")if(((q=t.content_block)==null?void 0:q.type)==="thinking")o.push(b({type:"thinking",thinking:"",signature:""}));else if(((j=t.content_block)==null?void 0:j.type)==="text")o.push(b({type:"text",text:""}));else if(((O=t.content_block)==null?void 0:O.type)==="tool_use")s.push(rt((L=t.content_block.id)!=null?L:"",(W=t.content_block.name)!=null?W:"",{}));else if(((N=t.content_block)==null?void 0:N.type)==="server_tool_use")o.push(b({type:"server_tool_use",id:(V=t.content_block.id)!=null?V:"",name:($=t.content_block.name)!=null?$:"",input:(Z=t.content_block.input)!=null?Z:{}}));else if(((G=t.content_block)==null?void 0:G.type)==="web_search_tool_result"){let st=(Q=t.content_block.content)!=null?Q:[],U=[];for(let X of st)if(X&&typeof X=="object"&&X.type==="web_search_result"){let tt=X;U.push({type:"web_search_result",url:tt.url,title:tt.title,encrypted_content:tt.encrypted_content,page_age:tt.page_age})}o.push(b({type:"web_search_tool_result",tool_use_id:(H=t.content_block.tool_use_id)!=null?H:"",content:U}))}else((it=t.content_block)==null?void 0:it.type)==="bash_code_execution_tool_result"&&o.push(b({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(((ot=t.delta)==null?void 0:ot.type)==="thinking_delta")o.push(b({type:"thinking",thinking:(ct=t.delta.thinking)!=null?ct:"",signature:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="text_delta")o.push(b({type:"text",text:(ht=t.delta.text)!=null?ht:""}));else if(((yt=t.delta)==null?void 0:yt.type)==="signature_delta")o.push(b({type:"thinking",thinking:"",signature:(Rt=t.delta.signature)!=null?Rt:""}));else if(((bt=t.delta)==null?void 0:bt.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?o.push(b({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(((xt=t.delta)==null?void 0:xt.type)==="citations_delta"&&t.delta.citation){let st=t.delta.citation,U=[ao(st)];o.push(b({type:"text",text:"",annotations:U}))}}let i=Pt(o,s);return Ct(i,n)},As=t=>typeof t=="string"&&t.startsWith("image/");function lo(t){var e,o,s,i;let n=t.web;return n&&typeof n=="object"?{uri:(e=n.uri)!=null?e:"",title:(o=n.title)!=null?o:""}:{uri:(s=t.uri)!=null?s:"",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 s of e)s&&typeof s=="object"&&typeof s.text=="string"&&o.push(s.text);return o.length>0?o.join(""):void 0}function Is(t){var o,s,i,l;if(!t||typeof t!="object")return[];let n=(o=t.citations)!=null?o:[],e=[];for(let p of n){if(!p||typeof p!="object")continue;let u=(s=p.uri)!=null?s:"";if(!u)continue;let _=(i=p.startIndex)!=null?i:0,m=(l=p.endIndex)!=null?l:0;e.push({type:"url_citation",url:u,title:u,start_index:_,end_index:m})}return e}function Ls(t,n){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,o=t.citationMetadata,s=Ns(e,n),i=Is(o);return[...s,...i]}function Ns(t,n){var p,u,_,m,y,k,h,P,x;let e=t&&typeof t=="object"?(p=t.groundingChunks)!=null?p:[]:[],o=t&&typeof t=="object"?(u=t.groundingSupports)!=null?u:[]:[];function s(g,w,f){let R=g.text;if(R!=null&&R!=="")return R;if(n!=null&&f>w)return n.slice(w,f)||void 0}if(o.length>0&&e.length>0){let g=[],w=new Set;for(let f of o){if(!f||typeof f!="object")continue;let R=(_=f.segment)!=null?_:{},I=(m=f.groundingChunkIndices)!=null?m:[],q=(y=R.startIndex)!=null?y:0,j=(k=R.endIndex)!=null?k:0,O=s(R,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 N=W.maps;if(N&&typeof N=="object"){let G=(h=N.uri)!=null?h:"",Q=(P=N.title)!=null?P:"",H=N.placeId;(G||Q)&&g.push(S(Y(S({type:"map_citation",url:G,title:Q||G},H!=null?{place_id:H}:{}),{start_index:q,end_index:j}),O!=null?{cited_text:O}:{}));continue}let V=W.retrievedContext;if(V&&typeof V=="object"){let G=(x=V.title)!=null?x:"";G&&!w.has(G)&&(w.add(G),g.push({type:"file_citation",file_id:G,filename:G,index:L}));continue}let{uri:$,title:Z}=lo(W);$&&g.push(S({type:"url_citation",url:$,title:Z||$,start_index:q,end_index:j},O!=null?{cited_text:O}:{}))}}return g}if(!t||typeof t!="object")return[];let i=[],l=new Set;return e.forEach((g,w)=>{var O,L,W;if(!g||typeof g!="object")return;let f=g,R=f.maps;if(R&&typeof R=="object"){let N=(O=R.uri)!=null?O:"",V=(L=R.title)!=null?L:"",$=R.placeId;(N||V)&&i.push(Y(S({type:"map_citation",url:N,title:V||N},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let I=f.retrievedContext;if(I&&typeof I=="object"){let N=(W=I.title)!=null?W:"";N&&!l.has(N)&&(l.add(N),i.push({type:"file_citation",file_id:N,filename:N,index:w}));return}let{uri:q,title:j}=lo(f);q&&i.push({type:"url_citation",url:q,title:j||q,start_index:0,end_index:0})}),i}var uo=(t,n)=>{var u,_,m,y,k,h,P,x,g;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(b({type:"thinking",thinking:f.text,signature:(_=f.thoughtSignature)!=null?_:""})):e.push(b(S({type:"text",text:f.text},f.thoughtSignature?{thought_signature:f.thoughtSignature}:{})));else if(f.functionCall)o.push(rt(f.functionCall.id||"",f.functionCall.name||"",f.functionCall.args||{}));else if(f.executableCode){let R=f.executableCode;e.push(b(S({type:"code",code:(m=R.code)!=null?m:""},R.language!=null?{language:R.language}:{})))}else if(f.codeExecutionResult){let R=f.codeExecutionResult;e.push(b({type:"code_execution_result",output:(y=R.output)!=null?y:"",outcome:(k=R.outcome)!=null?k:"OUTCOME_OK"}))}else{let R=f.inlineData;if(R&&f.thought!==!0){let I=(h=R.mimeType)!=null?h:"image/png",q=(P=R.data)!=null?P:"";if(As(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(b(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],i=Os(s),l=Ls(s,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 R=(g=f.annotations)!=null?g:[];e[w]=Y(S({},f),{annotations:[...R,...l]})}}let p=Pt(e,o);return Ct(p,n)},wn=(t,n)=>{let e=[],o=[];for(let i of t.choices)if(i.delta){i.delta.content&&e.push(b({type:"text",text:i.delta.content}));let l=i.delta.tool_calls||i.delta.toolCalls;if(l&&Array.isArray(l))for(let p of l)p.function&&o.push(rt(p.id||"",p.function.name||"",p.function.arguments||""))}let s=Pt(e,o);return Ct(s,n)},po=(t,n)=>{var l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt,st,U,X,tt,ut,et,nt,Ot,It,Lt,Nt,Ut,qt,Mt,jt,Wt,$t,Kt,Ft,Gt,Dt,Bt,zt,Vt,Jt,Yt,Xt,Ht,Zt,Qt,vt,te,ee,ne,oe,se,re,ie,ae,le,ce,ue,pe,de,_e,me,fe,ge,he,ye,Re,be,ke,we,xe,Se,Pe,Ce,Te,Ee,Ae,Oe,Ie,Le,Ne,Ue,qe,Me,je,We,$e,Ke,Fe,Ge,De,Be,ze,Ve,Je,Ye,Xe,He,C,M,a,c,E,pt,jn,Wn,$n,Kn,Fn,Gn,Dn,Bn,zn,Vn,Jn,Yn,Xn,Hn,Zn,Qn,vn,to,eo,no;let e=[],o=[],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:"",A=(p=t==null?void 0:t.item_id)!=null?p:"";r&&e.push(b({type:"thinking",item_id:A,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_text.done"){let r=(u=t==null?void 0:t.text)!=null?u:"",A=(_=t==null?void 0:t.item_id)!=null?_:"";r&&e.push(b({type:"thinking",item_id:A,thinking:r,signature:""}))}else if(s==="response.reasoning_summary_part.added"){let r=(m=t==null?void 0:t.part)!=null?m:{},A=(y=t==null?void 0:t.item_id)!=null?y:"";if((r==null?void 0:r.type)==="summary_text"){let d=(k=r==null?void 0:r.text)!=null?k:"";e.push(b({type:"thinking",item_id:A,thinking:d,signature:""}))}}else if(s==="response.reasoning_summary_part.done"){let r=(h=t==null?void 0:t.part)!=null?h:{},A=(P=t==null?void 0:t.item_id)!=null?P:"";if((r==null?void 0:r.type)==="summary_text"){let d=(x=r==null?void 0:r.text)!=null?x:"";d&&e.push(b({type:"thinking",item_id:A,thinking:d,signature:""}))}}else if(s==="response.function_call_arguments.delta"){let r=(g=t==null?void 0:t.item_id)!=null?g:"",A=(w=t==null?void 0:t.delta)!=null?w:"";A&&o.push(rt("","",A,r))}else if(s==="response.function_call_arguments.done"){let r=(f=t==null?void 0:t.item_id)!=null?f:"",A=(R=t==null?void 0:t.arguments)!=null?R:"";A&&o.push(rt("","",A,r))}else if(s==="response.output_item.added"){let r=(I=t==null?void 0:t.item)!=null?I:{},A=r==null?void 0:r.type,d=(q=r==null?void 0:r.id)!=null?q:"";A==="reasoning"?e.push(b({type:"thinking",thinking:"",signature:"",item_id:d})):A==="function_call"?o.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"","",d)):A==="message"?e.push(b({type:"text",item_id:d,text:""})):A==="code_interpreter_call"?e.push(b({type:"code",item_id:d,code:(j=r==null?void 0:r.code)!=null?j:"",container_id:(O=r==null?void 0:r.container_id)!=null?O:""})):A==="image_generation_call"?e.push(b({type:"output_media",item_id:d,url:"",mime_type:"image/png",media_type:"image"})):A==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:d,server_label:(L=r==null?void 0:r.server_label)!=null?L:"",tools:(W=r==null?void 0:r.tools)!=null?W:[]})):A==="mcp_call"?e.push(b({type:"mcp_call",item_id:d,name:(N=r==null?void 0:r.name)!=null?N:"",server_label:(V=r==null?void 0:r.server_label)!=null?V:"",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})):A==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:d,name:(Z=r==null?void 0:r.name)!=null?Z:"",arguments:(G=r==null?void 0:r.arguments)!=null?G:"",server_label:(Q=r==null?void 0:r.server_label)!=null?Q:""})):A==="shell_call"?e.push(b({type:"shell_call",item_id:d,call_id:(H=r==null?void 0:r.call_id)!=null?H:"",action:(it=r==null?void 0:r.action)!=null?it:{},status:(at=r==null?void 0:r.status)!=null?at:"in_progress"})):A==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:d,call_id:(D=r==null?void 0:r.call_id)!=null?D:"",output:(ot=r==null?void 0:r.output)!=null?ot:[],status:(ct=r==null?void 0:r.status)!=null?ct:"in_progress"})):A==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:d,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"})):A==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:d,call_id:(Rt=r==null?void 0:r.call_id)!=null?Rt:"",output:(bt=r==null?void 0:r.output)!=null?bt:"",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:{},A=(xt=r==null?void 0:r.type)!=null?xt:"output_text",d=(st=t==null?void 0:t.item_id)!=null?st:"";A==="output_text"&&e.push(b({type:"text",item_id:d,text:(U=r==null?void 0:r.text)!=null?U:"",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:{},A=(tt=r==null?void 0:r.type)!=null?tt:"output_text",d=(ut=t==null?void 0:t.item_id)!=null?ut:"";A==="output_text"&&e.push(b({type:"text",item_id:d,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)||{},A=r==null?void 0:r.type,d=null;A==="url_citation"?d={type:"url_citation",title:(nt=r==null?void 0:r.title)!=null?nt:"",url:(Ot=r==null?void 0:r.url)!=null?Ot:"",start_index:(It=r==null?void 0:r.start_index)!=null?It:0,end_index:(Lt=r==null?void 0:r.end_index)!=null?Lt:0}:A==="file_citation"?d={type:"file_citation",index:(Nt=r==null?void 0:r.index)!=null?Nt:0,file_id:(Ut=r==null?void 0:r.file_id)!=null?Ut:"",filename:(qt=r==null?void 0:r.filename)!=null?qt:""}:d=r,e.push(b({type:"text",item_id:(Mt=t==null?void 0:t.item_id)!=null?Mt:"",text:"",annotations:[d]}))}else if(s==="response.code_interpreter_call.in_progress")e.push(b({type:"code",item_id:(jt=t==null?void 0:t.item_id)!=null?jt:"",code:(Wt=t==null?void 0:t.code)!=null?Wt:"",container_id:($t=t==null?void 0:t.container_id)!=null?$t:""}));else if(s==="response.code_interpreter_call_code.delta")e.push(b({type:"code",item_id:(Kt=t==null?void 0:t.item_id)!=null?Kt:"",code:(Ft=t==null?void 0:t.delta)!=null?Ft:"",container_id:(Gt=t==null?void 0:t.container_id)!=null?Gt:""}));else if(s==="response.output_text.delta"){let r=(Dt=t==null?void 0:t.delta)!=null?Dt:"";r&&e.push(b({type:"text",item_id:(Bt=t==null?void 0:t.item_id)!=null?Bt:"",text:r}))}else if(s==="response.output_text.done")e.push(b({type:"text",item_id:(zt=t==null?void 0:t.item_id)!=null?zt:"",text:(Vt=t==null?void 0:t.text)!=null?Vt:""}));else if(s==="response.output_item.done"){let r=(Jt=t==null?void 0:t.item)!=null?Jt:{},A=r==null?void 0:r.type,d=(Yt=r==null?void 0:r.id)!=null?Yt:"";if(A==="reasoning"){let K=((Xt=r==null?void 0:r.summary)!=null?Xt:[]).map(dt=>{var J;return(J=dt==null?void 0:dt.text)!=null?J:""}).join("");e.push(b({type:"thinking",item_id:d,thinking:K,signature:""}))}else if(A==="function_call")o.push(rt((r==null?void 0:r.call_id)||"",(r==null?void 0:r.name)||"",(r==null?void 0:r.arguments)||"",d));else if(A==="message"){let B=(Ht=r==null?void 0:r.content)!=null?Ht:[];for(let K of B)(K==null?void 0:K.type)==="output_text"&&e.push(b({type:"text",item_id:d,text:(Zt=K==null?void 0:K.text)!=null?Zt:""}))}else if(A==="code_interpreter_call")e.push(b({type:"code",item_id:d,code:(Qt=r==null?void 0:r.code)!=null?Qt:"",container_id:(vt=r==null?void 0:r.container_id)!=null?vt:""}));else if(A==="image_generation_call"){let B=(te=r==null?void 0:r.result)!=null?te:"",dt=((ee=r==null?void 0:r.output_format)!=null?ee:"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(b(S({type:"output_media",item_id:d,url:B,mime_type:dt,media_type:"image"},Object.keys(J).length?{provider_metadata:J}:{})))}else A==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:d,server_label:(ne=r==null?void 0:r.server_label)!=null?ne:"",tools:(oe=r==null?void 0:r.tools)!=null?oe:[],error:r==null?void 0:r.error})):A==="mcp_call"?e.push(b({type:"mcp_call",item_id:d,name:(se=r==null?void 0:r.name)!=null?se:"",server_label:(re=r==null?void 0:r.server_label)!=null?re:"",arguments:(ie=r==null?void 0:r.arguments)!=null?ie:"",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})):A==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:d,name:(ae=r==null?void 0:r.name)!=null?ae:"",arguments:(le=r==null?void 0:r.arguments)!=null?le:"",server_label:(ce=r==null?void 0:r.server_label)!=null?ce:""})):A==="shell_call"?e.push(b({type:"shell_call",item_id:d,call_id:(ue=r==null?void 0:r.call_id)!=null?ue:"",action:(pe=r==null?void 0:r.action)!=null?pe:{},status:(de=r==null?void 0:r.status)!=null?de:"completed"})):A==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:d,call_id:(_e=r==null?void 0:r.call_id)!=null?_e:"",output:(me=r==null?void 0:r.output)!=null?me:[],status:(fe=r==null?void 0:r.status)!=null?fe:"completed"})):A==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:d,call_id:(ge=r==null?void 0:r.call_id)!=null?ge:"",operation:(he=r==null?void 0:r.operation)!=null?he:{},status:(ye=r==null?void 0:r.status)!=null?ye:"completed"})):A==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:d,call_id:(Re=r==null?void 0:r.call_id)!=null?Re:"",output:(be=r==null?void 0:r.output)!=null?be:"",status:(ke=r==null?void 0:r.status)!=null?ke:"completed"}))}else if(s==="response.code_interpreter_call_code.done")e.push(b({type:"code",item_id:(we=t==null?void 0:t.item_id)!=null?we:"",code:(xe=t==null?void 0:t.code)!=null?xe:"",container_id:(Se=t==null?void 0:t.container_id)!=null?Se:""}));else if(s==="response.code_interpreter_call.interpreting")e.push(b({type:"code",item_id:(Pe=t==null?void 0:t.item_id)!=null?Pe:"",code:(Ce=t==null?void 0:t.code)!=null?Ce:"",container_id:(Te=t==null?void 0:t.container_id)!=null?Te:""}));else if(s==="response.code_interpreter_call.completed")e.push(b({type:"code",item_id:(Ee=t==null?void 0:t.item_id)!=null?Ee:"",code:(Ae=t==null?void 0:t.code)!=null?Ae:"",container_id:(Oe=t==null?void 0:t.container_id)!=null?Oe:""}));else if(s==="response.image_generation_call.in_progress")e.push(b({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(s==="response.image_generation_call.generating")e.push(b({type:"output_media",item_id:(Le=t==null?void 0:t.item_id)!=null?Le:"",url:"",mime_type:"image/png",media_type:"image"}));else if(s==="response.image_generation_call.partial_image"){let A=((Ne=t==null?void 0:t.output_format)!=null?Ne:"png")==="webp"?"image/webp":"image/png",d={};for(let B of["background","size","quality","output_format"])(t==null?void 0:t[B])!=null&&(d[B]=t[B]);e.push(b(S({type:"output_media",item_id:(Ue=t==null?void 0:t.item_id)!=null?Ue:"",url:(qe=t==null?void 0:t.partial_image_b64)!=null?qe:"",mime_type:A,media_type:"image"},Object.keys(d).length?{provider_metadata:d}:{})))}else if(s==="response.shell_call_command.added")e.push(b({type:"shell_call",action:{command:(Me=t==null?void 0:t.command)!=null?Me:""}}));else if(s==="response.shell_call_command.delta")e.push(b({type:"shell_call",action:{command:(je=t==null?void 0:t.delta)!=null?je:""}}));else if(s==="response.shell_call_command.done")e.push(b({type:"shell_call",action:{command:(We=t==null?void 0:t.command)!=null?We:""}}));else if(s==="response.shell_call_output_content.delta")e.push(b({type:"shell_call_output",item_id:($e=t==null?void 0:t.item_id)!=null?$e:"",output:[(Ke=t==null?void 0:t.delta)!=null?Ke:{}]}));else if(s==="response.shell_call_output_content.done")e.push(b({type:"shell_call_output",item_id:(Fe=t==null?void 0:t.item_id)!=null?Fe:"",output:(Ge=t==null?void 0:t.output)!=null?Ge:[]}));else if(s==="response.apply_patch_call_operation_diff.delta")e.push(b({type:"apply_patch_call",item_id:(De=t==null?void 0:t.item_id)!=null?De:"",operation:{diff:(Be=t==null?void 0:t.delta)!=null?Be:""}}));else if(s==="response.apply_patch_call_operation_diff.done")e.push(b({type:"apply_patch_call",item_id:(ze=t==null?void 0:t.item_id)!=null?ze:"",operation:{diff:(Ve=t==null?void 0:t.diff)!=null?Ve:""}}));else if(s==="response.completed"){let r=(Je=t==null?void 0:t.response)!=null?Je:{},A=(Ye=r==null?void 0:r.output)!=null?Ye:[];for(let d of A){let B=d==null?void 0:d.type,K=(Xe=d==null?void 0:d.id)!=null?Xe:"";if(B==="reasoning"){let J=((He=d==null?void 0:d.summary)!=null?He:[]).map(mt=>{var St;return(St=mt==null?void 0:mt.text)!=null?St:""}).join("");e.push(b({type:"thinking",item_id:K,thinking:J,signature:""}))}else if(B==="function_call")o.push(rt((d==null?void 0:d.call_id)||"",(d==null?void 0:d.name)||"",(d==null?void 0:d.arguments)||"",K));else if(B==="message"){let dt=(C=d==null?void 0:d.content)!=null?C:[];for(let J of dt)(J==null?void 0:J.type)==="output_text"&&e.push(b({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(b({type:"code",item_id:K,code:(a=d==null?void 0:d.code)!=null?a:"",container_id:(c=d==null?void 0:d.container_id)!=null?c:""}));else if(B==="image_generation_call"){let dt=(E=d==null?void 0:d.result)!=null?E:"",mt=((pt=d==null?void 0:d.output_format)!=null?pt:"png")==="webp"?"image/webp":"image/png",St={};for(let Rn of["revised_prompt","background","size","quality","output_format"])(d==null?void 0:d[Rn])!=null&&(St[Rn]=d[Rn]);e.push(b(S({type:"output_media",item_id:K,url:dt,mime_type:mt,media_type:"image"},Object.keys(St).length?{provider_metadata:St}:{})))}else B==="mcp_list_tools"?e.push(b({type:"mcp_list_tools",item_id:K,server_label:(jn=d==null?void 0:d.server_label)!=null?jn:"",tools:(Wn=d==null?void 0:d.tools)!=null?Wn:[],error:d==null?void 0:d.error})):B==="mcp_call"?e.push(b({type:"mcp_call",item_id:K,name:($n=d==null?void 0:d.name)!=null?$n:"",server_label:(Kn=d==null?void 0:d.server_label)!=null?Kn:"",arguments:(Fn=d==null?void 0:d.arguments)!=null?Fn:"",output:d==null?void 0:d.output,error:d==null?void 0:d.error,approval_request_id:d==null?void 0:d.approval_request_id})):B==="mcp_approval_request"?e.push(b({type:"mcp_approval_request",item_id:K,name:(Gn=d==null?void 0:d.name)!=null?Gn:"",arguments:(Dn=d==null?void 0:d.arguments)!=null?Dn:"",server_label:(Bn=d==null?void 0:d.server_label)!=null?Bn:""})):B==="shell_call"?e.push(b({type:"shell_call",item_id:K,call_id:(zn=d==null?void 0:d.call_id)!=null?zn:"",action:(Vn=d==null?void 0:d.action)!=null?Vn:{},status:(Jn=d==null?void 0:d.status)!=null?Jn:"completed"})):B==="shell_call_output"?e.push(b({type:"shell_call_output",item_id:K,call_id:(Yn=d==null?void 0:d.call_id)!=null?Yn:"",output:(Xn=d==null?void 0:d.output)!=null?Xn:[],status:(Hn=d==null?void 0:d.status)!=null?Hn:"completed"})):B==="apply_patch_call"?e.push(b({type:"apply_patch_call",item_id:K,call_id:(Zn=d==null?void 0:d.call_id)!=null?Zn:"",operation:(Qn=d==null?void 0:d.operation)!=null?Qn:{},status:(vn=d==null?void 0:d.status)!=null?vn:"completed"})):B==="apply_patch_call_output"&&e.push(b({type:"apply_patch_call_output",item_id:K,call_id:(to=d==null?void 0:d.call_id)!=null?to:"",output:(eo=d==null?void 0:d.output)!=null?eo:"",status:(no=d==null?void 0:d.status)!=null?no:"completed"}))}}let i=Pt(e,o||[]);return Ct(i,n)},_o=(t,n)=>{var i,l,p,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)||"",y=((p=_.reasoningContent)==null?void 0:p.signature)||"";e.push(b({type:"thinking",thinking:m,signature:y}))}else if("text"in _)e.push(b({type:"text",text:_.text||""}));else if("toolUse"in _){let m=_.toolUse||{};o.push(rt(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(rt(m.toolUseId||"",m.name||"",""))}}let s=Pt(e,o);return Ct(s,n)},Us=["size","quality","background","output_format"],mo=(t,n)=>{var i,l,p,u,_,m,y;let e=[],o=(i=t==null?void 0:t.type)!=null?i:"";if(o==="image_generation.partial_image"){let k=(l=t==null?void 0:t.b64_json)!=null?l:"";if(k){let h=(p=t==null?void 0:t.output_format)!=null?p:"png",P=(u=io[h])!=null?u:"image/png",x={},g=t==null?void 0:t.partial_image_index;g!=null&&(x.partial_image_index=g),e.push(b(S({type:"output_media",url:k,mime_type:P,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}}else if(o==="image_generation.completed"){let k=(_=t==null?void 0:t.b64_json)!=null?_:"",h=(m=t==null?void 0:t.output_format)!=null?m:"png",P=(y=io[h])!=null?y:"image/png",x={};for(let g of Us)(t==null?void 0:t[g])!=null&&(x[g]=t[g]);e.push(b(S({type:"output_media",url:k,mime_type:P,media_type:"image"},Object.keys(x).length?{provider_metadata:x}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:n}};var Ro=["openai","openai.azure"],ln=t=>{var s,i,l,p,u,_,m,y,k,h,P,x,g,w,f,R,I,q,j,O,L,W,N,V,$,Z,G,Q,H,it,at,D,ot,ct,gt,ht,yt,Rt,bt,kt,wt,xt,st,U,X,tt,ut,et,nt,Ot,It,Lt,Nt,Ut,qt,Mt,jt,Wt,$t,Kt,Ft,Gt,Dt,Bt,zt,Vt,Jt,Yt,Xt,Ht,Zt,Qt,vt,te,ee,ne,oe,se,re,ie,ae,le,ce,ue,pe,de,_e,me,fe,ge,he,ye,Re,be,ke,we,xe,Se,Pe,Ce,Te,Ee,Ae,Oe,Ie,Le,Ne,Ue,qe,Me,je,We,$e,Ke,Fe,Ge,De,Be,ze,Ve,Je,Ye,Xe,He;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 C of t){let M=C==null?void 0:C.type;if(M==="response.created"){let a=C.response||{};n.id=(s=a.id)!=null?s: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=(p=a.status)!=null?p: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=(y=a.tools)!=null?y:n.tools,n.top_p=(k=a.top_p)!=null?k:n.top_p,n.truncation=(h=a.truncation)!=null?h:n.truncation,n.max_output_tokens=(P=a.max_output_tokens)!=null?P:n.max_output_tokens,n.previous_response_id=(x=a.previous_response_id)!=null?x:n.previous_response_id,n.store=(g=a.store)!=null?g: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 E=a.reasoning;E&&(n.reasoning=E);continue}if(M==="response.in_progress"){let a=C.response||{};n.status=(R=a.status)!=null?R:n.status;continue}if(M==="response.output_item.added"){let a=C.item||{},c=a.id,E=a.type,pt=C.output_index;pt!=null&&c&&(o[pt]=c),E==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(I=a.status)!=null?I:"in_progress"}:E==="function_call"?e[c]={type:"function_call",id:c,call_id:a.call_id,name:a.name,arguments:"",status:(q=a.status)!=null?q:"in_progress"}:E==="message"?e[c]={type:"message",id:c,role:(j=a.role)!=null?j:"assistant",content:[],status:(O=a.status)!=null?O:"in_progress"}:E==="code_interpreter_call"?e[c]={type:"code_interpreter_call",id:c,container_id:a.container_id,code:(L=a.code)!=null?L:"",status:(W=a.status)!=null?W:"in_progress"}:E==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(N=a.status)!=null?N:"in_progress",revised_prompt:(V=a.revised_prompt)!=null?V:"",result:($=a.result)!=null?$:"",background:a.background,size:a.size,quality:a.quality,output_format:a.output_format}:E==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(Z=a.status)!=null?Z:"in_progress"}:E==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(G=a.status)!=null?G:"in_progress"}:E==="mcp_list_tools"?e[c]={type:"mcp_list_tools",id:c,server_label:(Q=a.server_label)!=null?Q:"",tools:(H=a.tools)!=null?H:[],error:(it=a.error)!=null?it:null}:E==="mcp_call"?e[c]={type:"mcp_call",id:c,name:(at=a.name)!=null?at:"",server_label:(D=a.server_label)!=null?D:"",arguments:(ot=a.arguments)!=null?ot:"",output:(ct=a.output)!=null?ct:null,error:(gt=a.error)!=null?gt:null,approval_request_id:(ht=a.approval_request_id)!=null?ht:null,status:(yt=a.status)!=null?yt:"in_progress"}:E==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(Rt=a.name)!=null?Rt:"",arguments:(bt=a.arguments)!=null?bt:"",server_label:(kt=a.server_label)!=null?kt:""}:E==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(wt=a.call_id)!=null?wt:"",action:(xt=a.action)!=null?xt:{},status:(st=a.status)!=null?st:"in_progress"}:E==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(U=a.call_id)!=null?U:"",output:(X=a.output)!=null?X:[],status:(tt=a.status)!=null?tt:"in_progress"}:E==="apply_patch_call"?e[c]={type:"apply_patch_call",id:c,call_id:(ut=a.call_id)!=null?ut:"",operation:(et=a.operation)!=null?et:{},status:(nt=a.status)!=null?nt:"in_progress"}:E==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(Ot=a.call_id)!=null?Ot:"",output:(It=a.output)!=null?It:"",status:(Lt=a.status)!=null?Lt:"in_progress"});continue}if(M==="response.reasoning_summary_part.added"){let a=C.item_id,c=C.part||{};if(a in e&&e[a].type==="reasoning"){let E={type:(Nt=c.type)!=null?Nt:"summary_text",text:(Ut=c.text)!=null?Ut:""};e[a].summary.push(E)}continue}if(M==="response.reasoning_summary_text.delta"){let a=C.item_id,c=(qt=C.delta)!=null?qt:"",E=(Mt=C.summary_index)!=null?Mt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=E;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[E].text+=c}continue}if(M==="response.reasoning_summary_text.done"){let a=C.item_id,c=(jt=C.text)!=null?jt:"",E=(Wt=C.summary_index)!=null?Wt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=E;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[E].text=c}continue}if(M==="response.reasoning_summary_part.done"){let a=C.item_id,c=C.part||{};if(a in e&&e[a].type==="reasoning"){let E=($t=C.summary_index)!=null?$t:0;E<e[a].summary.length&&(e[a].summary[E]={type:(Kt=c.type)!=null?Kt:"summary_text",text:(Ft=c.text)!=null?Ft:""})}continue}if(M==="response.function_call_arguments.delta"){let a=C.item_id,c=(Gt=C.delta)!=null?Gt:"";a in e&&(e[a].arguments=`${e[a].arguments||""}${c}`);continue}if(M==="response.function_call_arguments.done"){let a=C.item_id,c=(Dt=C.arguments)!=null?Dt:"";a in e&&(e[a].arguments=c);continue}if(M==="response.content_part.added"){let a=C.part||{},c=Object.values(e).find(E=>E.type==="message");if(c){let E={type:(Bt=a.type)!=null?Bt:"output_text",text:(zt=a.text)!=null?zt:"",annotations:(Vt=a.annotations)!=null?Vt:[]};c.content.push(E)}continue}if(M==="response.output_text.delta"){let a=(Jt=C.delta)!=null?Jt:"";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||""}${a}`);break}continue}if(M==="response.output_text.done"){let a=(Yt=C.text)!=null?Yt:"";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=a);break}continue}if(M==="response.output_item.done"){let a=C.item||{},c=a.id;c in e&&(e[c].status=(Xt=a.status)!=null?Xt:"completed",a.type==="reasoning"?e[c].summary=(Ht=a.summary)!=null?Ht:e[c].summary:a.type==="function_call"?(e[c].arguments=(Zt=a.arguments)!=null?Zt:e[c].arguments,e[c].call_id=(Qt=a.call_id)!=null?Qt:e[c].call_id,e[c].name=(vt=a.name)!=null?vt:e[c].name):a.type==="message"?(e[c].content=(te=a.content)!=null?te:e[c].content,e[c].role=(ee=a.role)!=null?ee:e[c].role):a.type==="image_generation_call"?(e[c].result=(ne=a.result)!=null?ne:e[c].result,e[c].revised_prompt=(oe=a.revised_prompt)!=null?oe:e[c].revised_prompt,e[c].background=(se=a.background)!=null?se:e[c].background,e[c].size=(re=a.size)!=null?re:e[c].size,e[c].quality=(ie=a.quality)!=null?ie:e[c].quality,e[c].output_format=(ae=a.output_format)!=null?ae:e[c].output_format):a.type==="code_interpreter_call"?(e[c].code=(le=a.code)!=null?le:e[c].code,e[c].container_id=(ce=a.container_id)!=null?ce:e[c].container_id):a.type==="mcp_list_tools"?(e[c].tools=(ue=a.tools)!=null?ue:e[c].tools,e[c].error=(pe=a.error)!=null?pe:e[c].error):a.type==="mcp_call"?(e[c].name=(de=a.name)!=null?de:e[c].name,e[c].arguments=(_e=a.arguments)!=null?_e:e[c].arguments,e[c].output=(me=a.output)!=null?me:e[c].output,e[c].error=(fe=a.error)!=null?fe:e[c].error,e[c].server_label=(ge=a.server_label)!=null?ge:e[c].server_label):a.type==="mcp_approval_request"?(e[c].name=(he=a.name)!=null?he:e[c].name,e[c].arguments=(ye=a.arguments)!=null?ye:e[c].arguments,e[c].server_label=(Re=a.server_label)!=null?Re:e[c].server_label):a.type==="shell_call"?(e[c].action=(be=a.action)!=null?be:e[c].action,e[c].call_id=(ke=a.call_id)!=null?ke:e[c].call_id):a.type==="shell_call_output"?(e[c].output=(we=a.output)!=null?we: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=(Se=a.operation)!=null?Se:e[c].operation,e[c].call_id=(Pe=a.call_id)!=null?Pe:e[c].call_id):a.type==="apply_patch_call_output"?(e[c].output=(Ce=a.output)!=null?Ce:e[c].output,e[c].call_id=(Te=a.call_id)!=null?Te: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(M==="response.image_generation_call.in_progress"){let a=C.item_id;a in e&&(e[a].status="in_progress");continue}if(M==="response.image_generation_call.generating"){let a=C.item_id;a in e&&(e[a].status="generating");continue}if(M==="response.image_generation_call.partial_image"){let a=C.item_id;a in e&&(e[a].result=(Ee=C.partial_image_b64)!=null?Ee:e[a].result,e[a].background=(Ae=C.background)!=null?Ae:e[a].background,e[a].size=(Oe=C.size)!=null?Oe:e[a].size,e[a].quality=(Ie=C.quality)!=null?Ie:e[a].quality,e[a].output_format=(Le=C.output_format)!=null?Le:e[a].output_format);continue}if(M==="response.shell_call_command.added"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[C.command_index]=(Ne=C.command)!=null?Ne:"",e[a].action=c}continue}if(M==="response.shell_call_command.delta"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]);let E=(Ue=C.command_index)!=null?Ue:0;c.commands[E]=((qe=c.commands[E])!=null?qe:"")+((Me=C.delta)!=null?Me:""),e[a].action=c}continue}if(M==="response.shell_call_command.done"){let a=o[C.output_index];if(a&&a in e){let c=e[a].action||{commands:[]};c.commands||(c.commands=[]),c.commands[C.command_index]=(je=C.command)!=null?je:"",e[a].action=c}continue}if(M==="response.shell_call_output_content.delta"){let a=C.item_id;if(a&&a in e){e[a].output||(e[a].output=[]);let c=(We=C.command_index)!=null?We:0,E=($e=e[a].output[c])!=null?$e:{stdout:"",stderr:""},pt=(Ke=C.delta)!=null?Ke:{};pt.stdout&&(E.stdout=((Fe=E.stdout)!=null?Fe:"")+pt.stdout),pt.stderr&&(E.stderr=((Ge=E.stderr)!=null?Ge:"")+pt.stderr),e[a].output[c]=E}continue}if(M==="response.shell_call_output_content.done"){let a=C.item_id;a&&a in e&&(e[a].output=(De=C.output)!=null?De:e[a].output);continue}if(M==="response.apply_patch_call_operation_diff.delta"){let a=C.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=((Be=c.diff)!=null?Be:"")+((ze=C.delta)!=null?ze:""),e[a].operation=c}continue}if(M==="response.apply_patch_call_operation_diff.done"){let a=C.item_id;if(a&&a in e){let c=e[a].operation||{};c.diff=(Ve=C.diff)!=null?Ve:c.diff,e[a].operation=c}continue}if(M==="response.completed"){let a=C.response||{};n.status=(Ye=(Je=a.status)!=null?Je:n.status)!=null?Ye:"completed",n.usage=(Xe=a.usage)!=null?Xe:n.usage,n.output=(He=a.output)!=null?He:n.output,a.reasoning&&(n.reasoning=a.reasoning);continue}}return n},xn=t=>{var p,u,_,m,y,k,h,P,x,g;let n=null,e,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},s=t.at(-1);if(!s)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 R=(p=f.tool_calls)==null?void 0:p[0];if(R){i=i||[];let I=i.at(-1);if(!I||R.id){i.push({id:R.id||"",type:R.type||"function",function:{name:((u=R.function)==null?void 0:u.name)||"",arguments:((_=R.function)==null?void 0:_.arguments)||""}});continue}I.function.name=`${I.function.name}${((m=R.function)==null?void 0:m.name)||""}`,I.function.arguments=`${I.function.arguments}${((y=R.function)==null?void 0:y.arguments)||""}`}}let l=t[0].choices.at(0);return o.choices.push({finish_reason:(k=l==null?void 0:l.finish_reason)!=null?k:"stop",index:(h=l==null?void 0:l.index)!=null?h: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:(x=l==null?void 0:l.delta.refusal)!=null?x:null}}),o.id=s.id,o.model=s.model,o.created=s.created,o.system_fingerprint=s.system_fingerprint,o.usage=(g=s.usage)!=null?g:void 0,o},fo=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 s of t)s.choices.length>0&&s.choices[0].text&&(o=`${o}${s.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},Sn=t=>{var m,y,k,h,P,x;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,s=null,i="",l="",p="",u="",_={};for(let g of t)if(g.type==="message_start")n=S({},g.message);else if(g.type==="content_block_start")o=S({},g.content_block),s="index"in g&&typeof g.index=="number"?g.index:null,o.type==="thinking"?(i="",l=""):o.type==="text"?p="":(o.type==="tool_use"||o.type==="server_tool_use")&&(u="");else if(g.type==="content_block_delta"){let w=g.delta,f="index"in g&&typeof g.index=="number"?g.index:null;if((w==null?void 0:w.type)==="citations_delta"){let R=w.citation;if(R&&typeof R=="object"&&R.type==="web_search_result_location"&&f!==null){let I=S(S({type:"url_citation",url:(m=R.url)!=null?m:"",title:(y=R.title)!=null?y:"",start_index:(k=R.start_index)!=null?k:0,end_index:(h=R.end_index)!=null?h:0},R.cited_text!=null?{cited_text:R.cited_text}:{}),R.encrypted_index!=null?{encrypted_index:R.encrypted_index}:{});_[f]||(_[f]=[]),_[f].push(I)}}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&&(p+=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(g.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=i,o.thinking=l;else if(o.type==="text")o.text=p,o.citations=null,s!==null&&((P=_[s])!=null&&P.length)&&(o.annotations=_[s]);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,s=null,i="",l="",p="",u=""}else g.type==="message_delta"&&("usage"in g&&g.usage&&(n.usage=Y(S({},n.usage),{output_tokens:(x=g.usage.output_tokens)!=null?x:0})),"delta"in g&&g.delta&&("stop_reason"in g.delta&&g.delta.stop_reason!==void 0&&(n.stop_reason=g.delta.stop_reason),"stop_sequence"in g.delta&&g.delta.stop_sequence!==void 0&&(n.stop_sequence=g.delta.stop_sequence)));return n},go=t=>{let n={completion:"",id:"",model:"",stop_reason:"",type:"completion"},e=t.at(-1);if(!e)return n;let o="";for(let s of t)o=`${o}${s.completion}`;return n.completion=o,n.id=e.id,n.model=e.model,n.stop_reason=e.stop_reason,n},qs=t=>{var l,p,u,_,m,y,k,h,P,x;let n=null,e={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=t.at(-1).data;if(!o)return e;let s;for(let g of t){if(g.data.choices.length===0)continue;let w=g.data.choices[0].delta;w.content&&(n=`${n||""}${w.content||""}`);let f=(l=w.toolCalls)==null?void 0:l[0];if(f){s=s||[];let R=s.at(-1);if(!R||f.id){s.push({id:f.id||"",type:f.type||"function",function:{name:((p=f.function)==null?void 0:p.name)||"",arguments:((u=f.function)==null?void 0:u.arguments)||""}});continue}R.function.name=`${R.function.name}${((_=f.function)==null?void 0:_.name)||""}`,R.function.arguments=`${R.function.arguments}${((m=f.function)==null?void 0:m.arguments)||""}`}}let i=t[0].data.choices.at(0);return e.choices.push({finish_reason:(y=i==null?void 0:i.finish_reason)!=null?y:"stop",index:(k=i==null?void 0:i.index)!=null?k:0,logprobs:(h=i==null?void 0:i.logprobs)!=null?h:null,message:{role:"assistant",content:n,tool_calls:s||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=(x=o.usage)!=null?x:void 0,e},ho=t=>{let n={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},e=[],o=null,s="",i="",l="",p="";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}},s=""}}else if("contentBlockDelta"in u){let _=u.contentBlockDelta.delta;if("text"in _)i+=_.text;else if("reasoningContent"in _){let m=_.reasoningContent;"text"in m?p+=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 u)if(o&&s){try{o.toolUse.input=JSON.parse(s)}catch(_){o.toolUse.input={}}e.push(o),o=null,s=""}else i?(e.push({text:i}),i=""):p&&l&&(e.push({reasoningContent:{reasoningText:{text:p,signature:l}}}),p="",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},Ms=(t,n,e,o,s,i,l,p,u)=>{var k,h,P;let _=S({},l),m=[];if(t){let x={text:t,thought:!0};p&&(x.thoughtSignature=p),m.push(x)}if(n){let x={text:n,thought:null};u&&(x.thoughtSignature=u),m.push(x)}for(let x of s)m.push({executableCode:x});for(let x of i)m.push({codeExecutionResult:x});for(let x of o)m.push({inlineData:x});for(let x of e)m.push({functionCall:x});m.length>0&&((h=(k=_.candidates)==null?void 0:k[0])!=null&&h.content)&&(_.candidates[0].content.parts=m);let y=(P=l==null?void 0:l.candidates)==null?void 0:P[0];return y&&(_.candidates||(_.candidates=[]),_.candidates[0]||(_.candidates[0]={content:{parts:[]}}),y.groundingMetadata!=null&&(_.candidates[0].groundingMetadata=y.groundingMetadata),y.urlContextMetadata!=null&&(_.candidates[0].urlContextMetadata=y.urlContextMetadata),y.citationMetadata!=null&&(_.candidates[0].citationMetadata=y.citationMetadata)),_},bo=t=>{var m,y,k,h,P,x,g;let{GenerateContentResponse:n}=require("@google/genai");if(!t.length)return new n;let e="",o="",s=[],i=[],l=[],p=[],u=null,_=null;for(let w of t)if(w.candidates&&((y=(m=w.candidates[0])==null?void 0:m.content)!=null&&y.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)s.push(f.functionCall);else if(f.inlineData){let R=f.inlineData;i.push({data:(k=R.data)!=null?k:"",mimeType:(h=R.mimeType)!=null?h:"image/png"})}else f.executableCode?l.push({code:(P=f.executableCode.code)!=null?P:"",language:f.executableCode.language}):f.codeExecutionResult&&p.push({output:(x=f.codeExecutionResult.output)!=null?x:"",outcome:(g=f.codeExecutionResult.outcome)!=null?g:"OUTCOME_OK"});return Ms(e,o,s,i,l,p,t[t.length-1],u,_)},js=t=>bo(t),Ws=t=>bo(t),$s=["size","quality","background","output_format"],Pn=t=>{var i,l,p,u,_;let n={created:null,data:[],usage:null},e={},o="png";for(let m of t){let y=(i=m==null?void 0:m.type)!=null?i:"";if(y==="image_generation.partial_image"){let k=m.b64_json;if(k!=null){let h=(l=m.partial_image_index)!=null?l:0;e[h]=k}}else if(y==="image_generation.completed"){let k=m.b64_json;if(k!=null){let h=(p=m.partial_image_index)!=null?p:0;e[h]=k}n.created=(u=m.created_at)!=null?u:n.created,n.usage=(_=m.usage)!=null?_:n.usage;for(let h of $s)m[h]!=null&&(n[h]=m[h]);m.output_format&&(o=m.output_format)}}n.output_format||(n.output_format=o);let s=Object.keys(e).map(Number).sort((m,y)=>m-y);return s.length>0&&(n.data=s.map(m=>({b64_json:e[m]}))),n},ko=(t,n="openai.chat.completions.create")=>{if(n==="openai.responses.create"||n==="openai.AzureOpenAI.responses.create")return ln(t);if(n==="openai.images.generate"||n==="openai.AzureOpenAI.images.generate")return Pn(t);if("completion"in t[0])return t.reduce((e,o)=>Y(S({},o),{completion:`${e.completion}${o.completion}`}),{});if(n==="anthropic.messages.create")return Sn(t);if("text"in t[0].choices[0]){let e="";for(let s of t)e=`${e}${s.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=xn(t);return e.choices[0]=S(S({},e.choices[0]),e.choices[0].message),e}return""},yo=(t,n,e)=>{let o=n.model.provider,s=n.model.name;if(o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&s.startsWith("claude"))return co(t,n,e==null?void 0:e.anthropicBlockTypeByIndex);if(o==="google"||o==="vertexai"&&s.startsWith("gemini"))return uo(t,n);if(o==="amazon.bedrock")return _o(t,n);if(o==="mistral")return wn(t.data,n);if(o==="openai"||o==="openai.azure"){let i=n.model.api_type||"chat-completions";return i==="responses"?po(t,n):i==="images"?mo(t,n):wn(t,n)}return null};function wo(t,n,e,o){return rn(this,null,function*(){var k,h,P;let s={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 p=[],u=l==="anthropic"||l==="anthropic.bedrock"||l==="vertexai"&&((P=(h=(k=o.model)==null?void 0:k.name)==null?void 0:h.startsWith)==null?void 0:P.call(h,"claude")),_={};try{for(var x=an(t),g,w,f;g=!(w=yield new ft(x.next())).done;g=!1){let R=w.value;p.push(R),u&&(R==null?void 0:R.type)==="content_block_start"&&R.content_block&&(_[R.index]=R.content_block.type),s.raw_response=R,s.prompt_blueprint=yo(R,o,{anthropicBlockTypeByIndex:_}),yield s}}catch(w){f=[w]}finally{try{g&&(w=x.return)&&(yield new ft(w.call(x)))}finally{if(f)throw f[0]}}let m=e(p);l==="amazon.bedrock"&&(m.ResponseMetadata=i),s.raw_response=m,s.prompt_blueprint=yo(m,o),yield s;let y=yield new ft(n({request_response:m}));s.request_id=y.request_id,s.prompt_blueprint=y.prompt_blueprint,yield s})}var xo={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:xn},completion:{function_name:"openai.completions.create",stream_function:fo}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:ln}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:Pn}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:Sn},completion:{function_name:"anthropic.completions.create",stream_function:go}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:xn},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:fo}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ln},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ln}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:Pn}},google:{chat:{function_name:"google.convo.send_message",stream_function:js},completion:{function_name:"google.model.generate_content",stream_function:Ws}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:ho},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:ho}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:Sn},completion:{function_name:"anthropic.completions.create",stream_function:go}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:qs},completion:{function_name:"",stream_function:null}}};var Eo="1.3.1",Ks=()=>{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"},Fs=Ks(),Gs=`promptlayer-js/${Eo} (node ${Fs})`,z=()=>({"User-Agent":Gs,"X-SDK-Version":Eo}),Cn="SET_WORKFLOW_COMPLETE";var Qe=class extends Error{constructor(n,e){super(`Server error: ${n} ${e}`),this.name="PromptLayerRetryableHttpError",this.status=n,this.statusText=e}};function Ds(t,n,e,o){return T(this,null,function*(){let s=yield F(`${t}/workflow-version-execution-results?workflow_version_execution_id=${n}&return_all_outputs=${e}`,S({headers:o},z()));if(!s.ok)throw new Error("Failed to fetch final output");return s.json()})}function Ao(t,n,e,o,s){return function(i){return T(this,null,function*(){if(i.name===Cn)try{let l=JSON.parse(i.data),p=l.result_code,u;if(p==="OK"||p==null)u=l.final_output;else if(p==="EXCEEDS_SIZE_LIMIT")u=yield Ds(t,e,o,s),n.resolve(u);else throw new Error(`Unsupported final output code: ${p}`);n.resolve(u)}catch(l){n.reject(l)}})}}function Bs(p){return T(this,arguments,function*({token:t,channelName:n,executionId:e,returnAllOutputs:o,headers:s,timeout:i,baseURL:l}){let u=new Po.default.Realtime(t),_=u.channels.get(n),m={},y=new Promise((h,P)=>{m.resolve=h,m.reject=P}),k=Ao(l,m,e,o,s);yield _.subscribe(Cn,k);try{return yield new Promise((h,P)=>{let x=setTimeout(()=>{P(new Error("Workflow execution did not complete properly (timeout)"))},i);y.then(g=>{clearTimeout(x),h(g)}).catch(g=>{clearTimeout(x),P(g)})})}finally{console.log("Closing client"),_.unsubscribe(Cn,k),u.close(),console.log("Closed client")}})}var F=(t,n)=>T(null,null,function*(){return(0,To.default)(()=>T(null,null,function*(){let e=yield fetch(t,n);if(e.status>=500&&e.status<600||e.status===429)throw new Qe(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.`)}})}),Oo=(t,n,e,o=!0)=>T(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?Vs(t,n,e.request_response,e,o):yield Io(t,n,e,o)}),Io=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(e)}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);v(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(s){if(o)throw s;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${s}`)}return e.request_response}),Lo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-metadata`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track metadata";if(o)throw new Error(l);return v(i,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),No=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-score`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track score";if(o)throw new Error(l);return v(i,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${s}`),!1}return!0}),Uo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/library-track-prompt`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track prompt";if(o)throw new Error(l);return v(i,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${s}`),!1}return!0}),qo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/track-group`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(Y(S({},e),{api_key:t}))}),i=yield s.json();if(s.status!==200){let l=i.message||i.error||"Failed to track group";if(o)throw new Error(l);return v(i,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}}catch(s){if(o)throw s;return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${s}`),!1}return!0}),Mo=(t,n,e=!0)=>T(null,null,function*(){try{let o=yield F(`${n}/create-group`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify({api_key:t})}),s=yield o.json();if(o.status!==200){let i=s.message||s.error||"Failed to create group";if(e)throw new Error(i);return v(s,"WARNING: While creating a group PromptLayer had the following error"),!1}return s.id}catch(o){if(e)throw o;return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${o}`),!1}}),Tn=(t,n,e,o,s=!0)=>T(null,null,function*(){try{let i=new URL(`${n}/prompt-templates/${e}`),l=yield F(i,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(o)}),p=yield l.json();if(l.status!==200){let u=p.message||p.error||"Failed to fetch prompt template";if(s)throw new Error(u);return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${u}`),null}return p.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${p.warning}`),p}catch(i){if(s)throw i;return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${i}`),null}}),jo=(t,n,e,o=!0)=>T(null,null,function*(){let s=yield F(`${n}/rest/prompt-templates`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify({prompt_template:S({},e),prompt_version:S({},e),release_labels:e.release_labels?e.release_labels:void 0})}),i=yield s.json();if(s.status!==200&&s.status!==201){let l=i.message||i.error||"Failed to publish prompt template";if(o)throw new Error(l);v(i,"WARNING: While publishing a prompt template PromptLayer had the following error")}return i}),Wo=(t,n,e,o=!0)=>T(null,null,function*(){var p;let s=new URL(`${n}/prompt-templates`);Object.entries(e||{}).forEach(([u,_])=>s.searchParams.append(u,_.toString()));let i=yield F(s,{headers:S({"Content-Type":"application/json","X-API-KEY":t},z())}),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 v(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(p=l.items)!=null?p:[]}),zs=t=>T(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((s,i)=>{let l=m=>{_(),s(m)},p=Ao(t.baseURL,{resolve:l,reject:i},t.executionId,t.returnAllOutputs,t.headers);o.on("publication",m=>{p({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()})}),$o=_=>T(null,[_],function*({workflow_name:t,input_variables:n,metadata:e={},workflow_label_name:o=null,workflow_version_number:s=null,return_all_outputs:i=!1,api_key:l,timeout:p=36e5,baseURL:u}){let m={input_variables:n,metadata:e,workflow_label_name:o,workflow_version_number:s,return_all_outputs:i},y=S({"Content-Type":"application/json","X-API-KEY":l},z());try{let k=yield F(`${u}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:y,body:JSON.stringify(m)});if(k.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield k.json().catch(()=>({}))).error||k.statusText}`};let h=yield k.json();h.warning&&console.warn(`WARNING: ${h.warning}`);let P=h.workflow_version_execution_id;if(!P)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let x=`workflow_updates:${P}`,w=yield(yield F(`${u}/ws-token-request-library?capability=${x}`,{method:"POST",headers:y})).json(),R={token:w.token_details.token,channelName:x,executionId:P,returnAllOutputs:i,headers:y,timeout:p,baseURL:u};return w.messaging_backend==="centrifugo"?zs(R):yield Bs(R)}catch(k){throw console.error(`Failed to run workflow: ${k instanceof Error?k.message:k}`),k}});function Vs(t,n,e,o,s=!0){return rn(this,null,function*(){let i=[];try{for(var u=an(e),_,m,y;_=!(m=yield new ft(u.next())).done;_=!1){let k=m.value;yield o.return_pl_id?[k,null]:k,i.push(k)}}catch(m){y=[m]}finally{try{_&&(m=u.return)&&(yield new ft(m.call(u)))}finally{if(y)throw y[0]}}let l=ko(i,o.function_name),p=yield new ft(Io(t,n,Y(S({},o),{request_response:l,request_end_time:new Date().toISOString()}),s));if(p&&o.return_pl_id){let k=p[1];yield[i.at(-1),k]}})}var v=(t,n)=>{try{console.warn(`${n}: ${t.message}`)}catch(e){console.warn(`${n}: ${t}`)}},Ko=(t,n,e=!0)=>T(null,null,function*(){try{let o=yield F(`${t}/track-request`,{method:"POST",headers:S({"Content-Type":"application/json"},z()),body:JSON.stringify(n)}),s=yield o.json();if(o.status!==200){let i=s.message||s.error||"Failed to track request";if(e)throw new Error(i);v(s,"WARNING: While logging your request, PromptLayer experienced the following error:")}return s}catch(o){if(e)throw o;console.warn(`WARNING: While logging your request PromptLayer had the following error: ${o}`)}return{}}),Js=(t,n)=>T(null,null,function*(){return yield t.chat.completions.create(n)}),Ys=(t,n)=>T(null,null,function*(){return yield t.completions.create(n)}),Fo={chat:Js,completion:Ys},Go=(t,n)=>T(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 s=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(s==="chat-completions"){let p=Fo[t.prompt_template.type];return yield p(o,n)}else return s==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Do=(t,n)=>T(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 s=(l=(i=t.metadata)==null?void 0:i.model)==null?void 0:l.api_type;if(s==="chat-completions"){let p=Fo[t.prompt_template.type];return yield p(o,n)}else return s==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Bo=(t,n)=>T(null,null,function*(){return t.messages.create(n)}),Xs=(t,n)=>T(null,null,function*(){return t.completions.create(n)}),zo={chat:Bo,completion:Xs},Vo=(t,n)=>T(null,null,function*(){let e=require("@anthropic-ai/sdk").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey}),s=zo[t.prompt_template.type];return s(o,n)}),Jo=(t,n,e,o=!0)=>T(null,null,function*(){try{let s=yield F(`${n}/log-request`,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(e)}),i=yield s.json();if(s.status!==201){let l=i.message||i.error||"Failed to log request";if(o)throw new Error(l);return v(i,"WARNING: While logging your request PromptLayer had the following error"),null}return i}catch(s){if(o)throw s;return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${s}`),null}}),Hs=(t,n)=>T(null,null,function*(){var l,p;let e=n==null?void 0:n.history,o=n==null?void 0:n.generationConfig,s=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:(p=e.slice(0,-1))!=null?p:[],config:o});return n!=null&&n.stream?yield i.sendMessageStream({message:s}):yield i.sendMessage({message:s})}),Zs=(t,o)=>T(null,null,function*(){var s=o,{stream:n}=s,e=sn(s,["stream"]);return n?yield t.generateContentStream(S({},e)):yield t.generateContent(S({},e))}),Qs={chat:Hs,completion:Zs},En=(t,n)=>T(null,null,function*(){let{GoogleGenAI:e}=yield import("@google/genai"),o=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,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:s,scopes:["https://www.googleapis.com/auth/cloud-platform"]},p=o?new e({apiKey:o}):new e({vertexai:!0,project:s,location:i,googleAuthOptions:l}),u=Qs[t.prompt_template.type];return yield u(p,n)}),So=t=>t.replace(/_([a-z])/g,(n,e)=>e.toUpperCase()),cn=(t,n=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>cn(e,n)):Object.fromEntries(Object.entries(t).map(([e,o])=>n.has(e)?[So(e),o]:[So(e),cn(o,n)])),Yo=(t,n,e={},o=!1)=>{var u,_,m,y,k,h,P,x,g;let s=(m=n==null?void 0:n.client)!=null?m:(_=(u=t.metadata)==null?void 0:u.model)==null?void 0:_.provider,i=(k=(y=t.metadata)==null?void 0:y.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:o});["google","vertexai"].includes(s)&&((P=(h=t.metadata)==null?void 0:h.model)!=null&&P.name.startsWith("gemini"))&&(l=cn(l,new Set(["function_declarations","properties"])));let p={baseURL:(g=n==null?void 0:n.base_url)!=null?g:(x=t.provider_base_url)==null?void 0:x.url,apiKey:n==null?void 0:n.api_key};return Object.entries(p).forEach(([w,f])=>{f!==void 0&&(l[w]=f)}),o&&Ro.includes(s)&&i==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:s,kwargs:l}},Xo=(t,n)=>{let e=xo[t];if(!e)throw new Error(`Unsupported provider type: ${t}`);let o=n.type,s=e[o];if(!s)throw new Error(`Unsupported template type '${n.type}' for provider '${t}'`);return s},Ho=(t,n)=>T(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 En(t,n);if(e.name.startsWith("claude")){let{AnthropicVertex:s}=yield import("@anthropic-ai/vertex-sdk"),i=new s({baseURL:n.baseURL});if(t.prompt_template.type==="chat")return Bo(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`)}),Zo=(t,n)=>T(null,null,function*(){let{BedrockRuntimeClient:e,ConverseCommand:o,ConverseStreamCommand:s}=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 s(S({},n));return yield i.send(l)}else{n==null||delete n.stream;let l=new o(S({},n));return yield i.send(l)}}),Qo=(t,n)=>T(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}),s=zo[t.prompt_template.type];return s(o,n)}),vo=(t,n)=>T(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),o=new e({apiKey:process.env.MISTRAL_API_KEY});return n=cn(n,new Set),n!=null&&n.stream?(delete n.stream,yield o.chat.stream(n)):(delete n.stream,yield o.chat.complete(n))}),An=t=>{var n,e,o,s,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=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:i.call(s,t))==null?void 0:l.trim()};var un=class{constructor(n,e,o=!0){this.create=()=>Mo(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var _t=require("@opentelemetry/api"),ve=require("@opentelemetry/core");var On=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(ve.ExportResultCode.SUCCESS);let e=n.map(o=>{var s;return{name:o.name,context:{trace_id:o.spanContext().traceId,span_id:o.spanContext().spanId,trace_state:((s=o.spanContext().traceState)==null?void 0:s.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(S({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return F(this.url,{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},z()),body:JSON.stringify({spans:e})}).then(o=>o.ok?ve.ExportResultCode.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
+
HTTP error! status: ${o.status}`),ve.ExportResultCode.FAILED)).catch(o=>(console.error("Error exporting spans:",o),ve.ExportResultCode.FAILED))}shutdown(){return Promise.resolve()}},ts=On;var es=lt(require("@opentelemetry/api")),ns=require("@opentelemetry/sdk-trace-base"),os=require("@opentelemetry/sdk-trace-node"),Tt=(t="promptlayer-tracer")=>es.trace.getTracer(t),ss=(t,n,e)=>{let o=new os.NodeTracerProvider,s=new ts(t,n,e),i=new ns.SimpleSpanProcessor(s);o.addSpanProcessor(i),o.register()};var vs=Tt(),In=(t,n,e,o="",s="openai")=>{let i={construct:(l,p)=>{let u=Reflect.construct(l,p);return Object.defineProperties(u,{function_name:{value:o,writable:!0},provider:{value:s}}),new Proxy(u,i)},get:(l,p,u)=>{let _=l[p],m=`${Reflect.get(l,"function_name")}.${p.toString()}`;return typeof _=="object"?(Object.defineProperties(_,{function_name:{value:m,writable:!0},provider:{value:s}}),new Proxy(_,i)):typeof _=="function"?(...y)=>{var w,f,R,I,q,j;let k=new Date().toISOString(),h=Reflect.get(l,"provider"),P=(w=y[0])==null?void 0:w.return_pl_id,x=(f=y[0])==null?void 0:f.pl_tags,g=(R=y[0])==null?void 0:R.pl_warn_on_error;return(I=y[0])==null||delete I.return_pl_id,(q=y[0])==null||delete q.pl_tags,(j=y[0])==null||delete j.pl_warn_on_error,vs.startActiveSpan(`${h}.${m}`,O=>T(null,null,function*(){try{O.setAttribute("function_input",JSON.stringify(y));let L=Reflect.apply(_,l,y),W=O.spanContext().spanId;return L instanceof Promise?new Promise((N,V)=>{L.then($=>T(null,null,function*(){let Z=yield Oo(t,n,{api_key:t,provider_type:h,function_name:m,request_start_time:k,request_end_time:new Date().toISOString(),request_response:$,kwargs:y[0],return_pl_id:P,tags:x,span_id:W},!g);O.setAttribute("function_output",JSON.stringify(Z)),O.setAttribute("response_status","success"),O.end(),N(Z)})).catch($=>{O.recordException($),O.setAttribute("response_status","error"),O.end(),V($)})}):(O.setAttribute("function_output",JSON.stringify(L)),O.setAttribute("response_status","success"),O.end(),L)}catch(L){throw O.recordException(L),O.setAttribute("response_status","error"),O.end(),L}}))}:Reflect.get(l,p,u)}};return new Proxy(e,i)};var tn=t=>Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)),en=t=>T(null,null,function*(){var o;if(((o=t.headers.get("content-type"))!=null?o:"").includes("application/json"))return t.json();let e=yield t.text();if(!e)return{};try{return JSON.parse(e)}catch(s){return{message:e}}}),rs=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 pn=t=>`${t}/api/public/v2/skill-collections`,dn=(t,n)=>`${pn(t)}/${encodeURIComponent(n)}`,is=(t,n)=>`${dn(t,n)}/versions`;var Ln=t=>"zipFile"in t;var as=["claude_code","openai","openclaw"],ls=(t,n)=>{if(!t){if(n==="publishing")throw new Error("provider is required when publishing a skill collection.");return}if(!as.includes(t))throw new Error(`provider must be one of: ${as.join(", ")}.`)},cs=(t,n,e,o,s=!0)=>T(null,null,function*(){let i=new URL(dn(n,e));Object.entries(o||{}).forEach(([p,u])=>{u!==void 0&&i.searchParams.append(p,String(u))});let l=yield F(i,{headers:S({"X-API-KEY":t},z())});if(l.status!==200){let p=yield en(l),u=p.message||p.error||"Failed to pull skill collection";if(s)throw new Error(u);return v(p,"WARNING: While pulling a skill collection PromptLayer had the following error"),null}return(o==null?void 0:o.format)==="zip"?l.arrayBuffer():yield l.json()}),us=(t,n,e,o=!0)=>T(null,null,function*(){ls(e.provider,"publishing");let s=Ln(e)?(()=>{var _;let p=new FormData,u=tn({name:e.name,folder_id:e.folderId,provider:e.provider,commit_message:e.commitMessage});return p.append("files",rs(e.zipFile),(_=e.fileName)!=null?_:"skill-collection.zip"),p.append("json",JSON.stringify(u)),p})():JSON.stringify(tn({name:e.name,folder_id:e.folderId,provider:e.provider,files:e.files,commit_message:e.commitMessage})),i=Ln(e)?yield F(pn(n),{method:"POST",headers:S({"X-API-KEY":t},z()),body:s}):yield F(pn(n),{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:s}),l=yield en(i);if(i.status!==201){let p=l.message||l.error||"Failed to publish skill collection";if(o)throw new Error(p);return v(l,"WARNING: While publishing a skill collection PromptLayer had the following error"),null}return l}),ps=(t,n,e,o,s=!0)=>T(null,null,function*(){let i=yield F(dn(n,e),{method:"PATCH",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(tn(o))}),l=yield en(i);if(i.status!==200){let p=l.message||l.error||"Failed to update skill collection";if(s)throw new Error(p);return v(l,"WARNING: While updating a skill collection PromptLayer had the following error"),null}return l}),ds=(t,n,e,o,s=!0)=>T(null,null,function*(){ls(o.provider,"updating");let i=tn({file_updates:o.fileUpdates,moves:o.moves,deletes:o.deletes,commit_message:o.commitMessage,release_label:o.releaseLabel,provider:o.provider}),l=yield F(is(n,e),{method:"POST",headers:S({"Content-Type":"application/json","X-API-KEY":t},z()),body:JSON.stringify(i)}),p=yield en(l);if(l.status!==201){let u=p.message||p.error||"Failed to save skill collection version";if(s)throw new Error(u);return v(p,"WARNING: While saving a skill collection version PromptLayer had the following error"),null}return p});var Nn=t=>Array.isArray(t)&&t.length>0,tr=t=>Nn(t.fileUpdates)||Nn(t.moves)||Nn(t.deletes)||t.commitMessage!==void 0||t.releaseLabel!==void 0||t.provider!==void 0,er=(t,n,e)=>{var o;return Y(S({},t!=null?t:{}),{success:(o=t==null?void 0:t.success)!=null?o:!0,skill_collection:n,version:e})},_n=class{constructor(n,e,o=!0){this.pull=(n,e)=>cs(this.apiKey,this.baseURL,n,e,this.throwOnError);this.publish=n=>us(this.apiKey,this.baseURL,n,this.throwOnError);this.update=(n,e)=>T(this,null,function*(){var _,m,y,k;let o=e.name!==void 0,s=tr(e);if(!o&&!s)throw new Error("At least one of name, fileUpdates, moves, deletes, commitMessage, releaseLabel, or provider must be provided.");let i=n,l=null,p,u=null;if(o){let h=yield ps(this.apiKey,this.baseURL,n,{name:e.name},this.throwOnError);if(!h)return null;l=h,p=h.skill_collection,u=(_=h.version)!=null?_:null,i=String(h.skill_collection.id)}if(s){let h=yield ds(this.apiKey,this.baseURL,i,{fileUpdates:e.fileUpdates,moves:e.moves,deletes:e.deletes,commitMessage:e.commitMessage,releaseLabel:e.releaseLabel,provider:e.provider},this.throwOnError);if(!h)return null;l=h,p=(m=h.skill_collection)!=null?m:p,u=(y=h.version)!=null?y:u}if(!p){let h=yield this.pull(i);if(!h)return null;if(h instanceof ArrayBuffer)throw new Error("Expected JSON skill collection response but received binary data.");l=h,p=h.skill_collection,u=(k=h.version)!=null?k:u}return er(l,p,u)});this.apiKey=n,this.baseURL=e,this.throwOnError=o}};var mn=lt(require("@opentelemetry/api"));var ms=(t,n,e)=>function(...o){let s=Tt(),i=l=>{try{e&&Object.entries(e).forEach(([u,_])=>{l.setAttribute(u,_)}),l.setAttribute("function_input",JSON.stringify(o));let p=n(...o);return p instanceof Promise?p.then(u=>(l.setAttribute("function_output",JSON.stringify(u)),l.setStatus({code:mn.SpanStatusCode.OK}),u)).catch(u=>{throw _s(l,u,o),u}).finally(()=>l.end()):(l.setAttribute("function_output",JSON.stringify(p)),l.setStatus({code:mn.SpanStatusCode.OK}),l.end(),p)}catch(p){throw _s(l,p,o),p}};return s.startActiveSpan(t,i)},_s=(t,n,e)=>{t.setAttribute("function_input",JSON.stringify(e)),t.setStatus({code:mn.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),t.end()};var qn=lt(require("nunjucks")),nr=6e4,fs=1e3,or=512,Et=class t{constructor(n,e=fs){this.entries=new Map;this.nonRenderable=new Map;this.ttlMs=n*1e3,this.maxSize=e}static makeKey(n,e){var o,s,i,l;return e?[n,(o=e.version)!=null?o:null,(s=e.label)!=null?s:null,(i=e.provider)!=null?i:null,(l=e.model)!=null?l:null]:[n,null,null,null,null]}static serialize(n){return JSON.stringify(n)}get(n){let e=t.serialize(n),o=this.entries.get(e);if(!o)return[null,!1];let s=performance.now()-o.timestamp<this.ttlMs;return[structuredClone(o.response),s]}put(n,e){let o=t.serialize(n);this.entries.size>=this.maxSize&&!this.entries.has(o)&&this.evictOldestEntry(),this.entries.set(o,{response:structuredClone(e),timestamp:performance.now()})}isNonRenderable(n){let e=t.serialize(n),o=this.nonRenderable.get(e);return o===void 0?!1:performance.now()-o>=nr?(this.nonRenderable.delete(e),!1):!0}markNonRenderable(n){let e=t.serialize(n);this.nonRenderable.size>=fs&&!this.nonRenderable.has(e)&&this.evictOldestNonRenderable(),this.nonRenderable.set(e,performance.now())}clear(){this.entries.clear(),this.nonRenderable.clear()}invalidate(n){for(let e of this.entries.keys())JSON.parse(e)[0]===n&&this.entries.delete(e);for(let e of this.nonRenderable.keys())JSON.parse(e)[0]===n&&this.nonRenderable.delete(e)}evictOldestEntry(){let n=null,e=1/0;for(let[o,s]of this.entries)s.timestamp<e&&(e=s.timestamp,n=o);n!==null&&this.entries.delete(n)}evictOldestNonRenderable(){let n=null,e=1/0;for(let[o,s]of this.nonRenderable)s<e&&(e=s,n=o);n!==null&&this.nonRenderable.delete(n)}};function gs(t){return t?!!(t.metadata_filters||t.model_parameter_overrides):!1}function hs(t){var o,s;let n=t.prompt_template;if(!n)return!1;if(n.type==="chat"){let i=(o=n.messages)!=null?o:[];for(let l of i)if(l.role==="placeholder")return!1}let e=(s=n.tools)!=null?s:[];for(let i of e)if(i.type==="variable")return!1;return!0}function ys(t){let n=new Set(["input_variables","metadata_filters","model_parameter_overrides"]),e={};if(t)for(let[o,s]of Object.entries(t))n.has(o)||(e[o]=s);return e.skip_input_variable_rendering=!0,e}var sr=new qn.default.Environment(null,{autoescape:!1}),nn=new Map;function rr(t){let n=nn.get(t);if(!n){if(nn.size>=or){let e=nn.keys().next().value;e!==void 0&&nn.delete(e)}n=qn.default.compile(t,sr),nn.set(t,n)}return n}function ir(t,n){return rr(t).render(n)}function ar(t,n){return t.replace(/\{(\w+)(?:[!:][^}]*)?\}/g,(e,o)=>{if(o in n){let s=n[o];return s!=null?String(s):""}return""})}function At(t,n,e){try{return n==="jinja2"?ir(t,e):ar(t,e)}catch(o){return t}}function lr(t){var n,e;return t.type==="chat"?((n=t.messages)!=null?n:[]).map(s=>{var i;return(i=s.template_format)!=null?i:"f-string"}):t.type==="completion"?[(e=t.template_format)!=null?e:"f-string"]:["f-string"]}function cr(t,n){var e,o,s,i,l;if(t.type==="chat"){let p=(e=t.messages)!=null?e:[];for(let u of p){let _=(o=u.template_format)!=null?o:"f-string",m=(s=u.content)!=null?s:[];for(let y of m)y&&y.type==="text"&&typeof y.text=="string"&&(y.text=At(y.text,_,n))}}else if(t.type==="completion"){let p=(i=t.template_format)!=null?i:"f-string",u=(l=t.content)!=null?l:[];for(let _ of u)_&&_.type==="text"&&typeof _.text=="string"&&(_.text=At(_.text,p,n))}}var ur=new Set(["text","input_text"]);function Un(t,n,e){var o;if(typeof t=="string")return At(t,n,e);if(Array.isArray(t)){for(let s of t)if(s&&typeof s=="object"&&"text"in s&&typeof s.text=="string"){let i=s,l=(o=i.type)!=null?o:"text";ur.has(l)&&(i.text=At(i.text,n,e))}return t}return t}function fn(t,n,e){for(let o of t)o&&typeof o.text=="string"&&(o.text=At(o.text,n,e))}function pr(t){if("system_instruction"in t)return t.system_instruction;let n=t.generation_config;if(n&&typeof n=="object"&&!Array.isArray(n))return n.system_instruction}function dr(t,n,e){var _,m,y,k,h,P,x;let o=n.length>0?n[0]:"f-string",s=(_=t.messages)!=null?_:[];for(let g of s)"content"in g&&(g.content=Un(g.content,o,e));let i=(m=t.input)!=null?m:[];for(let g of i)if(g&&typeof g=="object"&&"content"in g){let w=g;w.content=Un(w.content,o,e)}"system"in t&&(t.system=Un(t.system,o,e));let l=(y=t.contents)!=null?y:[];for(let g of l)g&&typeof g=="object"&&fn((k=g.parts)!=null?k:[],o,e);let p=(h=t.history)!=null?h:[];for(let g of p)g&&typeof g=="object"&&fn((P=g.parts)!=null?P:[],o,e);let u=pr(t);u&&typeof u=="object"&&!Array.isArray(u)?fn((x=u.parts)!=null?x:[],o,e):Array.isArray(u)&&fn(u,o,e),typeof t.prompt=="string"&&(t.prompt=At(t.prompt,o,e))}function gn(t,n){let e=t.llm_kwargs!==null&&t.llm_kwargs!==void 0,o;if(e)o=n!=null?n:{};else{if(!n)return t;o=n}let s=t.prompt_template;if(s){cr(s,o);let i=lr(s);t.llm_kwargs&&dr(t.llm_kwargs,i,o)}return t}function _r(t){if(t instanceof Qe||t instanceof TypeError)return!0;let n=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();if(n.includes("timeout")||n.includes("timed out")||n.includes("econnreset")||n.includes("econnrefused")||n.includes("network"))return!0;if(t&&typeof t=="object"&&"status"in t){let e=t.status;if(typeof e=="number"&&e>=500)return!0}return!1}var hn=class{constructor(n,e,o=!0,s=null){this.get=(n,e)=>T(this,null,function*(){return this._cache&&!gs(e)?this._getWithCache(n,e):this._fetchNormal(n,e)});this._fetchNormal=(n,e)=>Tn(this.apiKey,this.baseURL,n,e,this.throwOnError);this._getWithCache=(n,e)=>T(this,null,function*(){let o=this._cache,s=Et.makeKey(n,e),i=e==null?void 0:e.input_variables;if(o.isNonRenderable(s))return this._fetchNormal(n,e);let[l,p]=o.get(s);if(l!==null&&p)return gn(l,i);let u=l,_=ys(e),m;try{m=yield Tn(this.apiKey,this.baseURL,n,_,!0)}catch(y){if(_r(y)){if(u!==null)return gn(u,i);if(!this.throwOnError)return null}if(!this.throwOnError)return null;throw y}return m?hs(m)?(o.put(s,m),gn(m,i)):(o.markNonRenderable(s),this._fetchNormal(n,e)):null});this.publish=n=>T(this,null,function*(){let e=yield jo(this.apiKey,this.baseURL,n,this.throwOnError);if(this._cache&&e){let o=n.prompt_name;o&&this._cache.invalidate(o)}return e});this.invalidate=n=>{this._cache&&(n?this._cache.invalidate(n):this._cache.clear())};this.all=n=>Wo(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o,this._cache=s}};var mr=(t,n,e,o=!0)=>{if(!(e.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[s,i]of Object.entries(e.metadata))if(typeof s!="string"||typeof i!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return Lo(t,n,e,o)},fr=(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 No(t,n,e,o)},gr=(t,n,e,o=!0)=>{if(!(e.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return Uo(t,n,e,o)},hr=(t,n,e,o=!0)=>qo(t,n,e,o),yn=class{constructor(n,e,o=!0){this.group=n=>hr(this.apiKey,this.baseURL,n,this.throwOnError);this.metadata=n=>mr(this.apiKey,this.baseURL,n,this.throwOnError);this.prompt=n=>gr(this.apiKey,this.baseURL,n,this.throwOnError);this.score=n=>fr(this.apiKey,this.baseURL,n,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};function yr(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function Rr(t){return t&&typeof t=="object"&&t.constructor?t.constructor.name:""}function Rs(t){let n=yr(t),e=Rr(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 bs=lt(require("@opentelemetry/api"));var br={openai:Go,anthropic:Vo,"openai.azure":Do,google:En,vertexai:Ho,"amazon.bedrock":Zo,"anthropic.bedrock":Qo,mistral:vo},kr=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(s=>s in o))},Mn=class{constructor({apiKey:n=An("PROMPTLAYER_API_KEY"),baseURL:e=An("PROMPTLAYER_BASE_URL"),enableTracing:o=!1,throwOnError:s=!0,cacheTtlSeconds:i=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=s;let l=i>0?new Et(i):null;this.templates=new hn(n,this.baseURL,this.throwOnError,l),this.skills=new _n(n,this.baseURL,this.throwOnError),this.group=new un(n,this.baseURL,this.throwOnError),this.track=new yn(n,this.baseURL,this.throwOnError),this.wrapWithSpan=ms,o&&ss(o,n,this.baseURL)}invalidate(n){this.templates.invalidate(n)}get Anthropic(){try{let n=require("@anthropic-ai/sdk").default;return In(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 In(this.apiKey,this.baseURL,n,"openai","openai")}catch(n){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(k){return T(this,arguments,function*({promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:s,tags:i,metadata:l,groupId:p,modelParameterOverrides:u,stream:_=!1,provider:m,model:y}){return Tt().startActiveSpan("PromptLayer Run",P=>T(this,null,function*(){try{let x={promptName:n,promptVersion:e,promptReleaseLabel:o,inputVariables:s,tags:i,metadata:l,groupId:p,modelParameterOverrides:u,stream:_};P.setAttribute("function_input",JSON.stringify(x));let g=s,w={label:o,version:e,metadata_filters:l,provider:m,model:y,model_parameter_overrides:u};s&&(w.input_variables=s);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 R=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 I=f.metadata;if(!I)throw new Error(`Prompt '${n}' does not have any metadata associated with it.`);let q=I.model;if(!q)throw new Error(`Prompt '${n}' does not have a model parameters associated with it.`);let j=f.custom_provider,O=new Date().toISOString(),{provider_type:L,kwargs:W}=Yo(f,j,u,_),N=L;if(L==="openai"||L==="openai.azure"){let D=q.api_type;N=`${L}:${D}`}q.name.startsWith("gemini")?N="google":q.name.startsWith("claude")&&(N="anthropic");let V=Xo(N,R),{function_name:$,stream_function:Z}=V,G=br[L];if(!G)throw new Error(`No request function found for provider: ${L}`);let Q=D=>{let ot=new Date().toISOString();return Ko(this.baseURL,S({function_name:$,provider_type:L,args:[],kwargs:W,tags:i,request_start_time:O,request_end_time:ot,api_key:this.apiKey,metadata:l,prompt_id:f.id,prompt_version:f.version,prompt_input_variables:g,group_id:p,return_prompt_blueprint:!0,span_id:P.spanContext().spanId},D),this.throwOnError)},H;try{H=yield G(f,W)}catch(D){let ot=Rs(D),ct=D instanceof Error?D.message:String(D);throw yield Q({request_response:{},status:"ERROR",error_type:ot,error_message:ct}),D}if(_)return wo(H,Q,Z,l||f.metadata);let it=yield Q({request_response:H}),at={request_id:it.request_id,raw_response:H,prompt_blueprint:it.prompt_blueprint};return P.setAttribute("function_output",JSON.stringify(at)),at}catch(x){throw P.setStatus({code:bs.SpanStatusCode.ERROR,message:x instanceof Error?x.message:"Unknown error"}),x}finally{P.end()}}))})}runWorkflow(p){return T(this,arguments,function*({workflowName:n,inputVariables:e={},metadata:o={},workflowLabelName:s=null,workflowVersion:i=null,returnAllOutputs:l=!1}){try{let u=yield $o({workflow_name:n,input_variables:e,metadata:o,workflow_label_name:s,workflow_version_number:i,return_all_outputs:l,api_key:this.apiKey,baseURL:this.baseURL});if(!l&&kr(u)){let m=Object.values(u).filter(k=>k.is_output_node===!0);if(m.length===0)throw new Error(JSON.stringify(u,null,2));if(!m.some(k=>k.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 T(this,null,function*(){return Jo(this.apiKey,this.baseURL,n,this.throwOnError)})}};0&&(module.exports={PromptLayer});
|
|
3
3
|
//# sourceMappingURL=index.js.map
|