UNPKG

azion

Version:

Azion Packages for Edge Computing.

3 lines (2 loc) 1.99 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const f="https://ai.azion.com/copilot/chat/completions",m=async(e,r)=>{const o=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return o.json()},y=async function*(e,r){const o=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${e}`},body:JSON.stringify(r)});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);const t=o.body?.getReader();if(!t)throw new Error("Response body is not readable");const n=new TextDecoder;let s="";for(;;){const{done:p,value:g}=await t.read();if(p)break;s+=n.decode(g,{stream:!0});const d=s.split(` `);s=d.pop()||"";for(const l of d)if(l.startsWith("data: ")){const h=l.slice(6);if(h==="[DONE]")return;yield JSON.parse(h)}}},w=process.env.AZION_DEBUG&&process.env.AZION_DEBUG==="true",a=e=>e??process.env.AZION_TOKEN??"",c=e=>e??!!w,i=async(e,r,o)=>{try{const t=await m(e,{...r,stream:!1});return o?.debug&&console.log("AI Chat Response:",t),{data:t,error:null}}catch(t){return o?.debug&&console.error("Error in AI chat:",t),{data:null,error:t instanceof Error?t:new Error("Unknown error occurred")}}},u=async function*(e,r,o){try{const t=y(e,{...r,stream:!0});for await(const n of t)o?.debug&&console.log("AI Stream Chunk:",n),yield{data:n,error:null}}catch(t){o?.debug&&console.error("Error in AI stream chat:",t),yield{data:null,error:t instanceof Error?t:new Error("Unknown error occurred")}}},C=(e,r)=>i(a(),e,{...r,debug:c(r?.debug)}),E=(e,r)=>u(a(),e,{...r,debug:c(r?.debug)}),b=e=>{const r=a(e?.token),o=c(e?.options?.debug);return{chat:(t,n)=>i(r,t,{...e?.options,...n,debug:o}),streamChat:(t,n)=>u(r,t,{...e?.options,...n,debug:o})}};exports.chat=C;exports.chatMethod=i;exports.createClient=b;exports.default=b;exports.streamChat=E;exports.streamChatMethod=u;