promptlayer 1.0.44 → 1.0.46
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/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
- package/src/index.ts +3 -1
- package/src/types.ts +2 -0
- package/src/utils/blueprint-builder.ts +57 -0
- package/src/utils/utils.ts +151 -1
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var nt=Object.defineProperty,ot=Object.defineProperties;var rt=Object.getOwnPropertyDescriptors;var L=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable;var pe=(n,e)=>{if(e=Symbol[n])return e;throw Error("Symbol."+n+" is not defined")};var le=(n,e,t)=>e in n?nt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,_=(n,e)=>{for(var t in e||(e={}))ue.call(e,t)&&le(n,t,e[t]);if(L)for(var t of L(e))me.call(e,t)&&le(n,t,e[t]);return n},S=(n,e)=>ot(n,rt(e));var I=(n=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(n,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):n)(function(n){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var v=(n,e)=>{var t={};for(var o in n)ue.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&L)for(var o of L(n))e.indexOf(o)<0&&me.call(n,o)&&(t[o]=n[o]);return t};var m=(n,e,t)=>new Promise((o,r)=>{var s=c=>{try{i(t.next(c))}catch(p){r(p)}},a=c=>{try{i(t.throw(c))}catch(p){r(p)}},i=c=>c.done?o(c.value):Promise.resolve(c.value).then(s,a);i((t=t.apply(n,e)).next())}),E=function(n,e){this[0]=n,this[1]=e},B=(n,e,t)=>{var o=(a,i,c,p)=>{try{var u=t[a](i),d=(i=u.value)instanceof E,l=u.done;Promise.resolve(d?i[0]:i).then(h=>d?o(a==="return"?a:"next",i[1]?{done:h.done,value:h.value}:h,c,p):c({value:h,done:l})).catch(h=>o("throw",h,c,p))}catch(h){p(h)}},r=a=>s[a]=i=>new Promise((c,p)=>o(a,i,c,p)),s={};return t=t.apply(n,e),s[Symbol.asyncIterator]=()=>s,r("next"),r("throw"),r("return"),s};var V=(n,e,t)=>(e=n[pe("asyncIterator")])?e.call(n):(n=n[pe("iterator")](),e={},t=(o,r)=>(r=n[o])&&(e[o]=s=>new Promise((a,i,c)=>(s=r.call(n,s),c=s.done,Promise.resolve(s.value).then(p=>a({value:p,done:c}),i)))),t("next"),t("return"),e);import st from"ably";var $=(n,e,t)=>({id:n,function:{name:e,input:t}}),C=t=>{var o=t,{type:n}=o,e=v(o,["type"]);return _({type:n},e)},X=(n,e)=>({input_variables:[],template_format:"f-string",content:n,role:"assistant",function_call:null,name:null,tool_calls:e}),z=(n,e)=>({prompt_template:{messages:[n],type:"chat",input_variables:[]},metadata:e}),fe=(n,e)=>{let t=[],o=[];n.type==="content_block_start"?n.content_block.type==="thinking"?t.push(C({type:"thinking",thinking:"",signature:""})):n.content_block.type==="text"?t.push(C({type:"text",text:""})):n.content_block.type==="tool_use"&&o.push($(n.content_block.id||"",n.content_block.name||"",{})):n.type==="content_block_delta"&&(n.delta.type==="thinking_delta"?t.push(C({type:"thinking",thinking:n.delta.thinking||"",signature:""})):n.delta.type==="text_delta"?t.push(C({type:"text",text:n.delta.text||""})):n.delta.type==="signature_delta"?t.push(C({type:"thinking",thinking:"",signature:n.delta.signature||""})):n.delta.type==="input_json_delta"&&o.push($("","",n.delta.partial_json)));let r=X(t,o);return z(r,e)},de=(n,e)=>{let t=[],o=[];for(let s of n.candidates)if(s.content&&s.content.parts&&Array.isArray(s.content.parts))for(let a of s.content.parts)a.text?a.thought===!0?t.push(C({type:"thinking",thinking:a.text,signature:a.thoughtSignature||""})):t.push(C({type:"text",text:a.text})):a.functionCall&&o.push($(a.functionCall.id||"",a.functionCall.name||"",a.functionCall.args||{}));let r=X(t,o);return z(r,e)},H=(n,e)=>{let t=[],o=[];for(let s of n.choices)if(s.delta){s.delta.content&&t.push(C({type:"text",text:s.delta.content}));let a=s.delta.tool_calls||s.delta.toolCalls;if(a&&Array.isArray(a))for(let i of a)i.function&&o.push($(i.id||"",i.function.name||"",i.function.arguments||""))}let r=X(t,o);return z(r,e)};var Z="SET_WORKFLOW_COMPLETE";function at(n,e,t){return m(this,null,function*(){let o=yield fetch(`${R}/workflow-version-execution-results?workflow_version_execution_id=${n}&return_all_outputs=${e}`,{headers:t});if(!o.ok)throw new Error("Failed to fetch final output");return o.json()})}function it(n,e,t,o){return function(r){return m(this,null,function*(){if(r.name===Z)try{let s=JSON.parse(r.data),a=s.result_code,i;if(a==="OK"||a==null)i=s.final_output;else if(a==="EXCEEDS_SIZE_LIMIT")i=yield at(e,t,o);else throw new Error(`Unsupported final output code: ${a}`);n.resolve(i)}catch(s){n.reject(s)}})}}function ct(a){return m(this,arguments,function*({token:n,channelName:e,executionId:t,returnAllOutputs:o,headers:r,timeout:s}){let i=new st.Realtime(n),c=i.channels.get(e),p={},u=new Promise((l,h)=>{p.resolve=l,p.reject=h}),d=it(p,t,o,r);yield c.subscribe(Z,d);try{return yield new Promise((l,h)=>{let w=setTimeout(()=>{h(new Error("Workflow execution did not complete properly (timeout)"))},s);u.then(g=>{clearTimeout(w),l(g)}).catch(g=>{clearTimeout(w),h(g)})})}finally{console.log("Closing client"),c.unsubscribe(Z,d),i.close(),console.log("Closed client")}})}var R=process.env.PROMPTLAYER_API_URL||"https://api.promptlayer.com",ge=(n,e)=>m(void 0,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?lt(n,e.request_response,e):yield we(n,e)}),we=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),o=yield t.json();if(t.status!==200&&A(o,"WARNING: While logging your request, PromptLayer experienced the following error:"),o&&e.return_pl_id)return[e.request_response,o.request_id]}catch(t){console.warn(`WARNING: While logging your request PromptLayer had the following error: ${t}`)}return e.request_response}),Pe=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/library-track-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S(_({},e),{api_key:n}))}),o=yield t.json();if(t.status!==200)return A(o,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}catch(t){return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${t}`),!1}return!0}),Re=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/library-track-score`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S(_({},e),{api_key:n}))}),o=yield t.json();if(t.status!==200)return A(o,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}catch(t){return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${t}`),!1}return!0}),Te=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/library-track-prompt`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S(_({},e),{api_key:n}))}),o=yield t.json();if(t.status!==200)return A(o,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}catch(t){return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${t}`),!1}return!0}),be=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/track-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S(_({},e),{api_key:n}))}),o=yield t.json();if(t.status!==200)return A(o,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}catch(t){return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${t}`),!1}return!0}),Se=n=>m(void 0,null,function*(){try{let e=yield fetch(`${R}/create-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n})}),t=yield e.json();return e.status!==200?(A(t,"WARNING: While creating a group PromptLayer had the following error"),!1):t.id}catch(e){return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${e}`),!1}}),Ae=(n,e,t)=>m(void 0,null,function*(){try{let o=new URL(`${R}/prompt-templates/${e}`),r=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":n},body:JSON.stringify(t)}),s=yield r.json();return r.status!==200?(A(s,"WARNING: While fetching a prompt template PromptLayer had the following error"),null):(s.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${s.warning}`),s)}catch(o){return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${o}`),null}}),Oe=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/rest/prompt-templates`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":n},body:JSON.stringify({prompt_template:_({},e),prompt_version:_({},e),release_labels:e.release_labels?e.release_labels:void 0})}),o=yield t.json();return t.status===400&&A(o,"WARNING: While publishing a prompt template PromptLayer had the following error"),o}catch(t){console.warn(`WARNING: While publishing a prompt template PromptLayer had the following error: ${t}`)}}),Ee=(n,e)=>m(void 0,null,function*(){var t;try{let o=new URL(`${R}/prompt-templates`);Object.entries(e||{}).forEach(([a,i])=>o.searchParams.append(a,i.toString()));let r=yield fetch(o,{headers:{"Content-Type":"application/json","X-API-KEY":n}}),s=yield r.json();return r.status!==200?(A(s,"WARNING: While fetching all prompt templates PromptLayer had the following error"),null):(t=s.items)!=null?t:[]}catch(o){return console.warn(`WARNING: While fetching all prompt templates PromptLayer had the following error: ${o}`),null}}),Ce=c=>m(void 0,[c],function*({workflow_name:n,input_variables:e,metadata:t={},workflow_label_name:o=null,workflow_version_number:r=null,return_all_outputs:s=!1,api_key:a,timeout:i=36e5}){let p={input_variables:e,metadata:t,workflow_label_name:o,workflow_version_number:r,return_all_outputs:s},u={"X-API-KEY":a,"Content-Type":"application/json"};try{let d=yield fetch(`${R}/workflows/${encodeURIComponent(n)}/run`,{method:"POST",headers:u,body:JSON.stringify(p)});if(d.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield d.json().catch(()=>({}))).error||d.statusText}`};let l=yield d.json();l.warning&&console.warn(`WARNING: ${l.warning}`);let h=l.workflow_version_execution_id;if(!h)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let w=`workflow_updates:${h}`,T=(yield(yield fetch(`${R}/ws-token-request-library?capability=${w}`,{method:"POST",headers:u})).json()).token_details.token;return yield ct({token:T,channelName:w,executionId:h,returnAllOutputs:s,headers:u,timeout:i})}catch(d){throw console.error(`Failed to run workflow: ${d instanceof Error?d.message:d}`),d}}),Q=n=>{var i,c,p,u,d,l,h,w,g,b;let e=null,t,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=n.at(-1);if(!r)return o;let s;for(let T of n){if(T.choices.length===0)continue;let y=T.choices[0].delta;y.content&&(e=`${e||""}${y.content||""}`),y.function_call&&(t={name:`${t?t.name:""}${y.function_call.name||""}`,arguments:`${t?t.arguments:""}${y.function_call.arguments||""}`});let f=(i=y.tool_calls)==null?void 0:i[0];if(f){s=s||[];let P=s.at(-1);if(!P||f.id){s.push({id:f.id||"",type:f.type||"function",function:{name:((c=f.function)==null?void 0:c.name)||"",arguments:((p=f.function)==null?void 0:p.arguments)||""}});continue}P.function.name=`${P.function.name}${((u=f.function)==null?void 0:u.name)||""}`,P.function.arguments=`${P.function.arguments}${((d=f.function)==null?void 0:d.arguments)||""}`}}let a=n[0].choices.at(0);return o.choices.push({finish_reason:(l=a==null?void 0:a.finish_reason)!=null?l:"stop",index:(h=a==null?void 0:a.index)!=null?h:0,logprobs:(w=a==null?void 0:a.logprobs)!=null?w:null,message:{role:"assistant",content:e,function_call:t||void 0,tool_calls:s||void 0,refusal:(g=a==null?void 0:a.delta.refusal)!=null?g:null}}),o.id=r.id,o.model=r.model,o.created=r.created,o.system_fingerprint=r.system_fingerprint,o.usage=(b=r.usage)!=null?b:void 0,o},ee=n=>{var c;let e={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(!n.at(-1))return e;let o=null,r="",s="",a="",i="";for(let p of n)if(p.type==="message_start")e=_({},p.message);else if(p.type==="content_block_start")o=_({},p.content_block),o.type==="thinking"?(r="",s=""):o.type==="text"?a="":(o.type==="tool_use"||o.type==="server_tool_use")&&(i="");else if(p.type==="content_block_delta"&&o!==null){if(o.type==="thinking")"signature"in p.delta&&(r=p.delta.signature||""),"thinking"in p.delta&&(s+=p.delta.thinking||"");else if(o.type==="text")"text"in p.delta&&(a+=p.delta.text||"");else if((o.type==="tool_use"||o.type==="server_tool_use")&&p.delta.type==="input_json_delta"){let u=p.delta;i+=u.partial_json||""}}else if(p.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=r,o.thinking=s;else if(o.type==="text")o.text=a,o.citations=null;else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=i?JSON.parse(i):{}}catch(u){o.input={}}e.content.push(o),o=null,r="",s="",a="",i=""}else p.type==="message_delta"&&("usage"in p&&p.usage&&(e.usage=S(_({},e.usage),{output_tokens:(c=p.usage.output_tokens)!=null?c:0})),"delta"in p&&p.delta&&("stop_reason"in p.delta&&p.delta.stop_reason!==void 0&&(e.stop_reason=p.delta.stop_reason),"stop_sequence"in p.delta&&p.delta.stop_sequence!==void 0&&(e.stop_sequence=p.delta.stop_sequence)));return e},pt=(n,e="openai.chat.completions.create")=>{if("completion"in n[0])return n.reduce((t,o)=>S(_({},o),{completion:`${t.completion}${o.completion}`}),{});if(e==="anthropic.messages.create")return ee(n);if("text"in n[0].choices[0]){let t="";for(let r of n)t=`${t}${r.choices[0].text}`;let o=structuredClone(n.at(-1));return o.choices[0].text=t,o}if("delta"in n[0].choices[0]){let t=Q(n);return t.choices[0]=_(_({},t.choices[0]),t.choices[0].message),t}return""};function lt(n,e,t){return B(this,null,function*(){let o=[];try{for(var a=V(e),i,c,p;i=!(c=yield new E(a.next())).done;i=!1){let u=c.value;yield t.return_pl_id?[u,null]:u,o.push(u)}}catch(c){p=[c]}finally{try{i&&(c=a.return)&&(yield new E(c.call(a)))}finally{if(p)throw p[0]}}let r=pt(o,t.function_name),s=yield new E(we(n,S(_({},t),{request_response:r,request_end_time:new Date().toISOString()})));if(s&&t.return_pl_id){let u=s[1];yield[o.at(-1),u]}})}var A=(n,e)=>{try{console.warn(`${e}: ${n.message}`)}catch(t){console.warn(`${e}: ${n}`)}},Ie=n=>m(void 0,null,function*(){try{let e=yield fetch(`${R}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),t=yield e.json();return e.status!==200&&A(t,"WARNING: While logging your request, PromptLayer experienced the following error:"),t}catch(e){console.warn(`WARNING: While logging your request PromptLayer had the following error: ${e}`)}return{}}),he=n=>{let e={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},t=n.at(-1);if(!t)return e;let o="";for(let r of n)r.choices.length>0&&r.choices[0].text&&(o=`${o}${r.choices[0].text}`);return e.choices[0].text=o,e.id=t.id,e.created=t.created,e.model=t.model,e.system_fingerprint=t.system_fingerprint,e.usage=t.usage,e},ye=n=>{let e={completion:"",id:"",model:"",stop_reason:"",type:"completion"},t=n.at(-1);if(!t)return e;let o="";for(let r of n)o=`${o}${r.completion}`;return e.completion=o,e.id=t.id,e.model=t.model,e.stop_reason=t.stop_reason,e},ut=n=>{var a,i,c,p,u,d,l,h,w,g;let e=null,t={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=n.at(-1).data;if(!o)return t;let r;for(let b of n){if(b.data.choices.length===0)continue;let T=b.data.choices[0].delta;T.content&&(e=`${e||""}${T.content||""}`);let y=(a=T.toolCalls)==null?void 0:a[0];if(y){r=r||[];let f=r.at(-1);if(!f||y.id){r.push({id:y.id||"",type:y.type||"function",function:{name:((i=y.function)==null?void 0:i.name)||"",arguments:((c=y.function)==null?void 0:c.arguments)||""}});continue}f.function.name=`${f.function.name}${((p=y.function)==null?void 0:p.name)||""}`,f.function.arguments=`${f.function.arguments}${((u=y.function)==null?void 0:u.arguments)||""}`}}let s=n[0].data.choices.at(0);return t.choices.push({finish_reason:(d=s==null?void 0:s.finish_reason)!=null?d:"stop",index:(l=s==null?void 0:s.index)!=null?l:0,logprobs:(h=s==null?void 0:s.logprobs)!=null?h:null,message:{role:"assistant",content:e,tool_calls:r||void 0,refusal:(w=s==null?void 0:s.delta.refusal)!=null?w:null}}),t.id=o.id,t.model=o.model,t.created=o.created,t.usage=(g=o.usage)!=null?g:void 0,t};function Ne(n,e,t,o){return B(this,null,function*(){let r={request_id:null,raw_response:null,prompt_blueprint:null},s=[];try{for(var c=V(n),p,u,d;p=!(u=yield new E(c.next())).done;p=!1){let l=u.value;s.push(l),r.raw_response=l,l&&typeof l=="object"&&"type"in l&&(r.prompt_blueprint=fe(l,o)),l&&typeof l=="object"&&"candidates"in l&&(r.prompt_blueprint=de(l,o)),l&&typeof l=="object"&&"choices"in l&&(r.prompt_blueprint=H(l,o)),l&&typeof l=="object"&&"data"in l&&(r.prompt_blueprint=H(l.data,o)),yield r}}catch(u){d=[u]}finally{try{p&&(u=c.return)&&(yield new E(u.call(c)))}finally{if(d)throw d[0]}}let a=t(s),i=yield new E(e({request_response:a}));r.request_id=i.request_id,r.prompt_blueprint=i.prompt_blueprint,yield r})}var mt=(n,e)=>m(void 0,null,function*(){return n.chat.completions.create(e)}),ft=(n,e)=>m(void 0,null,function*(){return n.completions.create(e)}),ke={chat:mt,completion:ft},xe=(n,e)=>m(void 0,null,function*(){let t=I("openai").default,o=new t({baseURL:e.baseURL,apiKey:e.apiKey});e==null||delete e.apiKey,e==null||delete e.baseURL;let r=ke[n.prompt_template.type];return r(o,e)}),qe=(n,e)=>m(void 0,null,function*(){let{AzureOpenAI:t}=I("openai"),o=new t({endpoint:process.env.AZURE_OPENAI_ENDPOINT||e.baseURL,apiVersion:process.env.OPENAI_API_VERSION||e.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||e.apiKey});e==null||delete e.baseURL,e==null||delete e.apiVersion,e==null||delete e.apiKey;let r=ke[n.prompt_template.type];return r(o,e)}),Le=(n,e)=>m(void 0,null,function*(){return n.messages.create(e)}),dt=(n,e)=>m(void 0,null,function*(){return n.completions.create(e)}),ve={chat:Le,completion:dt},$e=(n,e)=>m(void 0,null,function*(){let t=I("@anthropic-ai/sdk").default,o=new t({baseURL:e.baseURL,apiKey:e.apiKey}),r=ve[n.prompt_template.type];return r(o,e)}),Ge=(n,e)=>m(void 0,null,function*(){try{let t=yield fetch(`${R}/log-request`,{method:"POST",headers:{"X-API-KEY":n,"Content-Type":"application/json"},body:JSON.stringify(e)}),o=yield t.json();return t.status!==201?(A(o,"WARNING: While logging your request PromptLayer had the following error"),null):o}catch(t){return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${t}`),null}}),ht=(n,e,t,o)=>{var a,i;let r=_({},o),s=[];if(n){let c={text:n,thought:!0};s.push(c)}if(e){let c={text:e,thought:null};s.push(c)}for(let c of t){let p={function_call:c};s.push(p)}return s.length>0&&((i=(a=r.candidates)==null?void 0:a[0])!=null&&i.content)&&(r.candidates[0].content.parts=s),r},We=n=>{var s,a;let{GenerateContentResponse:e}=I("@google/genai");if(!n.length)return new e;let t="",o="",r=[];for(let i of n)if(i.candidates&&((a=(s=i.candidates[0])==null?void 0:s.content)!=null&&a.parts))for(let c of i.candidates[0].content.parts)c.text?c.thought===!0?t+=c.text:o+=c.text:c.functionCall&&r.push(c.functionCall);return ht(t,o,r,n[n.length-1])},yt=n=>We(n),_t=n=>We(n),gt=(n,e)=>m(void 0,null,function*(){var a,i;let t=e==null?void 0:e.history,o=e==null?void 0:e.generationConfig,r=t.length>0?(a=t[t.length-1])==null?void 0:a.parts:"",s=n.chats.create({model:e==null?void 0:e.model,history:(i=t.slice(0,-1))!=null?i:[],config:o});return e!=null&&e.stream?yield s.sendMessageStream({message:r}):yield s.sendMessage({message:r})}),wt=(n,o)=>m(void 0,null,function*(){var r=o,{stream:e}=r,t=v(r,["stream"]);return e?yield n.generateContentStream(_({},t)):yield n.generateContent(_({},t))}),Pt={chat:gt,completion:wt},te=(n,e)=>m(void 0,null,function*(){let{GoogleGenAI:t}=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,s=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,a={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:r,scopes:["https://www.googleapis.com/auth/cloud-platform"]},i=o?new t({apiKey:o}):new t({vertexai:!0,project:r,location:s,googleAuthOptions:a}),c=Pt[n.prompt_template.type];return yield c(i,e)}),_e=n=>n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),G=(n,e=new Set)=>!n||typeof n!="object"?n:Array.isArray(n)?n.map(t=>G(t,e)):Object.fromEntries(Object.entries(n).map(([t,o])=>e.has(t)?[_e(t),o]:[_e(t),G(o,e)])),Rt=["openai","openai.azure"],Tt={openai:{chat:{function_name:"openai.chat.completions.create",stream_function:Q},completion:{function_name:"openai.completions.create",stream_function:he}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:ee},completion:{function_name:"anthropic.completions.create",stream_function:ye}},"openai.azure":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:Q},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:he}},google:{chat:{function_name:"google.convo.send_message",stream_function:yt},completion:{function_name:"google.model.generate_content",stream_function:_t}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:ee},completion:{function_name:"anthropic.completions.create",stream_function:ye}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:ut},completion:{function_name:"",stream_function:null}}},Me=(n,e,t={},o=!1)=>{var i,c,p,u,d,l,h;let r=(p=e==null?void 0:e.client)!=null?p:(c=(i=n.metadata)==null?void 0:i.model)==null?void 0:c.provider;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let s=S(_({},n.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(r)&&((d=(u=n.metadata)==null?void 0:u.model)!=null&&d.name.startsWith("gemini"))&&(s=G(s,new Set(["function_declarations"])));let a={baseURL:(h=e==null?void 0:e.base_url)!=null?h:(l=n.provider_base_url)==null?void 0:l.url,apiKey:e==null?void 0:e.api_key};return Object.entries(a).forEach(([w,g])=>{g!==void 0&&(s[w]=g)}),o&&Rt.includes(r)&&(s.stream_options={include_usage:!0}),{provider_type:r,kwargs:s}},Ke=(n,e)=>{let t=Tt[n];if(!t)throw new Error(`Unsupported provider type: ${n}`);let o=e.type,r=t[o];if(!r)throw new Error(`Unsupported template type '${e.type}' for provider '${n}'`);return r},je=(n,e)=>m(void 0,null,function*(){var o;let t=(o=n.metadata)==null?void 0:o.model;if(!t)throw new Error("Model metadata not found in prompt blueprint");if(t.name.startsWith("gemini"))return te(n,e);if(t.name.startsWith("claude")){let{AnthropicVertex:r}=yield import("@anthropic-ai/vertex-sdk"),s=new r({baseURL:e.baseURL});if(n.prompt_template.type==="chat")return Le(s,e);throw new Error(`Unsupported prompt template type '${n.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${t.name}' for Vertex AI request`)}),Ue=(n,e)=>m(void 0,null,function*(){let{AnthropicBedrock:t}=yield import("@anthropic-ai/bedrock-sdk"),o=new t({awsAccessKey:e.aws_access_key,awsSecretKey:e.aws_secret_key,awsRegion:e.aws_region,awsSessionToken:e.aws_session_token,baseURL:e.base_url}),r=ve[n.prompt_template.type];return r(o,e)}),Je=(n,e)=>m(void 0,null,function*(){let{Mistral:t}=yield import("@mistralai/mistralai"),o=new t({apiKey:process.env.MISTRAL_API_KEY});return e=G(e,new Set),e!=null&&e.stream?(delete e.stream,yield o.chat.stream(e)):(delete e.stream,yield o.chat.complete(e))});var W=class{constructor(e){this.create=()=>Se(this.apiKey);this.apiKey=e}};import*as Fe from"@opentelemetry/api";import{SimpleSpanProcessor as bt}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as St}from"@opentelemetry/sdk-trace-node";import{SpanKind as q,SpanStatusCode as ne}from"@opentelemetry/api";import{ExportResultCode as M}from"@opentelemetry/core";var oe=class{constructor(e,t){this.apiKey=t||process.env.PROMPTLAYER_API_KEY,this.enableTracing=e,this.url=`${R}/spans-bulk`}attributesToObject(e){return e?Object.fromEntries(Object.entries(e)):{}}spanKindToString(e){return{[q.INTERNAL]:"SpanKind.INTERNAL",[q.SERVER]:"SpanKind.SERVER",[q.CLIENT]:"SpanKind.CLIENT",[q.PRODUCER]:"SpanKind.PRODUCER",[q.CONSUMER]:"SpanKind.CONSUMER"}[e]||"SpanKind.INTERNAL"}statusCodeToString(e){return{[ne.ERROR]:"StatusCode.ERROR",[ne.OK]:"StatusCode.OK",[ne.UNSET]:"StatusCode.UNSET"}[e]||"StatusCode.UNSET"}toNanoseconds(e){return(BigInt(e[0])*BigInt(1e9)+BigInt(e[1])).toString()}export(e){if(!this.enableTracing)return Promise.resolve(M.SUCCESS);let t=e.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(s=>({name:s.name,timestamp:this.toNanoseconds(s.time),attributes:this.attributesToObject(s.attributes)})),links:o.links.map(s=>({context:s.context,attributes:this.attributesToObject(s.attributes)})),resource:{attributes:S(_({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey||""},body:JSON.stringify({spans:t})}).then(o=>o.ok?M.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
-
HTTP error! status: ${o.status}`),
|
|
1
|
+
var st=Object.defineProperty,at=Object.defineProperties;var it=Object.getOwnPropertyDescriptors;var v=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable;var pe=(t,e)=>{if(e=Symbol[t])return e;throw Error("Symbol."+t+" is not defined")};var le=(t,e,n)=>e in t?st(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_=(t,e)=>{for(var n in e||(e={}))ue.call(e,n)&&le(t,n,e[n]);if(v)for(var n of v(e))me.call(e,n)&&le(t,n,e[n]);return t},w=(t,e)=>at(t,it(e));var I=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,n)=>(typeof require!="undefined"?require:e)[n]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var $=(t,e)=>{var n={};for(var o in t)ue.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&v)for(var o of v(t))e.indexOf(o)<0&&me.call(t,o)&&(n[o]=t[o]);return n};var m=(t,e,n)=>new Promise((o,r)=>{var s=c=>{try{p(n.next(c))}catch(i){r(i)}},a=c=>{try{p(n.throw(c))}catch(i){r(i)}},p=c=>c.done?o(c.value):Promise.resolve(c.value).then(s,a);p((n=n.apply(t,e)).next())}),O=function(t,e){this[0]=t,this[1]=e},V=(t,e,n)=>{var o=(a,p,c,i)=>{try{var l=n[a](p),f=(p=l.value)instanceof O,g=l.done;Promise.resolve(f?p[0]:p).then(y=>f?o(a==="return"?a:"next",p[1]?{done:y.done,value:y.value}:y,c,i):c({value:y,done:g})).catch(y=>o("throw",y,c,i))}catch(y){i(y)}},r=a=>s[a]=p=>new Promise((c,i)=>o(a,p,c,i)),s={};return n=n.apply(t,e),s[Symbol.asyncIterator]=()=>s,r("next"),r("throw"),r("return"),s};var X=(t,e,n)=>(e=t[pe("asyncIterator")])?e.call(t):(t=t[pe("iterator")](),e={},n=(o,r)=>(r=t[o])&&(e[o]=s=>new Promise((a,p,c)=>(s=r.call(t,s),c=s.done,Promise.resolve(s.value).then(i=>a({value:i,done:c}),p)))),n("next"),n("return"),e);import ct from"ably";var x=(t,e,n)=>({id:t,function:{name:e,input:n}}),A=n=>{var o=n,{type:t}=o,e=$(o,["type"]);return _({type:t},e)},G=(t,e)=>({input_variables:[],template_format:"f-string",content:t,role:"assistant",function_call:null,name:null,tool_calls:e}),W=(t,e)=>({prompt_template:{messages:[t],type:"chat",input_variables:[]},metadata:e}),fe=(t,e)=>{let n=[],o=[];t.type==="content_block_start"?t.content_block.type==="thinking"?n.push(A({type:"thinking",thinking:"",signature:""})):t.content_block.type==="text"?n.push(A({type:"text",text:""})):t.content_block.type==="tool_use"&&o.push(x(t.content_block.id||"",t.content_block.name||"",{})):t.type==="content_block_delta"&&(t.delta.type==="thinking_delta"?n.push(A({type:"thinking",thinking:t.delta.thinking||"",signature:""})):t.delta.type==="text_delta"?n.push(A({type:"text",text:t.delta.text||""})):t.delta.type==="signature_delta"?n.push(A({type:"thinking",thinking:"",signature:t.delta.signature||""})):t.delta.type==="input_json_delta"&&o.push(x("","",t.delta.partial_json)));let r=G(n,o);return W(r,e)},de=(t,e)=>{let n=[],o=[];for(let s of t.candidates)if(s.content&&s.content.parts&&Array.isArray(s.content.parts))for(let a of s.content.parts)a.text?a.thought===!0?n.push(A({type:"thinking",thinking:a.text,signature:a.thoughtSignature||""})):n.push(A({type:"text",text:a.text})):a.functionCall&&o.push(x(a.functionCall.id||"",a.functionCall.name||"",a.functionCall.args||{}));let r=G(n,o);return W(r,e)},H=(t,e)=>{let n=[],o=[];for(let s of t.choices)if(s.delta){s.delta.content&&n.push(A({type:"text",text:s.delta.content}));let a=s.delta.tool_calls||s.delta.toolCalls;if(a&&Array.isArray(a))for(let p of a)p.function&&o.push(x(p.id||"",p.function.name||"",p.function.arguments||""))}let r=G(n,o);return W(r,e)},he=(t,e)=>{var s,a,p,c;let n=[],o=[];if("contentBlockDelta"in t){let i=((s=t.contentBlockDelta)==null?void 0:s.delta)||{};if("reasoningContent"in i){let l=((a=i.reasoningContent)==null?void 0:a.text)||"",f=((p=i.reasoningContent)==null?void 0:p.signature)||"";n.push(A({type:"thinking",thinking:l,signature:f}))}else if("text"in i)n.push(A({type:"text",text:i.text||""}));else if("toolUse"in i){let l=i.toolUse||{};o.push(x(l.toolUseId||"",l.name||"",l.input||""))}}else if("contentBlockStart"in t){let i=((c=t.contentBlockStart)==null?void 0:c.start)||{};if("toolUse"in i){let l=i.toolUse||{};o.push(x(l.toolUseId||"",l.name||"",""))}}let r=G(n,o);return W(r,e)};var Z="SET_WORKFLOW_COMPLETE";function pt(t,e,n){return m(this,null,function*(){let o=yield fetch(`${P}/workflow-version-execution-results?workflow_version_execution_id=${t}&return_all_outputs=${e}`,{headers:n});if(!o.ok)throw new Error("Failed to fetch final output");return o.json()})}function lt(t,e,n,o){return function(r){return m(this,null,function*(){if(r.name===Z)try{let s=JSON.parse(r.data),a=s.result_code,p;if(a==="OK"||a==null)p=s.final_output;else if(a==="EXCEEDS_SIZE_LIMIT")p=yield pt(e,n,o);else throw new Error(`Unsupported final output code: ${a}`);t.resolve(p)}catch(s){t.reject(s)}})}}function ut(a){return m(this,arguments,function*({token:t,channelName:e,executionId:n,returnAllOutputs:o,headers:r,timeout:s}){let p=new ct.Realtime(t),c=p.channels.get(e),i={},l=new Promise((g,y)=>{i.resolve=g,i.reject=y}),f=lt(i,n,o,r);yield c.subscribe(Z,f);try{return yield new Promise((g,y)=>{let u=setTimeout(()=>{y(new Error("Workflow execution did not complete properly (timeout)"))},s);l.then(R=>{clearTimeout(u),g(R)}).catch(R=>{clearTimeout(u),y(R)})})}finally{console.log("Closing client"),c.unsubscribe(Z,f),p.close(),console.log("Closed client")}})}var P=process.env.PROMPTLAYER_API_URL||"https://api.promptlayer.com",Te=(t,e)=>m(void 0,null,function*(){return e.request_response[Symbol.asyncIterator]!==void 0?ft(t,e.request_response,e):yield Pe(t,e)}),Pe=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),o=yield n.json();if(n.status!==200&&E(o,"WARNING: While logging your request, PromptLayer experienced the following error:"),o&&e.return_pl_id)return[e.request_response,o.request_id]}catch(n){console.warn(`WARNING: While logging your request PromptLayer had the following error: ${n}`)}return e.request_response}),be=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/library-track-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w(_({},e),{api_key:t}))}),o=yield n.json();if(n.status!==200)return E(o,"WARNING: While logging metadata to your request, PromptLayer experienced the following error"),!1}catch(n){return console.warn(`WARNING: While logging metadata to your request, PromptLayer experienced the following error: ${n}`),!1}return!0}),Se=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/library-track-score`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w(_({},e),{api_key:t}))}),o=yield n.json();if(n.status!==200)return E(o,"WARNING: While scoring your request, PromptLayer experienced the following error"),!1}catch(n){return console.warn(`WARNING: While scoring your request, PromptLayer experienced the following error: ${n}`),!1}return!0}),we=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/library-track-prompt`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w(_({},e),{api_key:t}))}),o=yield n.json();if(n.status!==200)return E(o,"WARNING: While associating your request with a prompt template, PromptLayer experienced the following error"),!1}catch(n){return console.warn(`WARNING: While associating your request with a prompt template, PromptLayer experienced the following error: ${n}`),!1}return!0}),Ee=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/track-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w(_({},e),{api_key:t}))}),o=yield n.json();if(n.status!==200)return E(o,"WARNING: While associating your request with a group, PromptLayer experienced the following error"),!1}catch(n){return console.warn(`WARNING: While associating your request with a group, PromptLayer experienced the following error: ${n}`),!1}return!0}),Ae=t=>m(void 0,null,function*(){try{let e=yield fetch(`${P}/create-group`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t})}),n=yield e.json();return e.status!==200?(E(n,"WARNING: While creating a group PromptLayer had the following error"),!1):n.id}catch(e){return console.warn(`WARNING: While creating a group PromptLayer had the following error: ${e}`),!1}}),Ce=(t,e,n)=>m(void 0,null,function*(){try{let o=new URL(`${P}/prompt-templates/${e}`),r=yield fetch(o,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":t},body:JSON.stringify(n)}),s=yield r.json();return r.status!==200?(E(s,"WARNING: While fetching a prompt template PromptLayer had the following error"),null):(s.warning&&console.warn(`WARNING: While fetching your prompt PromptLayer had the following error: ${s.warning}`),s)}catch(o){return console.warn(`WARNING: While fetching a prompt template PromptLayer had the following error: ${o}`),null}}),Oe=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/rest/prompt-templates`,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":t},body:JSON.stringify({prompt_template:_({},e),prompt_version:_({},e),release_labels:e.release_labels?e.release_labels:void 0})}),o=yield n.json();return n.status===400&&E(o,"WARNING: While publishing a prompt template PromptLayer had the following error"),o}catch(n){console.warn(`WARNING: While publishing a prompt template PromptLayer had the following error: ${n}`)}}),Ie=(t,e)=>m(void 0,null,function*(){var n;try{let o=new URL(`${P}/prompt-templates`);Object.entries(e||{}).forEach(([a,p])=>o.searchParams.append(a,p.toString()));let r=yield fetch(o,{headers:{"Content-Type":"application/json","X-API-KEY":t}}),s=yield r.json();return r.status!==200?(E(s,"WARNING: While fetching all prompt templates PromptLayer had the following error"),null):(n=s.items)!=null?n:[]}catch(o){return console.warn(`WARNING: While fetching all prompt templates PromptLayer had the following error: ${o}`),null}}),xe=c=>m(void 0,[c],function*({workflow_name:t,input_variables:e,metadata:n={},workflow_label_name:o=null,workflow_version_number:r=null,return_all_outputs:s=!1,api_key:a,timeout:p=36e5}){let i={input_variables:e,metadata:n,workflow_label_name:o,workflow_version_number:r,return_all_outputs:s},l={"X-API-KEY":a,"Content-Type":"application/json"};try{let f=yield fetch(`${P}/workflows/${encodeURIComponent(t)}/run`,{method:"POST",headers:l,body:JSON.stringify(i)});if(f.status!==201)return{success:!1,message:`Failed to run workflow: ${(yield f.json().catch(()=>({}))).error||f.statusText}`};let g=yield f.json();g.warning&&console.warn(`WARNING: ${g.warning}`);let y=g.workflow_version_execution_id;if(!y)return console.log("No execution ID returned from workflow run"),{success:!1,message:"Failed to run workflow"};let u=`workflow_updates:${y}`,b=(yield(yield fetch(`${P}/ws-token-request-library?capability=${u}`,{method:"POST",headers:l})).json()).token_details.token;return yield ut({token:b,channelName:u,executionId:y,returnAllOutputs:s,headers:l,timeout:p})}catch(f){throw console.error(`Failed to run workflow: ${f instanceof Error?f.message:f}`),f}}),Q=t=>{var p,c,i,l,f,g,y,u,R,S;let e=null,n,o={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},r=t.at(-1);if(!r)return o;let s;for(let b of t){if(b.choices.length===0)continue;let h=b.choices[0].delta;h.content&&(e=`${e||""}${h.content||""}`),h.function_call&&(n={name:`${n?n.name:""}${h.function_call.name||""}`,arguments:`${n?n.arguments:""}${h.function_call.arguments||""}`});let d=(p=h.tool_calls)==null?void 0:p[0];if(d){s=s||[];let T=s.at(-1);if(!T||d.id){s.push({id:d.id||"",type:d.type||"function",function:{name:((c=d.function)==null?void 0:c.name)||"",arguments:((i=d.function)==null?void 0:i.arguments)||""}});continue}T.function.name=`${T.function.name}${((l=d.function)==null?void 0:l.name)||""}`,T.function.arguments=`${T.function.arguments}${((f=d.function)==null?void 0:f.arguments)||""}`}}let a=t[0].choices.at(0);return o.choices.push({finish_reason:(g=a==null?void 0:a.finish_reason)!=null?g:"stop",index:(y=a==null?void 0:a.index)!=null?y:0,logprobs:(u=a==null?void 0:a.logprobs)!=null?u:null,message:{role:"assistant",content:e,function_call:n||void 0,tool_calls:s||void 0,refusal:(R=a==null?void 0:a.delta.refusal)!=null?R:null}}),o.id=r.id,o.model=r.model,o.created=r.created,o.system_fingerprint=r.system_fingerprint,o.usage=(S=r.usage)!=null?S:void 0,o},ee=t=>{var c;let e={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 e;let o=null,r="",s="",a="",p="";for(let i of t)if(i.type==="message_start")e=_({},i.message);else if(i.type==="content_block_start")o=_({},i.content_block),o.type==="thinking"?(r="",s=""):o.type==="text"?a="":(o.type==="tool_use"||o.type==="server_tool_use")&&(p="");else if(i.type==="content_block_delta"&&o!==null){if(o.type==="thinking")"signature"in i.delta&&(r=i.delta.signature||""),"thinking"in i.delta&&(s+=i.delta.thinking||"");else if(o.type==="text")"text"in i.delta&&(a+=i.delta.text||"");else if((o.type==="tool_use"||o.type==="server_tool_use")&&i.delta.type==="input_json_delta"){let l=i.delta;p+=l.partial_json||""}}else if(i.type==="content_block_stop"&&o!==null){if(o.type==="thinking")o.signature=r,o.thinking=s;else if(o.type==="text")o.text=a,o.citations=null;else if(o.type==="tool_use"||o.type==="server_tool_use")try{o.input=p?JSON.parse(p):{}}catch(l){o.input={}}e.content.push(o),o=null,r="",s="",a="",p=""}else i.type==="message_delta"&&("usage"in i&&i.usage&&(e.usage=w(_({},e.usage),{output_tokens:(c=i.usage.output_tokens)!=null?c:0})),"delta"in i&&i.delta&&("stop_reason"in i.delta&&i.delta.stop_reason!==void 0&&(e.stop_reason=i.delta.stop_reason),"stop_sequence"in i.delta&&i.delta.stop_sequence!==void 0&&(e.stop_sequence=i.delta.stop_sequence)));return e},mt=(t,e="openai.chat.completions.create")=>{if("completion"in t[0])return t.reduce((n,o)=>w(_({},o),{completion:`${n.completion}${o.completion}`}),{});if(e==="anthropic.messages.create")return ee(t);if("text"in t[0].choices[0]){let n="";for(let r of t)n=`${n}${r.choices[0].text}`;let o=structuredClone(t.at(-1));return o.choices[0].text=n,o}if("delta"in t[0].choices[0]){let n=Q(t);return n.choices[0]=_(_({},n.choices[0]),n.choices[0].message),n}return""};function ft(t,e,n){return V(this,null,function*(){let o=[];try{for(var a=X(e),p,c,i;p=!(c=yield new O(a.next())).done;p=!1){let l=c.value;yield n.return_pl_id?[l,null]:l,o.push(l)}}catch(c){i=[c]}finally{try{p&&(c=a.return)&&(yield new O(c.call(a)))}finally{if(i)throw i[0]}}let r=mt(o,n.function_name),s=yield new O(Pe(t,w(_({},n),{request_response:r,request_end_time:new Date().toISOString()})));if(s&&n.return_pl_id){let l=s[1];yield[o.at(-1),l]}})}var E=(t,e)=>{try{console.warn(`${e}: ${t.message}`)}catch(n){console.warn(`${e}: ${t}`)}},Ne=t=>m(void 0,null,function*(){try{let e=yield fetch(`${P}/track-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=yield e.json();return e.status!==200&&E(n,"WARNING: While logging your request, PromptLayer experienced the following error:"),n}catch(e){console.warn(`WARNING: While logging your request PromptLayer had the following error: ${e}`)}return{}}),ye=t=>{let e={id:"",choices:[{finish_reason:"stop",index:0,text:"",logprobs:null}],created:Date.now(),model:"",object:"text_completion"},n=t.at(-1);if(!n)return e;let o="";for(let r of t)r.choices.length>0&&r.choices[0].text&&(o=`${o}${r.choices[0].text}`);return e.choices[0].text=o,e.id=n.id,e.created=n.created,e.model=n.model,e.system_fingerprint=n.system_fingerprint,e.usage=n.usage,e},_e=t=>{let e={completion:"",id:"",model:"",stop_reason:"",type:"completion"},n=t.at(-1);if(!n)return e;let o="";for(let r of t)o=`${o}${r.completion}`;return e.completion=o,e.id=n.id,e.model=n.model,e.stop_reason=n.stop_reason,e},dt=t=>{var a,p,c,i,l,f,g,y,u,R;let e=null,n={id:"",choices:[],created:Date.now(),model:"",object:"chat.completion"},o=t.at(-1).data;if(!o)return n;let r;for(let S of t){if(S.data.choices.length===0)continue;let b=S.data.choices[0].delta;b.content&&(e=`${e||""}${b.content||""}`);let h=(a=b.toolCalls)==null?void 0:a[0];if(h){r=r||[];let d=r.at(-1);if(!d||h.id){r.push({id:h.id||"",type:h.type||"function",function:{name:((p=h.function)==null?void 0:p.name)||"",arguments:((c=h.function)==null?void 0:c.arguments)||""}});continue}d.function.name=`${d.function.name}${((i=h.function)==null?void 0:i.name)||""}`,d.function.arguments=`${d.function.arguments}${((l=h.function)==null?void 0:l.arguments)||""}`}}let s=t[0].data.choices.at(0);return n.choices.push({finish_reason:(f=s==null?void 0:s.finish_reason)!=null?f:"stop",index:(g=s==null?void 0:s.index)!=null?g:0,logprobs:(y=s==null?void 0:s.logprobs)!=null?y:null,message:{role:"assistant",content:e,tool_calls:r||void 0,refusal:(u=s==null?void 0:s.delta.refusal)!=null?u:null}}),n.id=o.id,n.model=o.model,n.created=o.created,n.usage=(R=o.usage)!=null?R:void 0,n},ge=t=>{let e={ResponseMetadata:{},output:{message:{}},stopReason:"end_turn",metrics:{},usage:{}},n=[],o=null,r="",s="",a="",p="";for(let c of t)if("contentBlockStart"in c){let i=c.contentBlockStart;if("start"in i&&"toolUse"in i.start){let l=i.start.toolUse;o={toolUse:{toolUseId:l.toolUseId,name:l.name}},r=""}}else if("contentBlockDelta"in c){let i=c.contentBlockDelta.delta;if("text"in i)s+=i.text;else if("reasoningContent"in i){let l=i.reasoningContent;"text"in l?p+=l.text:"signature"in l&&(a+=l.signature)}else if("toolUse"in i&&"input"in i.toolUse){let l=i.toolUse.input;if(r+=l,!l.trim())continue}}else if("contentBlockStop"in c)if(o&&r){try{o.toolUse.input=JSON.parse(r)}catch(i){o.toolUse.input={}}n.push(o),o=null,r=""}else s?(n.push({text:s}),s=""):p&&a&&(n.push({reasoningContent:{reasoningText:{text:p,signature:a}}}),p="",a="");else if("messageStop"in c)e.stopReason=c.messageStop.stopReason;else if("metadata"in c){let i=c.metadata;e.usage=(i==null?void 0:i.usage)||{},e.metrics=(i==null?void 0:i.metrics)||{}}return e.output.message={role:"assistant",content:n},e};function ke(t,e,n,o){return V(this,null,function*(){let r={request_id:null,raw_response:null,prompt_blueprint:null},s={},a=o.model.provider;a=="amazon.bedrock"&&(s=t==null?void 0:t.$metadata,t=t==null?void 0:t.stream);let p=[];try{for(var l=X(t),f,g,y;f=!(g=yield new O(l.next())).done;f=!1){let u=g.value;p.push(u),r.raw_response=u,u&&typeof u=="object"&&"type"in u&&(r.prompt_blueprint=fe(u,o)),u&&typeof u=="object"&&"candidates"in u&&(r.prompt_blueprint=de(u,o)),u&&typeof u=="object"&&"choices"in u&&(r.prompt_blueprint=H(u,o)),u&&typeof u=="object"&&"data"in u&&(r.prompt_blueprint=H(u.data,o)),a==="amazon.bedrock"&&(r.prompt_blueprint=he(u,o)),yield r}}catch(g){y=[g]}finally{try{f&&(g=l.return)&&(yield new O(g.call(l)))}finally{if(y)throw y[0]}}let c=n(p);a==="amazon.bedrock"&&(c.ResponseMetadata=s);let i=yield new O(e({request_response:c}));r.request_id=i.request_id,r.prompt_blueprint=i.prompt_blueprint,yield r})}var ht=(t,e)=>m(void 0,null,function*(){return t.chat.completions.create(e)}),yt=(t,e)=>m(void 0,null,function*(){return t.completions.create(e)}),qe={chat:ht,completion:yt},Le=(t,e)=>m(void 0,null,function*(){let n=I("openai").default,o=new n({baseURL:e.baseURL,apiKey:e.apiKey});e==null||delete e.apiKey,e==null||delete e.baseURL;let r=qe[t.prompt_template.type];return r(o,e)}),ve=(t,e)=>m(void 0,null,function*(){let{AzureOpenAI:n}=I("openai"),o=new n({endpoint:process.env.AZURE_OPENAI_ENDPOINT||e.baseURL,apiVersion:process.env.OPENAI_API_VERSION||e.apiVersion,apiKey:process.env.AZURE_OPENAI_API_KEY||e.apiKey});e==null||delete e.baseURL,e==null||delete e.apiVersion,e==null||delete e.apiKey;let r=qe[t.prompt_template.type];return r(o,e)}),$e=(t,e)=>m(void 0,null,function*(){return t.messages.create(e)}),_t=(t,e)=>m(void 0,null,function*(){return t.completions.create(e)}),Ge={chat:$e,completion:_t},We=(t,e)=>m(void 0,null,function*(){let n=I("@anthropic-ai/sdk").default,o=new n({baseURL:e.baseURL,apiKey:e.apiKey}),r=Ge[t.prompt_template.type];return r(o,e)}),Ke=(t,e)=>m(void 0,null,function*(){try{let n=yield fetch(`${P}/log-request`,{method:"POST",headers:{"X-API-KEY":t,"Content-Type":"application/json"},body:JSON.stringify(e)}),o=yield n.json();return n.status!==201?(E(o,"WARNING: While logging your request PromptLayer had the following error"),null):o}catch(n){return console.warn(`WARNING: While tracking your prompt PromptLayer had the following error: ${n}`),null}}),gt=(t,e,n,o)=>{var a,p;let r=_({},o),s=[];if(t){let c={text:t,thought:!0};s.push(c)}if(e){let c={text:e,thought:null};s.push(c)}for(let c of n){let i={function_call:c};s.push(i)}return s.length>0&&((p=(a=r.candidates)==null?void 0:a[0])!=null&&p.content)&&(r.candidates[0].content.parts=s),r},Me=t=>{var s,a;let{GenerateContentResponse:e}=I("@google/genai");if(!t.length)return new e;let n="",o="",r=[];for(let p of t)if(p.candidates&&((a=(s=p.candidates[0])==null?void 0:s.content)!=null&&a.parts))for(let c of p.candidates[0].content.parts)c.text?c.thought===!0?n+=c.text:o+=c.text:c.functionCall&&r.push(c.functionCall);return gt(n,o,r,t[t.length-1])},Rt=t=>Me(t),Tt=t=>Me(t),Pt=(t,e)=>m(void 0,null,function*(){var a,p;let n=e==null?void 0:e.history,o=e==null?void 0:e.generationConfig,r=n.length>0?(a=n[n.length-1])==null?void 0:a.parts:"",s=t.chats.create({model:e==null?void 0:e.model,history:(p=n.slice(0,-1))!=null?p:[],config:o});return e!=null&&e.stream?yield s.sendMessageStream({message:r}):yield s.sendMessage({message:r})}),bt=(t,o)=>m(void 0,null,function*(){var r=o,{stream:e}=r,n=$(r,["stream"]);return e?yield t.generateContentStream(_({},n)):yield t.generateContent(_({},n))}),St={chat:Pt,completion:bt},te=(t,e)=>m(void 0,null,function*(){let{GoogleGenAI:n}=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,s=process.env.VERTEX_AI_PROJECT_LOCATION||process.env.GOOGLE_PROJECT_LOCATION||process.env.GOOGLE_CLOUD_PROJECT_LOCATION,a={keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,projectId:r,scopes:["https://www.googleapis.com/auth/cloud-platform"]},p=o?new n({apiKey:o}):new n({vertexai:!0,project:r,location:s,googleAuthOptions:a}),c=St[t.prompt_template.type];return yield c(p,e)}),Re=t=>t.replace(/_([a-z])/g,(e,n)=>n.toUpperCase()),K=(t,e=new Set)=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(n=>K(n,e)):Object.fromEntries(Object.entries(t).map(([n,o])=>e.has(n)?[Re(n),o]:[Re(n),K(o,e)])),wt=["openai","openai.azure"],Et={openai:{chat:{function_name:"openai.chat.completions.create",stream_function:Q},completion:{function_name:"openai.completions.create",stream_function:ye}},anthropic:{chat:{function_name:"anthropic.messages.create",stream_function:ee},completion:{function_name:"anthropic.completions.create",stream_function:_e}},"openai.azure":{chat:{function_name:"openai.AzureOpenAI.chat.completions.create",stream_function:Q},completion:{function_name:"openai.AzureOpenAI.completions.create",stream_function:ye}},google:{chat:{function_name:"google.convo.send_message",stream_function:Rt},completion:{function_name:"google.model.generate_content",stream_function:Tt}},"amazon.bedrock":{chat:{function_name:"boto3.bedrock-runtime.converse",stream_function:ge},completion:{function_name:"boto3.bedrock-runtime.converse",stream_function:ge}},"anthropic.bedrock":{chat:{function_name:"anthropic.messages.create",stream_function:ee},completion:{function_name:"anthropic.completions.create",stream_function:_e}},mistral:{chat:{function_name:"mistral.client.chat",stream_function:dt},completion:{function_name:"",stream_function:null}}},Ue=(t,e,n={},o=!1)=>{var p,c,i,l,f,g,y;let r=(i=e==null?void 0:e.client)!=null?i:(c=(p=t.metadata)==null?void 0:p.model)==null?void 0:c.provider;if(!r)throw new Error("Provider type not found in prompt blueprint or custom provider");let s=w(_({},t.llm_kwargs||{}),{stream:o});["google","vertexai"].includes(r)&&((f=(l=t.metadata)==null?void 0:l.model)!=null&&f.name.startsWith("gemini"))&&(s=K(s,new Set(["function_declarations"])));let a={baseURL:(y=e==null?void 0:e.base_url)!=null?y:(g=t.provider_base_url)==null?void 0:g.url,apiKey:e==null?void 0:e.api_key};return Object.entries(a).forEach(([u,R])=>{R!==void 0&&(s[u]=R)}),o&&wt.includes(r)&&(s.stream_options={include_usage:!0}),{provider_type:r,kwargs:s}},je=(t,e)=>{let n=Et[t];if(!n)throw new Error(`Unsupported provider type: ${t}`);let o=e.type,r=n[o];if(!r)throw new Error(`Unsupported template type '${e.type}' for provider '${t}'`);return r},De=(t,e)=>m(void 0,null,function*(){var o;let n=(o=t.metadata)==null?void 0:o.model;if(!n)throw new Error("Model metadata not found in prompt blueprint");if(n.name.startsWith("gemini"))return te(t,e);if(n.name.startsWith("claude")){let{AnthropicVertex:r}=yield import("@anthropic-ai/vertex-sdk"),s=new r({baseURL:e.baseURL});if(t.prompt_template.type==="chat")return $e(s,e);throw new Error(`Unsupported prompt template type '${t.prompt_template.type}' for Anthropic Vertex AI`)}throw new Error(`Unsupported model name '${n.name}' for Vertex AI request`)}),Be=(t,e)=>m(void 0,null,function*(){let{BedrockRuntimeClient:n,ConverseCommand:o,ConverseStreamCommand:r}=yield import("@aws-sdk/client-bedrock-runtime"),s=new n({credentials:{accessKeyId:(e==null?void 0:e.aws_access_key)||process.env.AWS_ACCESS_KEY_ID,secretAccessKey:(e==null?void 0:e.aws_secret_key)||process.env.AWS_SECRET_ACCESS_KEY,sessionToken:(e==null?void 0:e.aws_session_token)||process.env.AWS_SESSION_TOKEN},region:(e==null?void 0:e.aws_region)||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"});if(e!=null&&e.stream){delete e.stream;let a=new r(_({},e));return yield s.send(a)}else{e==null||delete e.stream;let a=new o(_({},e));return yield s.send(a)}}),Je=(t,e)=>m(void 0,null,function*(){let{AnthropicBedrock:n}=yield import("@anthropic-ai/bedrock-sdk"),o=new n({awsAccessKey:e.aws_access_key,awsSecretKey:e.aws_secret_key,awsRegion:e.aws_region,awsSessionToken:e.aws_session_token,baseURL:e.base_url}),r=Ge[t.prompt_template.type];return r(o,e)}),Fe=(t,e)=>m(void 0,null,function*(){let{Mistral:n}=yield import("@mistralai/mistralai"),o=new n({apiKey:process.env.MISTRAL_API_KEY});return e=K(e,new Set),e!=null&&e.stream?(delete e.stream,yield o.chat.stream(e)):(delete e.stream,yield o.chat.complete(e))});var M=class{constructor(e){this.create=()=>Ae(this.apiKey);this.apiKey=e}};import*as ze from"@opentelemetry/api";import{SimpleSpanProcessor as At}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Ct}from"@opentelemetry/sdk-trace-node";import{SpanKind as L,SpanStatusCode as ne}from"@opentelemetry/api";import{ExportResultCode as U}from"@opentelemetry/core";var oe=class{constructor(e,n){this.apiKey=n||process.env.PROMPTLAYER_API_KEY,this.enableTracing=e,this.url=`${P}/spans-bulk`}attributesToObject(e){return e?Object.fromEntries(Object.entries(e)):{}}spanKindToString(e){return{[L.INTERNAL]:"SpanKind.INTERNAL",[L.SERVER]:"SpanKind.SERVER",[L.CLIENT]:"SpanKind.CLIENT",[L.PRODUCER]:"SpanKind.PRODUCER",[L.CONSUMER]:"SpanKind.CONSUMER"}[e]||"SpanKind.INTERNAL"}statusCodeToString(e){return{[ne.ERROR]:"StatusCode.ERROR",[ne.OK]:"StatusCode.OK",[ne.UNSET]:"StatusCode.UNSET"}[e]||"StatusCode.UNSET"}toNanoseconds(e){return(BigInt(e[0])*BigInt(1e9)+BigInt(e[1])).toString()}export(e){if(!this.enableTracing)return Promise.resolve(U.SUCCESS);let n=e.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(s=>({name:s.name,timestamp:this.toNanoseconds(s.time),attributes:this.attributesToObject(s.attributes)})),links:o.links.map(s=>({context:s.context,attributes:this.attributesToObject(s.attributes)})),resource:{attributes:w(_({},o.resource.attributes),{"service.name":"prompt-layer-js"}),schema_url:""}}});return fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json","X-API-KEY":this.apiKey||""},body:JSON.stringify({spans:n})}).then(o=>o.ok?U.SUCCESS:(console.error(`Error exporting spans
|
|
2
|
+
HTTP error! status: ${o.status}`),U.FAILED)).catch(o=>(console.error("Error exporting spans:",o),U.FAILED))}shutdown(){return Promise.resolve()}},Ye=oe;var N=(t="promptlayer-tracer")=>ze.trace.getTracer(t),Ve=(t,e)=>{let n=new Ct,o=new Ye(t,e),r=new At(o);n.addSpanProcessor(r),n.register()};var Ot=N(),re=(t,e,n="",o="openai")=>{let r={construct:(s,a)=>{let p=Reflect.construct(s,a);return Object.defineProperties(p,{function_name:{value:n,writable:!0},provider:{value:o}}),new Proxy(p,r)},get:(s,a,p)=>{let c=s[a],i=`${Reflect.get(s,"function_name")}.${a.toString()}`;return typeof c=="object"?(Object.defineProperties(c,{function_name:{value:i,writable:!0},provider:{value:o}}),new Proxy(c,r)):typeof c=="function"?(...l)=>{var R,S,b,h;let f=new Date().toISOString(),g=Reflect.get(s,"provider"),y=(R=l[0])==null?void 0:R.return_pl_id,u=(S=l[0])==null?void 0:S.pl_tags;return(b=l[0])==null||delete b.return_pl_id,(h=l[0])==null||delete h.pl_tags,Ot.startActiveSpan(`${g}.${i}`,d=>m(void 0,null,function*(){try{d.setAttribute("function_input",JSON.stringify(l));let T=Reflect.apply(c,s,l),k=d.spanContext().spanId;return T instanceof Promise?new Promise((J,F)=>{T.then(C=>m(void 0,null,function*(){let q=yield Te(t,{api_key:t,provider_type:g,function_name:i,request_start_time:f,request_end_time:new Date().toISOString(),request_response:C,kwargs:l[0],return_pl_id:y,tags:u,span_id:k});d.setAttribute("function_output",JSON.stringify(q)),d.setAttribute("response_status","success"),d.end(),J(q)})).catch(C=>{d.recordException(C),d.setAttribute("response_status","error"),d.end(),F(C)})}):(d.setAttribute("function_output",JSON.stringify(T)),d.setAttribute("response_status","success"),d.end(),T)}catch(T){throw d.recordException(T),d.setAttribute("response_status","error"),d.end(),T}}))}:Reflect.get(s,a,p)}};return new Proxy(e,r)};import*as j from"@opentelemetry/api";var He=(t,e,n)=>function(...o){let r=N(),s=a=>{try{n&&Object.entries(n).forEach(([c,i])=>{a.setAttribute(c,i)}),a.setAttribute("function_input",JSON.stringify(o));let p=e(...o);return p instanceof Promise?p.then(c=>(a.setAttribute("function_output",JSON.stringify(c)),a.setStatus({code:j.SpanStatusCode.OK}),c)).catch(c=>{throw Xe(a,c,o),c}).finally(()=>a.end()):(a.setAttribute("function_output",JSON.stringify(p)),a.setStatus({code:j.SpanStatusCode.OK}),a.end(),p)}catch(p){throw Xe(a,p,o),p}};return r.startActiveSpan(t,s)},Xe=(t,e,n)=>{t.setAttribute("function_input",JSON.stringify(n)),t.setStatus({code:j.SpanStatusCode.ERROR,message:e instanceof Error?e.message:"Unknown error"}),t.end()};var D=class{constructor(e){this.get=(e,n)=>Ce(this.apiKey,e,n);this.publish=e=>Oe(this.apiKey,e);this.all=e=>Ie(this.apiKey,e);this.apiKey=e}};var It=(t,e)=>{if(!(e.metadata instanceof Object))throw new Error("Please provide a dictionary of metadata.");for(let[n,o]of Object.entries(e.metadata))if(typeof n!="string"||typeof o!="string")throw new Error("Please provide a dictionary of metadata with key value pair of strings.");return be(t,e)},xt=(t,e)=>{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 Se(t,e)},Nt=(t,e)=>{if(!(e.prompt_input_variables instanceof Object))throw new Error("Prompt template input variable dictionary not provided.");return we(t,e)},kt=(t,e)=>Ee(t,e),B=class{constructor(e){this.group=e=>kt(this.apiKey,e);this.metadata=e=>It(this.apiKey,e);this.prompt=e=>Nt(this.apiKey,e);this.score=e=>xt(this.apiKey,e);this.apiKey=e}};import*as Qe from"@opentelemetry/api";var qt={openai:Le,anthropic:We,"openai.azure":ve,google:te,vertexai:De,"amazon.bedrock":Be,"anthropic.bedrock":Je,mistral:Fe},Lt=t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=["status","value","error_message","raw_error_message","is_output_node"];return Object.values(t).every(o=>typeof o!="object"||o===null?!1:e.every(r=>r in o))},Ze=class{constructor({apiKey:e=process.env.PROMPTLAYER_API_KEY,enableTracing:n=!1}={}){if(e===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=e,this.enableTracing=n,this.templates=new D(e),this.group=new M(e),this.track=new B(e),this.wrapWithSpan=He,n&&Ve(n,e)}get Anthropic(){try{let e=I("@anthropic-ai/sdk").default;return re(this.apiKey,e,"anthropic","anthropic")}catch(e){console.error("To use the Anthropic module, you must install the @anthropic-ai/sdk package.")}}get OpenAI(){try{let e=I("openai").default;return re(this.apiKey,e,"openai","openai")}catch(e){console.error("To use the OpenAI module, you must install the @openai/api package.")}}run(g){return m(this,arguments,function*({promptName:e,promptVersion:n,promptReleaseLabel:o,inputVariables:r,tags:s,metadata:a,groupId:p,modelParameterOverrides:c,stream:i=!1,provider:l,model:f}){return N().startActiveSpan("PromptLayer Run",u=>m(this,null,function*(){try{let R={promptName:e,promptVersion:n,promptReleaseLabel:o,inputVariables:r,tags:s,metadata:a,groupId:p,modelParameterOverrides:c,stream:i};u.setAttribute("function_input",JSON.stringify(R));let S=r,b={label:o,version:n,metadata_filters:a,provider:l,model:f,model_parameter_overrides:c};r&&(b.input_variables=r);let h=yield this.templates.get(e,b);if(!h)throw new Error("Prompt not found");let d=h.prompt_template;h.llm_kwargs||console.warn(`Prompt '${e}' does not have any LLM kwargs associated with it. Please set your model parameters in the registry in the PromptLayer dashbaord.`);let T=h.metadata;if(!T)throw new Error(`Prompt '${e}' does not have any metadata associated with it.`);let k=T.model;if(!k)throw new Error(`Prompt '${e}' does not have a model parameters associated with it.`);let J=h.custom_provider,F=new Date().toISOString(),{provider_type:C,kwargs:q}=Ue(h,J,c,i),Y=C;k.name.startsWith("gemini")?Y="google":k.name.startsWith("claude")&&(Y="anthropic");let et=je(Y,d),{function_name:tt,stream_function:nt}=et,se=qt[C];if(!se)throw new Error(`No request function found for provider: ${C}`);let z=yield se(h,q),ae=ot=>{let rt=new Date().toISOString();return Ne(_({function_name:tt,provider_type:C,args:[],kwargs:q,tags:s,request_start_time:F,request_end_time:rt,api_key:this.apiKey,metadata:a,prompt_id:h.id,prompt_version:h.version,prompt_input_variables:S,group_id:p,return_prompt_blueprint:!0,span_id:u.spanContext().spanId},ot))};if(i)return ke(z,ae,nt,a||h.metadata);let ie=yield ae({request_response:z}),ce={request_id:ie.request_id,raw_response:z,prompt_blueprint:ie.prompt_blueprint};return u.setAttribute("function_output",JSON.stringify(ce)),ce}catch(R){throw u.setStatus({code:Qe.SpanStatusCode.ERROR,message:R instanceof Error?R.message:"Unknown error"}),R}finally{u.end()}}))})}runWorkflow(p){return m(this,arguments,function*({workflowName:e,inputVariables:n={},metadata:o={},workflowLabelName:r=null,workflowVersion:s=null,returnAllOutputs:a=!1}){try{let c=yield xe({workflow_name:e,input_variables:n,metadata:o,workflow_label_name:r,workflow_version_number:s,return_all_outputs:a,api_key:this.apiKey});if(!a&&Lt(c)){let l=Object.values(c).filter(g=>g.is_output_node===!0);if(l.length===0)throw new Error(JSON.stringify(c,null,2));if(!l.some(g=>g.status==="SUCCESS"))throw new Error(JSON.stringify(c,null,2))}return c}catch(c){throw c instanceof Error?(console.error("Error running workflow:",c.message),new Error(`Error running workflow: ${c.message}`)):(console.error("Unknown error running workflow:",c),new Error("Unknown error running workflow"))}})}logRequest(e){return m(this,null,function*(){return Ke(this.apiKey,e)})}};export{Ze as PromptLayer};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|