UNPKG

azion

Version:

Azion Packages for Edge Computing.

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