promptlayer 1.0.61 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/esm/chunk-SWBNW72U.js +2 -0
- package/dist/esm/chunk-SWBNW72U.js.map +1 -0
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/openai-agents.js +3 -0
- package/dist/esm/openai-agents.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/openai-agents.d.mts +42 -0
- package/dist/openai-agents.d.ts +42 -0
- package/dist/openai-agents.js +3 -0
- package/dist/openai-agents.js.map +1 -0
- package/package.json +23 -2
- package/src/integrations/openai-agents/helpers.test.ts +254 -0
- package/src/integrations/openai-agents/ids.ts +27 -0
- package/src/integrations/openai-agents/index.ts +8 -0
- package/src/integrations/openai-agents/instrumentation.test.ts +46 -0
- package/src/integrations/openai-agents/instrumentation.ts +47 -0
- package/src/integrations/openai-agents/mapping.ts +714 -0
- package/src/integrations/openai-agents/otlp-json.ts +120 -0
- package/src/integrations/openai-agents/processor.test.ts +509 -0
- package/src/integrations/openai-agents/processor.ts +388 -0
- package/src/integrations/openai-agents/time.ts +56 -0
- package/src/integrations/openai-agents/types.ts +49 -0
- package/src/integrations/openai-agents/url.ts +9 -0
- package/src/openai-agents.ts +1 -0
- package/tsup.config.ts +4 -1
- package/vitest.config.ts +3 -0
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Do=Object.defineProperty,Fo=Object.defineProperties;var Bo=Object.getOwnPropertyDescriptors;var He=Object.getOwnPropertySymbols;var Gn=Object.prototype.hasOwnProperty,Kn=Object.prototype.propertyIsEnumerable;var ln=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t);var $n=(t,n,e)=>n in t?Do(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e,E=(t,n)=>{for(var e in n||(n={}))Gn.call(n,e)&&$n(t,e,n[e]);if(He)for(var e of He(n))Kn.call(n,e)&&$n(t,e,n[e]);return t},Y=(t,n)=>Fo(t,Bo(n));var Tt=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(n,e)=>(typeof require!="undefined"?require:n)[e]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Xe=(t,n)=>{var e={};for(var o in t)Gn.call(t,o)&&n.indexOf(o)<0&&(e[o]=t[o]);if(t!=null&&He)for(var o of He(t))n.indexOf(o)<0&&Kn.call(t,o)&&(e[o]=t[o]);return e};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())}),_t=function(t,n){this[0]=t,this[1]=n},Ze=(t,n,e)=>{var o=(l,d,u,_)=>{try{var m=e[l](d),b=(d=m.value)instanceof _t,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[ln("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var Qe=(t,n,e)=>(n=t[ln("asyncIterator")])?n.call(t):(t=t[ln("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);import ns from"ably";import{Centrifuge as os}from"centrifuge";import ss from"p-retry";var Dn={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=Xe(r,["type","item_id"]);let i=E({type:t},e);return n&&(i.id=n),i},Et=(t,n)=>({role:"assistant",input_variables:[],template_format:"f-string",content:t,tool_calls:n}),Ot=(t,n)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:n});function Fn(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 zn=(t,n,e)=>{var l,d,u,_,m,b,R,x,O,T,h,w,f,g,I,M,W,C,N,j,q,B,$,X,K,Z,J,rt,at,D,nt,it,mt,ft,gt,yt,ht,bt,Rt,xt;let o=[],r=[];if(Array.isArray(t.content)){for(let L of t.content){if(!L||typeof L!="object")continue;let V=L.type;if(V==="text"){let v=(l=L.text)!=null?l:"",lt=(u=(d=L.citations)!=null?d:L.annotations)!=null?u:[],tt=[];for(let et of lt)et&&typeof et=="object"&&tt.push(Fn(et));o.push(y(E({type:"text",text:v},tt.length>0?{annotations:tt}:{})))}else if(V==="thinking")o.push(y({type:"thinking",thinking:(_=L.thinking)!=null?_:"",signature:(m=L.signature)!=null?m:""}));else if(V==="tool_use")r.push(st((b=L.id)!=null?b:"",(R=L.name)!=null?R:"",(x=L.input)!=null?x:{}));else if(V==="server_tool_use")o.push(y({type:"server_tool_use",id:(O=L.id)!=null?O:"",name:(T=L.name)!=null?T:"",input:(h=L.input)!=null?h:{}}));else if(V==="web_search_tool_result"){let v=(w=L.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=L.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=L.tool_use_id)!=null?g:"",content:(I=L.content)!=null?I:{}}))}let ot=Et(o,r);return Ot(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(((C=t.content_block)==null?void 0:C.type)==="tool_use")r.push(st((N=t.content_block.id)!=null?N:"",(j=t.content_block.name)!=null?j:"",{}));else if(((q=t.content_block)==null?void 0:q.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(((K=t.content_block)==null?void 0:K.type)==="web_search_tool_result"){let ot=(Z=t.content_block.content)!=null?Z:[],L=[];for(let V of ot)if(V&&typeof V=="object"&&V.type==="web_search_result"){let v=V;L.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:L}))}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(((mt=t.delta)==null?void 0:mt.type)==="text_delta")o.push(y({type:"text",text:(ft=t.delta.text)!=null?ft:""}));else if(((gt=t.delta)==null?void 0:gt.type)==="signature_delta")o.push(y({type:"thinking",thinking:"",signature:(yt=t.delta.signature)!=null?yt:""}));else if(((ht=t.delta)==null?void 0:ht.type)==="input_json_delta")(e==null?void 0:e[t.index])==="server_tool_use"?o.push(y({type:"server_tool_use",id:"",name:"",input:(bt=t.delta.partial_json)!=null?bt:{}})):r.push(st("","",(Rt=t.delta.partial_json)!=null?Rt:""));else if(((xt=t.delta)==null?void 0:xt.type)==="citations_delta"&&t.delta.citation){let ot=t.delta.citation,L=[Fn(ot)];o.push(y({type:"text",text:"",annotations:L}))}}let i=Et(o,r);return Ot(i,n)},zo=t=>typeof t=="string"&&t.startsWith("image/");function Bn(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 Vo(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 Jo(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 Yo(t,n){if(!t||typeof t!="object")return[];let e=t.groundingMetadata,o=t.citationMetadata,r=Ho(e,n),i=Jo(o);return[...r,...i]}function Ho(t,n){var d,u,_,m,b,R,x,O,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?_:{},I=(m=f.groundingChunkIndices)!=null?m:[],M=(b=g.startIndex)!=null?b:0,W=(R=g.endIndex)!=null?R:0,C=r(g,M,W);for(let N of I){if(typeof N!="number"||N>=e.length)continue;let j=e[N];if(!j||typeof j!="object")continue;let q=j.maps;if(q&&typeof q=="object"){let K=(x=q.uri)!=null?x:"",Z=(O=q.title)!=null?O:"",J=q.placeId;(K||Z)&&h.push(E(Y(E({type:"map_citation",url:K,title:Z||K},J!=null?{place_id:J}:{}),{start_index:M,end_index:W}),C!=null?{cited_text:C}:{}));continue}let B=j.retrievedContext;if(B&&typeof B=="object"){let K=(T=B.title)!=null?T:"";K&&!w.has(K)&&(w.add(K),h.push({type:"file_citation",file_id:K,filename:K,index:N}));continue}let{uri:$,title:X}=Bn(j);$&&h.push(E({type:"url_citation",url:$,title:X||$,start_index:M,end_index:W},C!=null?{cited_text:C}:{}))}}return h}if(!t||typeof t!="object")return[];let i=[],l=new Set;return e.forEach((h,w)=>{var C,N,j;if(!h||typeof h!="object")return;let f=h,g=f.maps;if(g&&typeof g=="object"){let q=(C=g.uri)!=null?C:"",B=(N=g.title)!=null?N:"",$=g.placeId;(q||B)&&i.push(Y(E({type:"map_citation",url:q,title:B||q},$!=null?{place_id:$}:{}),{start_index:0,end_index:0}));return}let I=f.retrievedContext;if(I&&typeof I=="object"){let q=(j=I.title)!=null?j:"";q&&!l.has(q)&&(l.add(q),i.push({type:"file_citation",file_id:q,filename:q,index:w}));return}let{uri:M,title:W}=Bn(f);M&&i.push({type:"url_citation",url:M,title:W||M,start_index:0,end_index:0})}),i}var Vn=(t,n)=>{var u,_,m,b,R,x,O,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 I=(x=g.mimeType)!=null?x:"image/png",M=(O=g.data)!=null?O:"";if(zo(I)&&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:I,media_type:"image"},Object.keys(W).length?{provider_metadata:W}:{})))}}}let r=(T=t.candidates)==null?void 0:T[0],i=Vo(r),l=Yo(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=Et(e,o);return Ot(d,n)},cn=(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=Et(e,o);return Ot(r,n)},Jn=(t,n)=>{var l,d,u,_,m,b,R,x,O,T,h,w,f,g,I,M,W,C,N,j,q,B,$,X,K,Z,J,rt,at,D,nt,it,mt,ft,gt,yt,ht,bt,Rt,xt,ot,L,V,v,lt,tt,et,Pt,kt,St,Ct,It,Nt,qt,Lt,Mt,Ut,Wt,jt,$t,Gt,Kt,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,Oe,Ae,Pe,ke,Se,Ce,Ie,Ne,qe,Le,Me,Ue,We,je,$e,Ge,Ke,De,Fe,Be,ze,Ve,Je,A,U,a,c,P,ct,bn,Rn,xn,wn,Tn,En,On,An,Pn,kn,Sn,Cn,In,Nn,qn,Ln,Mn,Un,Wn,jn;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=(O=t==null?void 0:t.item_id)!=null?O:"";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=(I=t==null?void 0:t.item)!=null?I:{},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:(C=s==null?void 0:s.container_id)!=null?C:""})):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:(q=s==null?void 0:s.name)!=null?q:"",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:(K=s==null?void 0:s.arguments)!=null?K:"",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:(mt=s==null?void 0:s.call_id)!=null?mt:"",operation:(ft=s==null?void 0:s.operation)!=null?ft:{},status:(gt=s==null?void 0:s.status)!=null?gt:"in_progress"})):k==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(yt=s==null?void 0:s.call_id)!=null?yt:"",output:(ht=s==null?void 0:s.output)!=null?ht:"",status:(bt=s==null?void 0:s.status)!=null?bt:"in_progress"}))}else if(r==="response.content_part.added"){let s=(Rt=t==null?void 0:t.part)!=null?Rt:{},k=(xt=s==null?void 0:s.type)!=null?xt:"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:(L=s==null?void 0:s.text)!=null?L:"",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:(Pt=s==null?void 0:s.url)!=null?Pt:"",start_index:(kt=s==null?void 0:s.start_index)!=null?kt:0,end_index:(St=s==null?void 0:s.end_index)!=null?St:0}:k==="file_citation"?p={type:"file_citation",index:(Ct=s==null?void 0:s.index)!=null?Ct:0,file_id:(It=s==null?void 0:s.file_id)!=null?It:"",filename:(Nt=s==null?void 0:s.filename)!=null?Nt:""}: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:(Lt=t==null?void 0:t.item_id)!=null?Lt:"",code:(Mt=t==null?void 0:t.code)!=null?Mt:"",container_id:(Ut=t==null?void 0:t.container_id)!=null?Ut:""}));else if(r==="response.code_interpreter_call_code.delta")e.push(y({type:"code",item_id:(Wt=t==null?void 0:t.item_id)!=null?Wt:"",code:(jt=t==null?void 0:t.delta)!=null?jt:"",container_id:($t=t==null?void 0:t.container_id)!=null?$t:""}));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:(Kt=t==null?void 0:t.item_id)!=null?Kt:"",text:s}))}else if(r==="response.output_text.done")e.push(y({type:"text",item_id:(Dt=t==null?void 0:t.item_id)!=null?Dt:"",text:(Ft=t==null?void 0:t.text)!=null?Ft:""}));else if(r==="response.output_item.done"){let s=(Bt=t==null?void 0:t.item)!=null?Bt:{},k=s==null?void 0:s.type,p=(zt=s==null?void 0:s.id)!=null?zt:"";if(k==="reasoning"){let G=((Vt=s==null?void 0:s.summary)!=null?Vt:[]).map(pt=>{var z;return(z=pt==null?void 0:pt.text)!=null?z:""}).join("");e.push(y({type:"thinking",item_id:p,thinking:G,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=(Jt=s==null?void 0:s.content)!=null?Jt:[];for(let G of F)(G==null?void 0:G.type)==="output_text"&&e.push(y({type:"text",item_id:p,text:(Yt=G==null?void 0:G.text)!=null?Yt:""}))}else if(k==="code_interpreter_call")e.push(y({type:"code",item_id:p,code:(Ht=s==null?void 0:s.code)!=null?Ht:"",container_id:(Xt=s==null?void 0:s.container_id)!=null?Xt:""}));else if(k==="image_generation_call"){let F=(Zt=s==null?void 0:s.result)!=null?Zt:"",pt=((Qt=s==null?void 0:s.output_format)!=null?Qt:"png")==="webp"?"image/webp":"image/png",z={};for(let dt of["revised_prompt","background","size","quality","output_format"])(s==null?void 0:s[dt])!=null&&(z[dt]=s[dt]);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:(vt=s==null?void 0:s.server_label)!=null?vt:"",tools:(te=s==null?void 0:s.tools)!=null?te:[],error:s==null?void 0:s.error})):k==="mcp_call"?e.push(y({type:"mcp_call",item_id:p,name:(ee=s==null?void 0:s.name)!=null?ee:"",server_label:(ne=s==null?void 0:s.server_label)!=null?ne:"",arguments:(oe=s==null?void 0:s.arguments)!=null?oe:"",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:(se=s==null?void 0:s.name)!=null?se:"",arguments:(re=s==null?void 0:s.arguments)!=null?re:"",server_label:(ae=s==null?void 0:s.server_label)!=null?ae:""})):k==="shell_call"?e.push(y({type:"shell_call",item_id:p,call_id:(ie=s==null?void 0:s.call_id)!=null?ie:"",action:(le=s==null?void 0:s.action)!=null?le:{},status:(ce=s==null?void 0:s.status)!=null?ce:"completed"})):k==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:p,call_id:(pe=s==null?void 0:s.call_id)!=null?pe:"",output:(ue=s==null?void 0:s.output)!=null?ue:[],status:(de=s==null?void 0:s.status)!=null?de:"completed"})):k==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:p,call_id:(_e=s==null?void 0:s.call_id)!=null?_e:"",operation:(me=s==null?void 0:s.operation)!=null?me:{},status:(fe=s==null?void 0:s.status)!=null?fe:"completed"})):k==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:p,call_id:(ge=s==null?void 0:s.call_id)!=null?ge:"",output:(ye=s==null?void 0:s.output)!=null?ye:"",status:(he=s==null?void 0:s.status)!=null?he:"completed"}))}else if(r==="response.code_interpreter_call_code.done")e.push(y({type:"code",item_id:(be=t==null?void 0:t.item_id)!=null?be:"",code:(Re=t==null?void 0:t.code)!=null?Re:"",container_id:(xe=t==null?void 0:t.container_id)!=null?xe:""}));else if(r==="response.code_interpreter_call.interpreting")e.push(y({type:"code",item_id:(we=t==null?void 0:t.item_id)!=null?we:"",code:(Te=t==null?void 0:t.code)!=null?Te:"",container_id:(Ee=t==null?void 0:t.container_id)!=null?Ee:""}));else if(r==="response.code_interpreter_call.completed")e.push(y({type:"code",item_id:(Oe=t==null?void 0:t.item_id)!=null?Oe:"",code:(Ae=t==null?void 0:t.code)!=null?Ae:"",container_id:(Pe=t==null?void 0:t.container_id)!=null?Pe:""}));else if(r==="response.image_generation_call.in_progress")e.push(y({type:"output_media",item_id:(ke=t==null?void 0:t.item_id)!=null?ke:"",url:"",mime_type:"image/png",media_type:"image"}));else if(r==="response.image_generation_call.generating")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.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:(Ie=t==null?void 0:t.item_id)!=null?Ie:"",url:(Ne=t==null?void 0:t.partial_image_b64)!=null?Ne:"",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:(Le=t==null?void 0:t.delta)!=null?Le:""}}));else if(r==="response.shell_call_command.done")e.push(y({type:"shell_call",action:{command:(Me=t==null?void 0:t.command)!=null?Me:""}}));else if(r==="response.shell_call_output_content.delta")e.push(y({type:"shell_call_output",item_id:(Ue=t==null?void 0:t.item_id)!=null?Ue:"",output:[(We=t==null?void 0:t.delta)!=null?We:{}]}));else if(r==="response.shell_call_output_content.done")e.push(y({type:"shell_call_output",item_id:(je=t==null?void 0:t.item_id)!=null?je:"",output:($e=t==null?void 0:t.output)!=null?$e:[]}));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:(Ke=t==null?void 0:t.delta)!=null?Ke:""}}));else if(r==="response.apply_patch_call_operation_diff.done")e.push(y({type:"apply_patch_call",item_id:(De=t==null?void 0:t.item_id)!=null?De:"",operation:{diff:(Fe=t==null?void 0:t.diff)!=null?Fe:""}}));else if(r==="response.completed"){let s=(Be=t==null?void 0:t.response)!=null?Be:{},k=(ze=s==null?void 0:s.output)!=null?ze:[];for(let p of k){let F=p==null?void 0:p.type,G=(Ve=p==null?void 0:p.id)!=null?Ve:"";if(F==="reasoning"){let z=((Je=p==null?void 0:p.summary)!=null?Je:[]).map(dt=>{var wt;return(wt=dt==null?void 0:dt.text)!=null?wt:""}).join("");e.push(y({type:"thinking",item_id:G,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)||"",G));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:G,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:G,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=(P=p==null?void 0:p.result)!=null?P:"",dt=((ct=p==null?void 0:p.output_format)!=null?ct:"png")==="webp"?"image/webp":"image/png",wt={};for(let an of["revised_prompt","background","size","quality","output_format"])(p==null?void 0:p[an])!=null&&(wt[an]=p[an]);e.push(y(E({type:"output_media",item_id:G,url:pt,mime_type:dt,media_type:"image"},Object.keys(wt).length?{provider_metadata:wt}:{})))}else F==="mcp_list_tools"?e.push(y({type:"mcp_list_tools",item_id:G,server_label:(bn=p==null?void 0:p.server_label)!=null?bn:"",tools:(Rn=p==null?void 0:p.tools)!=null?Rn:[],error:p==null?void 0:p.error})):F==="mcp_call"?e.push(y({type:"mcp_call",item_id:G,name:(xn=p==null?void 0:p.name)!=null?xn:"",server_label:(wn=p==null?void 0:p.server_label)!=null?wn:"",arguments:(Tn=p==null?void 0:p.arguments)!=null?Tn:"",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:G,name:(En=p==null?void 0:p.name)!=null?En:"",arguments:(On=p==null?void 0:p.arguments)!=null?On:"",server_label:(An=p==null?void 0:p.server_label)!=null?An:""})):F==="shell_call"?e.push(y({type:"shell_call",item_id:G,call_id:(Pn=p==null?void 0:p.call_id)!=null?Pn:"",action:(kn=p==null?void 0:p.action)!=null?kn:{},status:(Sn=p==null?void 0:p.status)!=null?Sn:"completed"})):F==="shell_call_output"?e.push(y({type:"shell_call_output",item_id:G,call_id:(Cn=p==null?void 0:p.call_id)!=null?Cn:"",output:(In=p==null?void 0:p.output)!=null?In:[],status:(Nn=p==null?void 0:p.status)!=null?Nn:"completed"})):F==="apply_patch_call"?e.push(y({type:"apply_patch_call",item_id:G,call_id:(qn=p==null?void 0:p.call_id)!=null?qn:"",operation:(Ln=p==null?void 0:p.operation)!=null?Ln:{},status:(Mn=p==null?void 0:p.status)!=null?Mn:"completed"})):F==="apply_patch_call_output"&&e.push(y({type:"apply_patch_call_output",item_id:G,call_id:(Un=p==null?void 0:p.call_id)!=null?Un:"",output:(Wn=p==null?void 0:p.output)!=null?Wn:"",status:(jn=p==null?void 0:p.status)!=null?jn:"completed"}))}}let i=Et(e,o||[]);return Ot(i,n)},Yn=(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=Et(e,o);return Ot(r,n)},Xo=["size","quality","background","output_format"],Hn=(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",O=(u=Dn[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:O,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",O=(b=Dn[x])!=null?b:"image/png",T={};for(let h of Xo)(t==null?void 0:t[h])!=null&&(T[h]=t[h]);e.push(y(E({type:"output_media",url:R,mime_type:O,media_type:"image"},Object.keys(T).length?{provider_metadata:T}:{})))}return{prompt_template:{type:"completion",content:e,input_variables:[]},metadata:n}};var to=["openai","openai.azure"],ve=t=>{var r,i,l,d,u,_,m,b,R,x,O,T,h,w,f,g,I,M,W,C,N,j,q,B,$,X,K,Z,J,rt,at,D,nt,it,mt,ft,gt,yt,ht,bt,Rt,xt,ot,L,V,v,lt,tt,et,Pt,kt,St,Ct,It,Nt,qt,Lt,Mt,Ut,Wt,jt,$t,Gt,Kt,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,Oe,Ae,Pe,ke,Se,Ce,Ie,Ne,qe,Le,Me,Ue,We,je,$e,Ge,Ke,De,Fe,Be,ze,Ve,Je;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=(O=a.max_output_tokens)!=null?O: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 P=a.reasoning;P&&(n.reasoning=P);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,P=a.type,ct=A.output_index;ct!=null&&c&&(o[ct]=c),P==="reasoning"?e[c]={type:"reasoning",id:c,summary:[],status:(I=a.status)!=null?I:"in_progress"}:P==="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"}:P==="message"?e[c]={type:"message",id:c,role:(W=a.role)!=null?W:"assistant",content:[],status:(C=a.status)!=null?C:"in_progress"}:P==="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"}:P==="image_generation_call"?e[c]={type:"image_generation_call",id:c,status:(q=a.status)!=null?q:"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}:P==="web_search_call"?e[c]={type:"web_search_call",id:c,status:(X=a.status)!=null?X:"in_progress"}:P==="file_search_call"?e[c]={type:"file_search_call",id:c,status:(K=a.status)!=null?K:"in_progress"}:P==="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}:P==="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:(mt=a.error)!=null?mt:null,approval_request_id:(ft=a.approval_request_id)!=null?ft:null,status:(gt=a.status)!=null?gt:"in_progress"}:P==="mcp_approval_request"?e[c]={type:"mcp_approval_request",id:c,name:(yt=a.name)!=null?yt:"",arguments:(ht=a.arguments)!=null?ht:"",server_label:(bt=a.server_label)!=null?bt:""}:P==="shell_call"?e[c]={type:"shell_call",id:c,call_id:(Rt=a.call_id)!=null?Rt:"",action:(xt=a.action)!=null?xt:{},status:(ot=a.status)!=null?ot:"in_progress"}:P==="shell_call_output"?e[c]={type:"shell_call_output",id:c,call_id:(L=a.call_id)!=null?L:"",output:(V=a.output)!=null?V:[],status:(v=a.status)!=null?v:"in_progress"}:P==="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"}:P==="apply_patch_call_output"&&(e[c]={type:"apply_patch_call_output",id:c,call_id:(Pt=a.call_id)!=null?Pt:"",output:(kt=a.output)!=null?kt:"",status:(St=a.status)!=null?St:"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 P={type:(Ct=c.type)!=null?Ct:"summary_text",text:(It=c.text)!=null?It:""};e[a].summary.push(P)}continue}if(U==="response.reasoning_summary_text.delta"){let a=A.item_id,c=(Nt=A.delta)!=null?Nt:"",P=(qt=A.summary_index)!=null?qt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=P;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[P].text+=c}continue}if(U==="response.reasoning_summary_text.done"){let a=A.item_id,c=(Lt=A.text)!=null?Lt:"",P=(Mt=A.summary_index)!=null?Mt:0;if(a in e&&e[a].type==="reasoning"){for(;e[a].summary.length<=P;)e[a].summary.push({type:"summary_text",text:""});e[a].summary[P].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 P=(Ut=A.summary_index)!=null?Ut:0;P<e[a].summary.length&&(e[a].summary[P]={type:(Wt=c.type)!=null?Wt:"summary_text",text:(jt=c.text)!=null?jt:""})}continue}if(U==="response.function_call_arguments.delta"){let a=A.item_id,c=($t=A.delta)!=null?$t:"";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(P=>P.type==="message");if(c){let P={type:(Kt=a.type)!=null?Kt:"output_text",text:(Dt=a.text)!=null?Dt:"",annotations:(Ft=a.annotations)!=null?Ft:[]};c.content.push(P)}continue}if(U==="response.output_text.delta"){let a=(Bt=A.delta)!=null?Bt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let P=c.content[c.content.length-1];P&&P.type==="output_text"&&(P.text=`${P.text||""}${a}`);break}continue}if(U==="response.output_text.done"){let a=(zt=A.text)!=null?zt:"";for(let c of Object.values(e))if(c.type==="message"&&c.content&&c.content.length){let P=c.content[c.content.length-1];P&&P.type==="output_text"&&(P.text=a);break}continue}if(U==="response.output_item.done"){let a=A.item||{},c=a.id;c in e&&(e[c].status=(Vt=a.status)!=null?Vt:"completed",a.type==="reasoning"?e[c].summary=(Jt=a.summary)!=null?Jt:e[c].summary:a.type==="function_call"?(e[c].arguments=(Yt=a.arguments)!=null?Yt:e[c].arguments,e[c].call_id=(Ht=a.call_id)!=null?Ht:e[c].call_id,e[c].name=(Xt=a.name)!=null?Xt:e[c].name):a.type==="message"?(e[c].content=(Zt=a.content)!=null?Zt:e[c].content,e[c].role=(Qt=a.role)!=null?Qt:e[c].role):a.type==="image_generation_call"?(e[c].result=(vt=a.result)!=null?vt:e[c].result,e[c].revised_prompt=(te=a.revised_prompt)!=null?te:e[c].revised_prompt,e[c].background=(ee=a.background)!=null?ee:e[c].background,e[c].size=(ne=a.size)!=null?ne:e[c].size,e[c].quality=(oe=a.quality)!=null?oe:e[c].quality,e[c].output_format=(se=a.output_format)!=null?se:e[c].output_format):a.type==="code_interpreter_call"?(e[c].code=(re=a.code)!=null?re:e[c].code,e[c].container_id=(ae=a.container_id)!=null?ae:e[c].container_id):a.type==="mcp_list_tools"?(e[c].tools=(ie=a.tools)!=null?ie:e[c].tools,e[c].error=(le=a.error)!=null?le:e[c].error):a.type==="mcp_call"?(e[c].name=(ce=a.name)!=null?ce:e[c].name,e[c].arguments=(pe=a.arguments)!=null?pe:e[c].arguments,e[c].output=(ue=a.output)!=null?ue:e[c].output,e[c].error=(de=a.error)!=null?de:e[c].error,e[c].server_label=(_e=a.server_label)!=null?_e:e[c].server_label):a.type==="mcp_approval_request"?(e[c].name=(me=a.name)!=null?me:e[c].name,e[c].arguments=(fe=a.arguments)!=null?fe:e[c].arguments,e[c].server_label=(ge=a.server_label)!=null?ge:e[c].server_label):a.type==="shell_call"?(e[c].action=(ye=a.action)!=null?ye:e[c].action,e[c].call_id=(he=a.call_id)!=null?he:e[c].call_id):a.type==="shell_call_output"?(e[c].output=(be=a.output)!=null?be:e[c].output,e[c].call_id=(Re=a.call_id)!=null?Re:e[c].call_id):a.type==="apply_patch_call"?(e[c].operation=(xe=a.operation)!=null?xe:e[c].operation,e[c].call_id=(we=a.call_id)!=null?we:e[c].call_id):a.type==="apply_patch_call_output"?(e[c].output=(Te=a.output)!=null?Te:e[c].output,e[c].call_id=(Ee=a.call_id)!=null?Ee: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=(Oe=A.partial_image_b64)!=null?Oe:e[a].result,e[a].background=(Ae=A.background)!=null?Ae:e[a].background,e[a].size=(Pe=A.size)!=null?Pe:e[a].size,e[a].quality=(ke=A.quality)!=null?ke:e[a].quality,e[a].output_format=(Se=A.output_format)!=null?Se: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 P=(Ie=A.command_index)!=null?Ie:0;c.commands[P]=((Ne=c.commands[P])!=null?Ne:"")+((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]=(Le=A.command)!=null?Le:"",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=(Me=A.command_index)!=null?Me:0,P=(Ue=e[a].output[c])!=null?Ue:{stdout:"",stderr:""},ct=(We=A.delta)!=null?We:{};ct.stdout&&(P.stdout=((je=P.stdout)!=null?je:"")+ct.stdout),ct.stderr&&(P.stderr=(($e=P.stderr)!=null?$e:"")+ct.stderr),e[a].output[c]=P}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=((Ke=c.diff)!=null?Ke:"")+((De=A.delta)!=null?De:""),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=(Fe=A.diff)!=null?Fe:c.diff,e[a].operation=c}continue}if(U==="response.completed"){let a=A.response||{};n.status=(ze=(Be=a.status)!=null?Be:n.status)!=null?ze:"completed",n.usage=(Ve=a.usage)!=null?Ve:n.usage,n.output=(Je=a.output)!=null?Je:n.output,a.reasoning&&(n.reasoning=a.reasoning);continue}}return n},pn=t=>{var d,u,_,m,b,R,x,O,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 I=i.at(-1);if(!I||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}I.function.name=`${I.function.name}${((m=g.function)==null?void 0:m.name)||""}`,I.function.arguments=`${I.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:(O=l==null?void 0:l.logprobs)!=null?O: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},Xn=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},un=t=>{var m,b,R,x,O,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 I=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(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&&(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&&((O=_[r])!=null&&O.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},Zn=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},Zo=t=>{var l,d,u,_,m,b,R,x,O,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:(O=i==null?void 0:i.delta.refusal)!=null?O:null}}),e.id=o.id,e.model=o.model,e.created=o.created,e.usage=(T=o.usage)!=null?T:void 0,e},Qn=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},Qo=(t,n,e,o,r,i,l,d,u)=>{var R,x,O;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=(O=l==null?void 0:l.candidates)==null?void 0:O[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)),_},eo=t=>{var m,b,R,x,O,T,h;let{GenerateContentResponse:n}=Tt("@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:(O=f.executableCode.code)!=null?O:"",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 Qo(e,o,r,i,l,d,t[t.length-1],u,_)},vo=t=>eo(t),ts=t=>eo(t),es=["size","quality","background","output_format"],dn=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 es)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},no=(t,n="openai.chat.completions.create")=>{if(n==="openai.responses.create"||n==="openai.AzureOpenAI.responses.create")return ve(t);if(n==="openai.images.generate"||n==="openai.AzureOpenAI.images.generate")return dn(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 un(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=pn(t);return e.choices[0]=E(E({},e.choices[0]),e.choices[0].message),e}return""},vn=(t,n,e)=>{let o=n.model.provider,r=n.model.name;if(o==="anthropic"||o==="anthropic.bedrock"||o==="vertexai"&&r.startsWith("claude"))return zn(t,n,e==null?void 0:e.anthropicBlockTypeByIndex);if(o==="google"||o==="vertexai"&&r.startsWith("gemini"))return Vn(t,n);if(o==="amazon.bedrock")return Yn(t,n);if(o==="mistral")return cn(t.data,n);if(o==="openai"||o==="openai.azure"){let i=n.model.api_type||"chat-completions";return i==="responses"?Jn(t,n):i==="images"?Hn(t,n):cn(t,n)}return null};function oo(t,n,e,o){return Ze(this,null,function*(){var R,x,O;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"&&((O=(x=(R=o.model)==null?void 0:R.name)==null?void 0:x.startsWith)==null?void 0:O.call(x,"claude")),_={};try{for(var T=Qe(t),h,w,f;h=!(w=yield new _t(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=vn(g,o,{anthropicBlockTypeByIndex:_}),yield r}}catch(w){f=[w]}finally{try{h&&(w=T.return)&&(yield new _t(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=vn(m,o),yield r;let b=yield new _t(n({request_response:m}));r.request_id=b.request_id,r.prompt_blueprint=b.prompt_blueprint,yield r})}var so={"openai:chat-completions":{chat:{function_name:"openai.chat.completions.create",stream_function:pn},completion:{function_name:"openai.completions.create",stream_function:Xn}},"openai:responses":{chat:{function_name:"openai.responses.create",stream_function:ve}},"openai:images":{completion:{function_name:"openai.images.generate",stream_function:dn}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:un},completion:{function_name:"anthropic.completions.create",stream_function:Zn}},"openai.azure:chat-completions":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:pn},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:Xn}},"openai.azure:responses":{chat:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ve},completion:{function_name:"openai.AzureOpenAI.responses.create",stream_function:ve}},"openai.azure:images":{completion:{function_name:"openai.AzureOpenAI.images.generate",stream_function:dn}},google:{chat:{function_name:"google.convo.send_message",stream_function:vo},completion:{function_name:"google.model.generate_content",stream_function:ts}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:Qn},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:Qn}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:un},completion:{function_name:"anthropic.completions.create",stream_function:Zn}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:Zo},completion:{function_name:"",stream_function:null}}};var ao="1.0.61",rs=()=>{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"},as=rs(),is=`promptlayer-js/${ao} (node ${as})`,Q=()=>({"User-Agent":is,"X-SDK-Version":ao}),_n="SET_WORKFLOW_COMPLETE";function ls(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 io(t,n,e,o,r){return function(i){return S(this,null,function*(){if(i.name===_n)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 ls(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 cs(d){return S(this,arguments,function*({token:t,channelName:n,executionId:e,returnAllOutputs:o,headers:r,timeout:i,baseURL:l}){let u=new ns.Realtime(t),_=u.channels.get(n),m={},b=new Promise((x,O)=>{m.resolve=x,m.reject=O}),R=io(l,m,e,o,r);yield _.subscribe(_n,R);try{return yield new Promise((x,O)=>{let T=setTimeout(()=>{O(new Error("Workflow execution did not complete properly (timeout)"))},i);b.then(h=>{clearTimeout(T),x(h)}).catch(h=>{clearTimeout(T),O(h)})})}finally{console.log("Closing client"),_.unsubscribe(_n,R),u.close(),console.log("Closed client")}})}var H=(t,n)=>S(null,null,function*(){return ss(()=>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.`)}})}),lo=(t,n,e,o=!0)=>S(null,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?us(t,n,e.request_response,e,o):yield co(t,n,e,o)}),co=(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);ut(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}),po=(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 ut(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}),uo=(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 ut(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}),_o=(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 ut(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}),mo=(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 ut(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}),fo=(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 ut(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}}),go=(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}}),yo=(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);ut(i,"WARNING: While publishing a prompt template PromptLayer had the following error")}return i}),ho=(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 ut(l,"WARNING: While fetching all prompt templates PromptLayer had the following error"),[]}return(d=l.items)!=null?d:[]}),ps=t=>S(null,null,function*(){let n=new URL(`${t.baseURL}/connection/websocket`);n.protocol=n.protocol==="https:"?"wss:":"ws:";let e=new os(n.toString(),{token:t.token}),o=e.newSubscription(t.channelName);return new Promise((r,i)=>{let l=m=>{_(),r(m)},d=io(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()})}),bo=_=>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 O=x.workflow_version_execution_id;if(!O)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let T=`workflow_updates:${O}`,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:O,returnAllOutputs:i,headers:b,timeout:d,baseURL:u};return w.messaging_backend==="centrifugo"?ps(g):yield cs(g)}catch(R){throw console.error(`Failed to run workflow: ${R instanceof Error?R.message:R}`),R}});function us(t,n,e,o,r=!0){return Ze(this,null,function*(){let i=[];try{for(var u=Qe(e),_,m,b;_=!(m=yield new _t(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 _t(m.call(u)))}finally{if(b)throw b[0]}}let l=no(i,o.function_name),d=yield new _t(co(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 ut=(t,n)=>{try{console.warn(`${n}: ${t.message}`)}catch(e){console.warn(`${n}: ${t}`)}},Ro=(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);ut(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{}}),ds=(t,n)=>S(null,null,function*(){return yield t.chat.completions.create(n)}),_s=(t,n)=>S(null,null,function*(){return yield t.completions.create(n)}),xo={chat:ds,completion:_s},wo=(t,n)=>S(null,null,function*(){var i,l;let e=Tt("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=xo[t.prompt_template.type];return yield d(o,n)}else return r==="images"?yield o.images.generate(n):yield o.responses.create(n)}),To=(t,n)=>S(null,null,function*(){var i,l;let{AzureOpenAI:e}=Tt("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=xo[t.prompt_template.type];return yield d(o,n)}else return r==="images"?yield o.images.generate(n):yield o.responses.create(n)}),Eo=(t,n)=>S(null,null,function*(){return t.messages.create(n)}),ms=(t,n)=>S(null,null,function*(){return t.completions.create(n)}),Oo={chat:Eo,completion:ms},Ao=(t,n)=>S(null,null,function*(){let e=Tt("@anthropic-ai/sdk").default,o=new e({baseURL:n.baseURL,apiKey:n.apiKey}),r=Oo[t.prompt_template.type];return r(o,n)}),Po=(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 ut(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}}),fs=(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})}),gs=(t,o)=>S(null,null,function*(){var r=o,{stream:n}=r,e=Xe(r,["stream"]);return n?yield t.generateContentStream(E({},e)):yield t.generateContent(E({},e))}),ys={chat:fs,completion:gs},mn=(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=ys[t.prompt_template.type];return yield u(d,n)}),ro=t=>t.replace(/_([a-z])/g,(n,e)=>e.toUpperCase()),tn=(t,n=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(e=>tn(e,n)):Object.fromEntries(Object.entries(t).map(([e,o])=>n.has(e)?[ro(e),o]:[ro(e),tn(o,n)])),ko=(t,n,e={},o=!1)=>{var u,_,m,b,R,x,O,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)&&((O=(x=t.metadata)==null?void 0:x.model)!=null&&O.name.startsWith("gemini"))&&(l=tn(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&&to.includes(r)&&i==="chat-completions"&&(l.stream_options={include_usage:!0}),{provider_type:r,kwargs:l}},So=(t,n)=>{let e=so[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},Co=(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 mn(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 Eo(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`)}),Io=(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)}}),No=(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=Oo[t.prompt_template.type];return r(o,n)}),qo=(t,n)=>S(null,null,function*(){let{Mistral:e}=yield import("@mistralai/mistralai"),o=new e({apiKey:process.env.MISTRAL_API_KEY});return n=tn(n,new Set),n!=null&&n.stream?(delete n.stream,yield o.chat.stream(n)):(delete n.stream,yield o.chat.complete(n))}),fn=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 en=class{constructor(n,e,o=!0){this.create=()=>fo(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=n,this.baseURL=e,this.throwOnError=o}};import{SpanKind as Ye,SpanStatusCode as gn}from"@opentelemetry/api";import{ExportResultCode as nn}from"@opentelemetry/core";var yn=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{[Ye.INTERNAL]:"SpanKind.INTERNAL",[Ye.SERVER]:"SpanKind.SERVER",[Ye.CLIENT]:"SpanKind.CLIENT",[Ye.PRODUCER]:"SpanKind.PRODUCER",[Ye.CONSUMER]:"SpanKind.CONSUMER"}[n]||"SpanKind.INTERNAL"}statusCodeToString(n){return{[gn.ERROR]:"StatusCode.ERROR",[gn.OK]:"StatusCode.OK",[gn.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(nn.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?nn.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
-
HTTP error! status: ${
|
|
1
|
+
import{A as wt,B as Et,C as yt,D as bt,E as $,a as P,b as F,c as Q,d as R,e as X,g as Z,h as tt,i as et,j as rt,k as ot,l as nt,m as st,n as it,o as at,p as ut,q as pt,r as ct,s as mt,t as lt,u as ht,v as ft,w as dt,x as Rt,y as gt,z as _t}from"./chunk-SWBNW72U.js";var C=class{constructor(t,r,e=!0){this.create=()=>it(this.apiKey,this.baseURL,this.throwOnError);this.apiKey=t,this.baseURL=r,this.throwOnError=e}};import{SpanKind as k,SpanStatusCode as G}from"@opentelemetry/api";import{ExportResultCode as N}from"@opentelemetry/core";var J=class{constructor(t,r,e){this.apiKey=r,this.baseURL=e,this.enableTracing=t,this.url=`${this.baseURL}/spans-bulk`}attributesToObject(t){return t?Object.fromEntries(Object.entries(t)):{}}spanKindToString(t){return{[k.INTERNAL]:"SpanKind.INTERNAL",[k.SERVER]:"SpanKind.SERVER",[k.CLIENT]:"SpanKind.CLIENT",[k.PRODUCER]:"SpanKind.PRODUCER",[k.CONSUMER]:"SpanKind.CONSUMER"}[t]||"SpanKind.INTERNAL"}statusCodeToString(t){return{[G.ERROR]:"StatusCode.ERROR",[G.OK]:"StatusCode.OK",[G.UNSET]:"StatusCode.UNSET"}[t]||"StatusCode.UNSET"}toNanoseconds(t){return(BigInt(t[0])*BigInt(1e9)+BigInt(t[1])).toString()}export(t){if(!this.enableTracing)return Promise.resolve(N.SUCCESS);let r=t.map(e=>{var i;return{name:e.name,context:{trace_id:e.spanContext().traceId,span_id:e.spanContext().spanId,trace_state:((i=e.spanContext().traceState)==null?void 0:i.serialize())||""},kind:this.spanKindToString(e.kind),parent_id:e.parentSpanId||null,start_time:this.toNanoseconds(e.startTime),end_time:this.toNanoseconds(e.endTime),status:{status_code:this.statusCodeToString(e.status.code),description:e.status.message},attributes:this.attributesToObject(e.attributes),events:e.events.map(a=>({name:a.name,timestamp:this.toNanoseconds(a.time),attributes:this.attributesToObject(a.attributes)})),links:e.links.map(a=>({context:a.context,attributes:this.attributesToObject(a.attributes)})),resource:{attributes:F(P({},e.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return tt(this.url,{method:"POST",headers:P({"Content-Type":"application/json","X-API-KEY":this.apiKey||""},Z()),body:JSON.stringify({spans:r})}).then(e=>e.ok?N.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
+
HTTP error! status: ${e.status}`),N.FAILED)).catch(e=>(console.error("Error exporting spans:",e),N.FAILED))}shutdown(){return Promise.resolve()}},Ot=J;import*as St from"@opentelemetry/api";import{SimpleSpanProcessor as At}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Ct}from"@opentelemetry/sdk-trace-node";var b=(o="promptlayer-tracer")=>St.trace.getTracer(o),Tt=(o,t,r)=>{let e=new Ct,i=new Ot(o,t,r),a=new At(i);e.addSpanProcessor(a),e.register()};var Nt=b(),B=(o,t,r,e="",i="openai")=>{let a={construct:(s,u)=>{let n=Reflect.construct(s,u);return Object.defineProperties(n,{function_name:{value:e,writable:!0},provider:{value:i}}),new Proxy(n,a)},get:(s,u,n)=>{let l=s[u],d=`${Reflect.get(s,"function_name")}.${u.toString()}`;return typeof l=="object"?(Object.defineProperties(l,{function_name:{value:d,writable:!0},provider:{value:i}}),new Proxy(l,a)):typeof l=="function"?(...h)=>{var S,m,I,T,w,L;let O=new Date().toISOString(),M=Reflect.get(s,"provider"),g=(S=h[0])==null?void 0:S.return_pl_id,_=(m=h[0])==null?void 0:m.pl_tags,D=(I=h[0])==null?void 0:I.pl_warn_on_error;return(T=h[0])==null||delete T.return_pl_id,(w=h[0])==null||delete w.pl_tags,(L=h[0])==null||delete L.pl_warn_on_error,Nt.startActiveSpan(`${M}.${d}`,p=>R(null,null,function*(){try{p.setAttribute("function_input",JSON.stringify(h));let c=Reflect.apply(l,s,h),U=p.spanContext().spanId;return c instanceof Promise?new Promise((E,j)=>{c.then(y=>R(null,null,function*(){let v=yield et(o,t,{api_key:o,provider_type:M,function_name:d,request_start_time:O,request_end_time:new Date().toISOString(),request_response:y,kwargs:h[0],return_pl_id:g,tags:_,span_id:U},!D);p.setAttribute("function_output",JSON.stringify(v)),p.setAttribute("response_status","success"),p.end(),E(v)})).catch(y=>{p.recordException(y),p.setAttribute("response_status","error"),p.end(),j(y)})}):(p.setAttribute("function_output",JSON.stringify(c)),p.setAttribute("response_status","success"),p.end(),c)}catch(c){throw p.recordException(c),p.setAttribute("response_status","error"),p.end(),c}}))}:Reflect.get(s,u,n)}};return new Proxy(r,a)};import*as K from"@opentelemetry/api";var kt=(o,t,r)=>function(...e){let i=b(),a=s=>{try{r&&Object.entries(r).forEach(([n,l])=>{s.setAttribute(n,l)}),s.setAttribute("function_input",JSON.stringify(e));let u=t(...e);return u instanceof Promise?u.then(n=>(s.setAttribute("function_output",JSON.stringify(n)),s.setStatus({code:K.SpanStatusCode.OK}),n)).catch(n=>{throw Pt(s,n,e),n}).finally(()=>s.end()):(s.setAttribute("function_output",JSON.stringify(u)),s.setStatus({code:K.SpanStatusCode.OK}),s.end(),u)}catch(u){throw Pt(s,u,e),u}};return i.startActiveSpan(o,a)},Pt=(o,t,r)=>{o.setAttribute("function_input",JSON.stringify(r)),o.setStatus({code:K.SpanStatusCode.ERROR,message:t instanceof Error?t.message:"Unknown error"}),o.end()};var x=class{constructor(t,r,e=!0){this.get=(t,r)=>at(this.apiKey,this.baseURL,t,r,this.throwOnError);this.publish=t=>ut(this.apiKey,this.baseURL,t,this.throwOnError);this.all=t=>pt(this.apiKey,this.baseURL,t,this.throwOnError);this.apiKey=t,this.baseURL=r,this.throwOnError=e}};var Kt=(o,t,r,e=!0)=>{if(!(r.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[i,a]of Object.entries(r.metadata))if(typeof i!="string"||typeof a!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return rt(o,t,r,e)},xt=(o,t,r,e=!0)=>{if(typeof r.score!="number")throw new Error("Score must be a number");if(r.score<0||r.score>100)throw new Error("Score must be a number between 0 and 100.");return ot(o,t,r,e)},qt=(o,t,r,e=!0)=>{if(!(r.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return nt(o,t,r,e)},Mt=(o,t,r,e=!0)=>st(o,t,r,e),q=class{constructor(t,r,e=!0){this.group=t=>Mt(this.apiKey,this.baseURL,t,this.throwOnError);this.metadata=t=>Kt(this.apiKey,this.baseURL,t,this.throwOnError);this.prompt=t=>qt(this.apiKey,this.baseURL,t,this.throwOnError);this.score=t=>xt(this.apiKey,this.baseURL,t,this.throwOnError);this.apiKey=t,this.baseURL=r,this.throwOnError=e}};function Dt(o){if(o&&typeof o=="object"&&"status"in o&&typeof o.status=="number")return o.status}function jt(o){return o&&typeof o=="object"&&o.constructor?o.constructor.name:""}function It(o){let t=Dt(o),r=jt(o),e=o instanceof Error?o.message.toLowerCase():String(o).toLowerCase();return t===429||/ratelimit/i.test(r)?"PROVIDER_RATE_LIMIT":/timeout/i.test(r)?"PROVIDER_TIMEOUT":t===401||/authentication/i.test(r)?"PROVIDER_AUTH_ERROR":e.includes("quota")?"PROVIDER_QUOTA_LIMIT":e.includes("timeout")||e.includes("timed out")?"PROVIDER_TIMEOUT":t!==void 0?"PROVIDER_ERROR":"UNKNOWN_ERROR"}import*as Ut from"@opentelemetry/api";var Wt={openai:lt,anthropic:ft,"openai.azure":ht,google:Rt,vertexai:wt,"amazon.bedrock":Et,"anthropic.bedrock":yt,mistral:bt},Vt=o=>{if(!o||typeof o!="object"||Array.isArray(o))return!1;let t=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(o).every(e=>typeof e!="object"||e===null?!1:t.every(i=>i in e))},Lt=class{constructor({apiKey:t=$("PROMPTLAYER_API_KEY"),baseURL:r=$("PROMPTLAYER_BASE_URL"),enableTracing:e=!1,throwOnError:i=!0}={}){if(t===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=t,this.baseURL=r||"https://api.promptlayer.com",this.enableTracing=e,this.throwOnError=i,this.templates=new x(t,this.baseURL,this.throwOnError),this.group=new C(t,this.baseURL,this.throwOnError),this.track=new q(t,this.baseURL,this.throwOnError),this.wrapWithSpan=kt,e&&Tt(e,t,this.baseURL)}get Anthropic(){try{let t=Q("@anthropic-ai/sdk").default;return B(this.apiKey,this.baseURL,t,"anthropic","anthropic")}catch(t){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let t=Q("openai").default;return B(this.apiKey,this.baseURL,t,"openai","openai")}catch(t){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(O){return R(this,arguments,function*({promptName:t,promptVersion:r,promptReleaseLabel:e,inputVariables:i,tags:a,metadata:s,groupId:u,modelParameterOverrides:n,stream:l=!1,provider:d,model:h}){return b().startActiveSpan("PromptLayer Run",g=>R(this,null,function*(){try{let _={promptName:t,promptVersion:r,promptReleaseLabel:e,inputVariables:i,tags:a,metadata:s,groupId:u,modelParameterOverrides:n,stream:l};g.setAttribute("function_input",JSON.stringify(_));let D=i,S={label:e,version:r,metadata_filters:s,provider:d,model:h,model_parameter_overrides:n};i&&(S.input_variables=i);let m=yield this.templates.get(t,S);if(!m)throw new Error(`Cannot proceed: prompt template '${t}' could not be fetched. Check the warnings above for the actual error.`);let I=m.prompt_template;if(!m.llm_kwargs){let f=`Prompt '${t}' 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(f);console.warn(`WARNING: ${f}`)}let T=m.metadata;if(!T)throw new Error(`Prompt '${t}' does not have any metadata associated with it.`);let w=T.model;if(!w)throw new Error(`Prompt '${t}' does not have a model parameters associated with it.`);let L=m.custom_provider,p=new Date().toISOString(),{provider_type:c,kwargs:U}=gt(m,L,n,l),E=c;if(c==="openai"||c==="openai.azure"){let f=w.api_type;E=`${c}:${f}`}w.name.startsWith("gemini")?E="google":w.name.startsWith("claude")&&(E="anthropic");let j=_t(E,I),{function_name:y,stream_function:v}=j,z=Wt[c];if(!z)throw new Error(`No request function found for provider: ${c}`);let W=f=>{let V=new Date().toISOString();return mt(this.baseURL,P({function_name:y,provider_type:c,args:[],kwargs:U,tags:a,request_start_time:p,request_end_time:V,api_key:this.apiKey,metadata:s,prompt_id:m.id,prompt_version:m.version,prompt_input_variables:D,group_id:u,return_prompt_blueprint:!0,span_id:g.spanContext().spanId},f),this.throwOnError)},A;try{A=yield z(m,U)}catch(f){let V=It(f),vt=f instanceof Error?f.message:String(f);throw yield W({request_response:{},status:"ERROR",error_type:V,error_message:vt}),f}if(l)return X(A,W,v,s||m.metadata);let H=yield W({request_response:A}),Y={request_id:H.request_id,raw_response:A,prompt_blueprint:H.prompt_blueprint};return g.setAttribute("function_output",JSON.stringify(Y)),Y}catch(_){throw g.setStatus({code:Ut.SpanStatusCode.ERROR,message:_ instanceof Error?_.message:"Unknown error"}),_}finally{g.end()}}))})}runWorkflow(u){return R(this,arguments,function*({workflowName:t,inputVariables:r={},metadata:e={},workflowLabelName:i=null,workflowVersion:a=null,returnAllOutputs:s=!1}){try{let n=yield ct({workflow_name:t,input_variables:r,metadata:e,workflow_label_name:i,workflow_version_number:a,return_all_outputs:s,api_key:this.apiKey,baseURL:this.baseURL});if(!s&&Vt(n)){let d=Object.values(n).filter(O=>O.is_output_node===!0);if(d.length===0)throw new Error(JSON.stringify(n,null,2));if(!d.some(O=>O.status==="SUCCESS"))throw new Error(JSON.stringify(n,null,2))}return n}catch(n){throw n instanceof Error?(console.error("Error running workflow:",n.message),new Error(`Error running workflow: ${n.message}`)):(console.error("Unknown error running workflow:",n),new Error("Unknown error running workflow"))}})}logRequest(t){return R(this,null,function*(){return dt(this.apiKey,this.baseURL,t,this.throwOnError)})}};export{Lt as PromptLayer};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|