vue-llm 0.4.0 → 1.0.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/dist/index.js CHANGED
@@ -1,483 +1,724 @@
1
- import { ref as C, computed as R, onScopeDispose as I, toValue as N } from "vue";
2
- class P {
3
- constructor(r, e, t) {
4
- this.messages = r, this.status = e, this.generateId = t;
1
+ import { ref as x, watch as V, computed as A, onScopeDispose as L, toValue as N } from "vue";
2
+ import { c as q } from "./file-x_kW7BHa.js";
3
+ import { f as de } from "./file-x_kW7BHa.js";
4
+ import { L as J } from "./errors-B3A_zmVE.js";
5
+ class U {
6
+ constructor(t, e, a) {
7
+ this.messages = t, this.status = e, this.generateId = a;
5
8
  }
6
9
  messages;
7
10
  status;
8
11
  generateId;
9
- async processStream(r, e, t) {
12
+ async processStream(t, e, a) {
10
13
  this.status.value = "streaming";
11
- const s = this.getOrCreateAssistantMessage(), i = /* @__PURE__ */ new Map(), o = [];
12
- let n = "stop", p;
13
- const g = r.getReader();
14
+ const o = this.getOrCreateAssistantMessage(), s = /* @__PURE__ */ new Map(), l = [];
15
+ let u = "stop", i;
16
+ const v = t.getReader();
14
17
  try {
15
18
  for (; !e.aborted; ) {
16
- const { done: m, value: v } = await g.read();
17
- if (m) break;
18
- if (this.applyChunk(s, v, i), v.type === "tool-call-end") {
19
- const S = i.get(v.toolCallId) ?? "{}";
20
- let w;
19
+ const { done: d, value: f } = await v.read();
20
+ if (d) break;
21
+ if (this.applyChunk(o, f, s), f.type === "tool-call-end") {
22
+ const y = s.get(f.toolCallId) ?? "{}";
23
+ let m;
21
24
  try {
22
- w = JSON.parse(S);
25
+ m = JSON.parse(y);
23
26
  } catch {
24
- w = S;
27
+ m = y;
25
28
  }
26
- const y = { toolCallId: v.toolCallId, toolName: this.getToolName(s, v.toolCallId), args: w };
27
- if (o.push(y), t.onToolCall) {
28
- const d = this.findToolCallPart(s, v.toolCallId);
29
- d && (d.state = "running", d.args = w), this.triggerReactivity();
29
+ const h = { toolCallId: f.toolCallId, toolName: this.getToolName(o, f.toolCallId), args: m };
30
+ if (l.push(h), a.onToolCall) {
31
+ const g = this.findToolCallPart(o, f.toolCallId);
32
+ g && (g.state = "running", g.args = m), this.triggerReactivity();
30
33
  try {
31
- const b = await t.onToolCall(y);
32
- b !== void 0 && d && (d.state = "result", d.result = b, this.triggerReactivity());
34
+ const b = await a.onToolCall(h);
35
+ b !== void 0 && g && (g.state = "result", g.result = b, this.triggerReactivity());
33
36
  } catch (b) {
34
- d && (d.state = "error", d.error = b instanceof Error ? b.message : String(b), this.triggerReactivity());
37
+ g && (g.state = "error", g.error = b instanceof Error ? b.message : String(b), this.triggerReactivity());
35
38
  }
36
39
  }
37
40
  }
38
- if (v.type === "finish" && (n = v.finishReason, p = v.usage), v.type === "error")
39
- throw v.error;
41
+ if (f.type === "finish" && (u = f.finishReason, i = f.usage), f.type === "error")
42
+ throw f.error;
40
43
  this.triggerReactivity();
41
44
  }
42
- } catch (m) {
45
+ } catch (d) {
43
46
  if (!e.aborted) {
44
- const v = m instanceof Error ? m : new Error(String(m));
45
- throw t.onError?.(v), v;
47
+ const f = d instanceof Error ? d : new Error(String(d));
48
+ throw a.onError?.(f), f;
46
49
  }
47
50
  } finally {
48
- g.releaseLock();
51
+ v.releaseLock();
49
52
  }
50
- return this.finalizeTextParts(s), this.triggerReactivity(), t.onFinish?.(s, { finishReason: n, usage: p }), { finishReason: n, usage: p, toolCalls: o };
53
+ return this.finalizeTextParts(o), this.triggerReactivity(), a.onFinish?.(o, { finishReason: u, usage: i }), { finishReason: u, usage: i, toolCalls: l };
51
54
  }
52
55
  getOrCreateAssistantMessage() {
53
- const r = this.messages.value, e = r[r.length - 1];
56
+ const t = this.messages.value, e = t[t.length - 1];
54
57
  if (e?.role === "assistant") return e;
55
- const t = {
58
+ const a = {
56
59
  id: this.generateId(),
57
60
  role: "assistant",
58
61
  parts: [],
59
62
  createdAt: /* @__PURE__ */ new Date()
60
63
  };
61
- return r.push(t), t;
64
+ return t.push(a), a;
62
65
  }
63
- applyChunk(r, e, t) {
66
+ applyChunk(t, e, a) {
64
67
  switch (e.type) {
65
68
  case "text-delta": {
66
- const s = r.parts[r.parts.length - 1];
67
- s?.type === "text" && s.state === "streaming" ? s.text += e.text : r.parts.push({ type: "text", text: e.text, state: "streaming" });
69
+ const o = t.parts[t.parts.length - 1];
70
+ o?.type === "text" && o.state === "streaming" ? o.text += e.text : t.parts.push({ type: "text", text: e.text, state: "streaming" });
68
71
  break;
69
72
  }
70
73
  case "reasoning-delta": {
71
- const s = r.parts[r.parts.length - 1];
72
- s?.type === "reasoning" && s.state === "streaming" ? s.text += e.text : r.parts.push({ type: "reasoning", text: e.text, state: "streaming" });
74
+ const o = t.parts[t.parts.length - 1];
75
+ o?.type === "reasoning" && o.state === "streaming" ? o.text += e.text : t.parts.push({ type: "reasoning", text: e.text, state: "streaming" });
73
76
  break;
74
77
  }
75
78
  case "tool-call-start":
76
- r.parts.push({
79
+ t.parts.push({
77
80
  type: "tool-call",
78
81
  toolCallId: e.toolCallId,
79
82
  toolName: e.toolName,
80
83
  args: void 0,
81
84
  state: "pending"
82
- }), t.set(e.toolCallId, "");
85
+ }), a.set(e.toolCallId, "");
83
86
  break;
84
87
  case "tool-call-delta":
85
- t.set(
88
+ a.set(
86
89
  e.toolCallId,
87
- (t.get(e.toolCallId) ?? "") + e.args
90
+ (a.get(e.toolCallId) ?? "") + e.args
88
91
  );
89
92
  break;
90
93
  }
91
94
  }
92
- finalizeTextParts(r) {
93
- for (const e of r.parts)
95
+ finalizeTextParts(t) {
96
+ for (const e of t.parts)
94
97
  (e.type === "text" || e.type === "reasoning") && e.state === "streaming" && (e.state = "done");
95
98
  }
96
- findToolCallPart(r, e) {
97
- return r.parts.find(
98
- (t) => t.type === "tool-call" && t.toolCallId === e
99
+ findToolCallPart(t, e) {
100
+ return t.parts.find(
101
+ (a) => a.type === "tool-call" && a.toolCallId === e
99
102
  );
100
103
  }
101
- getToolName(r, e) {
102
- return this.findToolCallPart(r, e)?.toolName ?? "";
104
+ getToolName(t, e) {
105
+ return this.findToolCallPart(t, e)?.toolName ?? "";
103
106
  }
104
107
  triggerReactivity() {
105
108
  this.messages.value = [...this.messages.value];
106
109
  }
107
110
  }
108
- const T = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
109
- function O(a = 16) {
110
- const r = crypto.getRandomValues(new Uint8Array(a));
111
+ const j = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
112
+ function I(r = 16) {
113
+ const t = crypto.getRandomValues(new Uint8Array(r));
111
114
  let e = "";
112
- for (let t = 0; t < a; t++)
113
- e += T[r[t] % T.length];
115
+ for (let a = 0; a < r; a++)
116
+ e += j[t[a] % j.length];
114
117
  return e;
115
118
  }
116
- function j(a) {
117
- const r = a.id ?? O(), e = C(a.initialMessages ?? []), t = C("ready"), s = C(void 0), i = C("");
118
- let o = null;
119
- const n = new P(e, t, O), p = () => {
120
- const l = [];
121
- a.system && l.push({ role: "system", content: a.system });
122
- for (const f of e.value) {
123
- if (f.role === "system") continue;
124
- const c = f.parts.filter((h) => h.type === "text").map((h) => h.text).join(""), E = f.parts.filter((h) => h.type === "tool-call").map((h) => ({ id: h.toolCallId, name: h.toolName, args: h.args }));
125
- if (f.role === "user")
126
- l.push({ role: "user", content: c });
127
- else if (f.role === "assistant") {
128
- l.push({
119
+ function Q(r) {
120
+ const t = r.id ?? I(), e = x(r.initialMessages ?? []), a = x("ready"), o = x(void 0), s = x("");
121
+ let l = null;
122
+ const u = x(!r.storage), i = r.storage, v = (n) => {
123
+ r.onError?.(n instanceof Error ? n : new Error(String(n)));
124
+ };
125
+ if (i) {
126
+ const n = e.value, C = (c) => {
127
+ c?.length && e.value === n && (e.value = c), u.value = !0;
128
+ };
129
+ try {
130
+ const c = i.load(t);
131
+ c instanceof Promise ? c.then(C, (p) => {
132
+ v(p), u.value = !0;
133
+ }) : C(c);
134
+ } catch (c) {
135
+ v(c), u.value = !0;
136
+ }
137
+ V([e, a, u], () => {
138
+ if (!(!u.value || a.value === "submitted" || a.value === "streaming"))
139
+ try {
140
+ const c = e.value.length > 0 ? i.save(t, e.value) : i.remove(t);
141
+ c instanceof Promise && c.catch(v);
142
+ } catch (c) {
143
+ v(c);
144
+ }
145
+ }, { deep: !0 });
146
+ }
147
+ const d = new U(e, a, I), f = () => {
148
+ const n = [], C = [
149
+ N(r.system),
150
+ ...e.value.filter((c) => c.role === "system").map((c) => c.parts.filter((p) => p.type === "text").map((p) => p.text).join(""))
151
+ ].filter(Boolean);
152
+ C.length > 0 && n.push({ role: "system", content: C.join(`
153
+
154
+ `) });
155
+ for (const c of e.value) {
156
+ if (c.role === "system") continue;
157
+ const E = c.parts.filter((w) => w.type === "text").map((w) => w.text).join(""), S = c.parts.filter((w) => w.type === "tool-call").map((w) => ({ id: w.toolCallId, name: w.toolName, args: w.args }));
158
+ if (c.role === "user") {
159
+ const w = c.parts.filter((O) => O.type === "file");
160
+ if (w.length === 0) {
161
+ n.push({ role: "user", content: E });
162
+ continue;
163
+ }
164
+ const D = w.map((O) => ({
165
+ type: "file",
166
+ url: O.url,
167
+ mediaType: O.mediaType,
168
+ filename: O.filename
169
+ }));
170
+ E && D.push({ type: "text", text: E }), n.push({ role: "user", content: D });
171
+ } else if (c.role === "assistant") {
172
+ n.push({
129
173
  role: "assistant",
130
- content: c,
131
- toolCalls: E.length > 0 ? E : void 0
174
+ content: E,
175
+ toolCalls: S.length > 0 ? S : void 0
132
176
  });
133
- for (const h of f.parts)
134
- h.type !== "tool-call" || h.state !== "result" || l.push({
177
+ for (const w of c.parts)
178
+ w.type !== "tool-call" || w.state !== "result" || n.push({
135
179
  role: "tool",
136
- content: JSON.stringify(h.result),
137
- toolCallId: h.toolCallId
180
+ content: JSON.stringify(w.result),
181
+ toolCallId: w.toolCallId
138
182
  });
139
183
  }
140
184
  }
141
- return l;
142
- }, g = async (l) => {
143
- const f = a.maxToolRoundtrips ?? 5;
144
- let u = 0;
145
- for (; u < f; ) {
146
- const c = p();
147
- a.provider.validateConfig();
148
- const { stream: E } = await a.provider.chat({
149
- model: a.model,
150
- messages: c,
151
- tools: a.tools,
152
- signal: l,
185
+ return n;
186
+ }, y = async (n) => {
187
+ const C = r.maxToolRoundtrips ?? 5;
188
+ let c = 0;
189
+ for (; c < C; ) {
190
+ const p = f();
191
+ r.provider.validateConfig();
192
+ const { stream: E } = await r.provider.chat({
193
+ model: r.model,
194
+ messages: p,
195
+ tools: r.tools,
196
+ signal: n,
153
197
  providerOptions: {
154
- ...a.providerOptions,
155
- ...N(a.body)
198
+ ...r.providerOptions,
199
+ ...N(r.body)
156
200
  }
157
- }), h = await n.processStream(E, l, {
158
- onFinish: a.onFinish,
159
- onError: a.onError,
160
- onToolCall: a.onToolCall
201
+ }), S = await d.processStream(E, n, {
202
+ onFinish: r.onFinish,
203
+ onError: r.onError,
204
+ onToolCall: r.onToolCall
161
205
  });
162
- if (h.finishReason !== "tool-calls" || h.toolCalls.length === 0)
206
+ if (S.finishReason !== "tool-calls" || S.toolCalls.length === 0)
163
207
  break;
164
- u++;
208
+ c++;
165
209
  }
166
- }, m = async (l) => {
167
- const f = typeof l == "string" ? l : l?.text ?? i.value;
168
- if (!f.trim()) return;
169
- (typeof l != "object" || l === null || !("text" in l)) && (i.value = "");
170
- const u = {
171
- id: O(),
210
+ }, m = async (n) => {
211
+ const C = typeof n == "string" ? n : n?.text ?? s.value;
212
+ let c;
213
+ try {
214
+ c = typeof n == "object" ? await q(n.files) : [];
215
+ } catch (S) {
216
+ o.value = S instanceof Error ? S : new Error(String(S)), a.value = "error";
217
+ return;
218
+ }
219
+ if (!C.trim() && c.length === 0) return;
220
+ (typeof n != "object" || n === null || !("text" in n)) && (s.value = "");
221
+ const p = [...c];
222
+ C.trim() && p.push({ type: "text", text: C, state: "done" });
223
+ const E = {
224
+ id: I(),
172
225
  role: "user",
173
- parts: [{ type: "text", text: f, state: "done" }],
226
+ parts: p,
174
227
  createdAt: /* @__PURE__ */ new Date()
175
228
  };
176
- e.value = [...e.value, u], s.value = void 0, t.value = "submitted", o?.abort(), o = new AbortController();
229
+ e.value = [...e.value, E], o.value = void 0, a.value = "submitted", l?.abort(), l = new AbortController();
177
230
  try {
178
- await g(o.signal), t.value = "ready";
179
- } catch (c) {
180
- if (o.signal.aborted) {
181
- t.value = "ready";
231
+ await y(l.signal), a.value = "ready";
232
+ } catch (S) {
233
+ if (l.signal.aborted) {
234
+ a.value = "ready";
182
235
  return;
183
236
  }
184
- s.value = c instanceof Error ? c : new Error(String(c)), t.value = "error";
237
+ o.value = S instanceof Error ? S : new Error(String(S)), a.value = "error";
185
238
  }
186
- }, v = async () => {
187
- const l = e.value, f = l.reduce((u, c, E) => c.role === "assistant" ? E : u, -1);
188
- if (f !== -1) {
189
- e.value = l.slice(0, f), s.value = void 0, t.value = "submitted", o?.abort(), o = new AbortController();
239
+ }, h = async () => {
240
+ const n = e.value, C = n.reduce((c, p, E) => p.role === "assistant" ? E : c, -1);
241
+ if (C !== -1) {
242
+ e.value = n.slice(0, C), o.value = void 0, a.value = "submitted", l?.abort(), l = new AbortController();
190
243
  try {
191
- await g(o.signal), t.value = "ready";
192
- } catch (u) {
193
- if (o.signal.aborted) {
194
- t.value = "ready";
244
+ await y(l.signal), a.value = "ready";
245
+ } catch (c) {
246
+ if (l.signal.aborted) {
247
+ a.value = "ready";
195
248
  return;
196
249
  }
197
- s.value = u instanceof Error ? u : new Error(String(u)), t.value = "error";
250
+ o.value = c instanceof Error ? c : new Error(String(c)), a.value = "error";
198
251
  }
199
252
  }
200
- }, S = () => {
201
- o?.abort(), o = null, t.value = "ready";
202
- }, w = (l) => {
203
- e.value = typeof l == "function" ? l(e.value) : l;
204
- }, y = (l) => {
205
- l?.preventDefault?.(), i.value.trim() && m();
206
- }, d = R(() => t.value === "submitted" || t.value === "streaming"), b = ({ toolCallId: l, result: f }) => {
207
- for (const u of e.value)
208
- for (const c of u.parts)
209
- if (c.type === "tool-call" && c.toolCallId === l) {
210
- c.state = "result", c.result = f, e.value = [...e.value];
253
+ }, g = () => {
254
+ l?.abort(), l = null, a.value = "ready";
255
+ }, b = (n) => {
256
+ e.value = typeof n == "function" ? n(e.value) : n;
257
+ }, R = (n) => {
258
+ n?.preventDefault?.(), s.value.trim() && m();
259
+ }, T = A(() => a.value === "submitted" || a.value === "streaming"), P = ({ toolCallId: n, result: C }) => {
260
+ for (const c of e.value)
261
+ for (const p of c.parts)
262
+ if (p.type === "tool-call" && p.toolCallId === n) {
263
+ p.state = "result", p.result = C, e.value = [...e.value];
211
264
  return;
212
265
  }
213
- }, x = () => {
214
- s.value = void 0, t.value === "error" && (t.value = "ready");
266
+ }, M = () => {
267
+ o.value = void 0, a.value === "error" && (a.value = "ready");
215
268
  };
216
- return I(() => {
217
- o?.abort();
269
+ return L(() => {
270
+ l?.abort();
218
271
  }), {
219
272
  messages: e,
220
- status: R(() => t.value),
221
- error: s,
222
- id: r,
223
- input: i,
273
+ status: A(() => a.value),
274
+ error: o,
275
+ id: t,
276
+ input: s,
224
277
  sendMessage: m,
225
- regenerate: v,
226
- stop: S,
227
- setMessages: w,
228
- handleSubmit: y,
229
- isLoading: d,
230
- addToolResult: b,
231
- clearError: x
278
+ regenerate: h,
279
+ stop: g,
280
+ setMessages: b,
281
+ handleSubmit: R,
282
+ isLoading: T,
283
+ addToolResult: P,
284
+ clearError: M,
285
+ isRestored: A(() => u.value)
232
286
  };
233
287
  }
234
- function J(a) {
235
- const r = a.id ?? O(), e = C(""), t = C("ready"), s = C(void 0), i = C("");
236
- let o = null;
237
- const n = async (S) => {
238
- const w = S ?? i.value;
239
- if (!w.trim()) return e.value;
240
- S || (i.value = ""), e.value = "", s.value = void 0, t.value = "submitted", o?.abort(), o = new AbortController();
288
+ function X(r) {
289
+ const t = r.id ?? I(), e = x(""), a = x("ready"), o = x(void 0), s = x("");
290
+ let l = null;
291
+ const u = async (y) => {
292
+ const m = y ?? s.value;
293
+ if (!m.trim()) return e.value;
294
+ y || (s.value = ""), e.value = "", o.value = void 0, a.value = "submitted", l?.abort(), l = new AbortController();
241
295
  try {
242
- a.provider.validateConfig();
243
- const y = a.system ? [
244
- { role: "system", content: a.system },
245
- { role: "user", content: w }
246
- ] : [{ role: "user", content: w }], { stream: d } = await a.provider.chat({
247
- model: a.model,
248
- messages: y,
249
- signal: o.signal
296
+ r.provider.validateConfig();
297
+ const h = N(r.system), g = h ? [
298
+ { role: "system", content: h },
299
+ { role: "user", content: m }
300
+ ] : [{ role: "user", content: m }], { stream: b } = await r.provider.chat({
301
+ model: r.model,
302
+ messages: g,
303
+ signal: l.signal
250
304
  });
251
- t.value = "streaming";
252
- const b = d.getReader();
253
- let x = "stop", l;
254
- for (; !o.signal.aborted; ) {
255
- const { done: f, value: u } = await b.read();
256
- if (f) break;
257
- if (u.type === "text-delta")
258
- e.value += u.text;
259
- else if (u.type === "finish")
260
- x = u.finishReason, l = u.usage;
261
- else if (u.type === "error")
262
- throw u.error;
305
+ a.value = "streaming";
306
+ const R = b.getReader();
307
+ let T = "stop", P;
308
+ for (; !l.signal.aborted; ) {
309
+ const { done: M, value: n } = await R.read();
310
+ if (M) break;
311
+ if (n.type === "text-delta")
312
+ e.value += n.text;
313
+ else if (n.type === "finish")
314
+ T = n.finishReason, P = n.usage;
315
+ else if (n.type === "error")
316
+ throw n.error;
263
317
  }
264
- return b.releaseLock(), t.value = "ready", a.onFinish?.(e.value, { finishReason: x, usage: l }), e.value;
265
- } catch (y) {
266
- if (!o || o.signal.aborted)
267
- return t.value = "ready", e.value;
268
- const d = y instanceof Error ? y : new Error(String(y));
269
- return s.value = d, t.value = "error", a.onError?.(d), e.value;
318
+ return R.releaseLock(), a.value = "ready", r.onFinish?.(e.value, { finishReason: T, usage: P }), e.value;
319
+ } catch (h) {
320
+ if (!l || l.signal.aborted)
321
+ return a.value = "ready", e.value;
322
+ const g = h instanceof Error ? h : new Error(String(h));
323
+ return o.value = g, a.value = "error", r.onError?.(g), e.value;
270
324
  }
271
- }, p = () => {
272
- o?.abort(), o = null, t.value = "ready";
273
- }, g = () => {
274
- s.value = void 0, t.value === "error" && (t.value = "ready");
275
- }, m = (S) => {
276
- S?.preventDefault?.(), i.value.trim() && n();
277
- }, v = R(() => t.value === "submitted" || t.value === "streaming");
278
- return I(() => {
279
- o?.abort();
325
+ }, i = () => {
326
+ l?.abort(), l = null, a.value = "ready";
327
+ }, v = () => {
328
+ o.value = void 0, a.value === "error" && (a.value = "ready");
329
+ }, d = (y) => {
330
+ y?.preventDefault?.(), s.value.trim() && u();
331
+ }, f = A(() => a.value === "submitted" || a.value === "streaming");
332
+ return L(() => {
333
+ l?.abort();
280
334
  }), {
281
335
  completion: e,
282
- status: R(() => t.value),
283
- error: s,
284
- isLoading: v,
285
- id: r,
286
- input: i,
287
- complete: n,
288
- stop: p,
289
- clearError: g,
290
- handleSubmit: m
336
+ status: A(() => a.value),
337
+ error: o,
338
+ isLoading: f,
339
+ id: t,
340
+ input: s,
341
+ complete: u,
342
+ stop: i,
343
+ clearError: v,
344
+ handleSubmit: d
291
345
  };
292
346
  }
293
- function F(a) {
294
- const r = a.id ?? O(), e = C(void 0), t = C(void 0), s = C("ready"), i = C(void 0), o = C("");
295
- let n = null;
296
- const p = async (S) => {
297
- const w = S ?? o.value;
298
- if (!w.trim()) return e.value;
299
- S || (o.value = ""), e.value = void 0, t.value = void 0, i.value = void 0, s.value = "submitted", n?.abort(), n = new AbortController();
347
+ function ee(r) {
348
+ const t = r.id ?? I(), e = x(void 0), a = x(void 0), o = x("ready"), s = x(void 0), l = x("");
349
+ let u = null;
350
+ const i = async (y) => {
351
+ const m = y ?? l.value;
352
+ if (!m.trim()) return e.value;
353
+ y || (l.value = ""), e.value = void 0, a.value = void 0, s.value = void 0, o.value = "submitted", u?.abort(), u = new AbortController();
300
354
  try {
301
- a.provider.validateConfig();
302
- const y = [
303
- a.system ?? "",
355
+ r.provider.validateConfig();
356
+ const h = [
357
+ N(r.system) ?? "",
304
358
  "Respond with valid JSON matching this schema:",
305
- JSON.stringify(a.schema, null, 2),
359
+ JSON.stringify(r.schema, null, 2),
306
360
  "Output ONLY the JSON object, no other text."
307
361
  ].filter(Boolean).join(`
308
362
 
309
- `), { stream: d } = await a.provider.chat({
310
- model: a.model,
363
+ `), { stream: g } = await r.provider.chat({
364
+ model: r.model,
311
365
  messages: [
312
- { role: "system", content: y },
313
- { role: "user", content: w }
366
+ { role: "system", content: h },
367
+ { role: "user", content: m }
314
368
  ],
315
- signal: n.signal,
369
+ signal: u.signal,
316
370
  providerOptions: {
317
371
  response_format: { type: "json_object" }
318
372
  }
319
373
  });
320
- s.value = "streaming";
321
- const b = d.getReader();
322
- let x = "", l = "stop", f;
323
- for (; !n.signal.aborted; ) {
324
- const { done: u, value: c } = await b.read();
325
- if (u) break;
326
- if (c.type === "text-delta") {
327
- x += c.text;
374
+ o.value = "streaming";
375
+ const b = g.getReader();
376
+ let R = "", T = "stop", P;
377
+ for (; !u.signal.aborted; ) {
378
+ const { done: M, value: n } = await b.read();
379
+ if (M) break;
380
+ if (n.type === "text-delta") {
381
+ R += n.text;
328
382
  try {
329
- t.value = M(x);
383
+ a.value = _(R);
330
384
  } catch {
331
385
  }
332
- } else if (c.type === "finish")
333
- l = c.finishReason, f = c.usage;
334
- else if (c.type === "error")
335
- throw c.error;
386
+ } else if (n.type === "finish")
387
+ T = n.finishReason, P = n.usage;
388
+ else if (n.type === "error")
389
+ throw n.error;
336
390
  }
337
391
  b.releaseLock();
338
392
  try {
339
- e.value = JSON.parse(x), t.value = e.value;
393
+ e.value = JSON.parse(R), a.value = e.value;
340
394
  } catch {
341
- throw new Error(`Failed to parse JSON response: ${x.slice(0, 200)}`);
395
+ throw new Error(`Failed to parse JSON response: ${R.slice(0, 200)}`);
342
396
  }
343
- return s.value = "ready", a.onFinish?.(e.value, { finishReason: l, usage: f }), e.value;
344
- } catch (y) {
345
- if (n.signal.aborted)
346
- return s.value = "ready", e.value;
347
- const d = y instanceof Error ? y : new Error(String(y));
348
- i.value = d, s.value = "error", a.onError?.(d);
397
+ return o.value = "ready", r.onFinish?.(e.value, { finishReason: T, usage: P }), e.value;
398
+ } catch (h) {
399
+ if (u.signal.aborted)
400
+ return o.value = "ready", e.value;
401
+ const g = h instanceof Error ? h : new Error(String(h));
402
+ s.value = g, o.value = "error", r.onError?.(g);
349
403
  return;
350
404
  }
351
- }, g = () => {
352
- n?.abort(), n = null, s.value = "ready";
353
- }, m = () => {
354
- i.value = void 0, s.value === "error" && (s.value = "ready");
355
- }, v = R(() => s.value === "submitted" || s.value === "streaming");
356
- return I(() => {
357
- n?.abort();
405
+ }, v = () => {
406
+ u?.abort(), u = null, o.value = "ready";
407
+ }, d = () => {
408
+ s.value = void 0, o.value === "error" && (o.value = "ready");
409
+ }, f = A(() => o.value === "submitted" || o.value === "streaming");
410
+ return L(() => {
411
+ u?.abort();
358
412
  }), {
359
413
  object: e,
360
- partialObject: t,
361
- status: R(() => s.value),
362
- error: i,
363
- isLoading: v,
364
- id: r,
365
- input: o,
366
- submit: p,
367
- stop: g,
368
- clearError: m
414
+ partialObject: a,
415
+ status: A(() => o.value),
416
+ error: s,
417
+ isLoading: f,
418
+ id: t,
419
+ input: l,
420
+ submit: i,
421
+ stop: v,
422
+ clearError: d
369
423
  };
370
424
  }
371
- function M(a) {
372
- let r = a.trim();
373
- if (!r.startsWith("{")) return;
374
- let e = 0, t = !1, s = !1;
375
- for (let i = 0; i < r.length; i++) {
376
- const o = r[i];
377
- if (s) {
378
- s = !1;
425
+ function _(r) {
426
+ let t = r.trim();
427
+ if (!t.startsWith("{")) return;
428
+ let e = 0, a = !1, o = !1;
429
+ for (let s = 0; s < t.length; s++) {
430
+ const l = t[s];
431
+ if (o) {
432
+ o = !1;
379
433
  continue;
380
434
  }
381
- if (o === "\\") {
382
- s = !0;
435
+ if (l === "\\") {
436
+ o = !0;
383
437
  continue;
384
438
  }
385
- if (o === '"') {
386
- t = !t;
439
+ if (l === '"') {
440
+ a = !a;
387
441
  continue;
388
442
  }
389
- t || (o === "{" && e++, o === "}" && e--);
443
+ a || (l === "{" && e++, l === "}" && e--);
390
444
  }
391
445
  for (; e > 0; )
392
- r += "}", e--;
446
+ t += "}", e--;
393
447
  try {
394
- return JSON.parse(r);
448
+ return JSON.parse(t);
395
449
  } catch {
396
450
  return;
397
451
  }
398
452
  }
399
- function L(a, r) {
400
- return r.length ? {
401
- id: a.id,
402
- supportsStreaming: a.supportsStreaming,
453
+ const F = /(\\)?\{\{\s*([A-Za-z_][\w-]*)\s*\}\}/g;
454
+ function k(r, t = {}) {
455
+ return {
456
+ template: r,
457
+ variables: z(r),
458
+ render(e) {
459
+ return $(r, { ...t.defaults, ...e });
460
+ }
461
+ };
462
+ }
463
+ function te(r, t = {}) {
464
+ const e = (a) => {
465
+ const o = { ...t.defaults, ...a };
466
+ return r.map((s) => ({ role: s.role, content: $(s.content, o) }));
467
+ };
468
+ return {
469
+ messages: r,
470
+ variables: [...new Set(r.flatMap((a) => z(a.content)))],
471
+ render: e,
472
+ toUIMessages(a) {
473
+ return e(a).map((o) => ({
474
+ id: I(),
475
+ role: o.role,
476
+ parts: [{ type: "text", text: o.content, state: "done" }],
477
+ createdAt: /* @__PURE__ */ new Date()
478
+ }));
479
+ }
480
+ };
481
+ }
482
+ function $(r, t) {
483
+ return r.replace(F, (e, a, o) => {
484
+ if (a) return e.slice(1);
485
+ const s = t[o];
486
+ if (s == null)
487
+ throw new Error(`[vue-llm] Missing prompt variable "${o}"`);
488
+ return String(s);
489
+ });
490
+ }
491
+ function z(r) {
492
+ const t = /* @__PURE__ */ new Set();
493
+ for (const [, e, a] of r.matchAll(F))
494
+ e || t.add(a);
495
+ return [...t];
496
+ }
497
+ function re(r, t) {
498
+ const e = typeof r == "string" ? k(r) : r;
499
+ return A(() => e.render(N(t)));
500
+ }
501
+ function ae(r, t) {
502
+ return t.length ? {
503
+ id: r.id,
504
+ supportsStreaming: r.supportsStreaming,
403
505
  validateConfig() {
404
- a.validateConfig();
506
+ r.validateConfig();
405
507
  },
406
508
  async chat(e) {
407
- let t = e;
408
- for (const n of r)
409
- n.beforeRequest && (t = await n.beforeRequest(t, a));
509
+ let a = e;
510
+ for (const i of t)
511
+ i.beforeRequest && (a = await i.beforeRequest(a, r));
512
+ const o = t.reduceRight(
513
+ (i, v) => v.wrapChat ? (d) => v.wrapChat(i, d) : i,
514
+ (i) => r.chat(i)
515
+ );
410
516
  let s;
411
517
  try {
412
- s = await a.chat(t);
413
- } catch (n) {
414
- let p = n instanceof Error ? n : new Error(String(n));
415
- for (const g of r)
416
- if (g.onError) {
417
- const m = await g.onError(p, t);
418
- m instanceof Error && (p = m);
518
+ s = await o(a);
519
+ } catch (i) {
520
+ let v = i instanceof Error ? i : new Error(String(i));
521
+ for (const d of t)
522
+ if (d.onError) {
523
+ const f = await d.onError(v, a);
524
+ f instanceof Error && (v = f);
419
525
  }
420
- throw p;
526
+ throw v;
421
527
  }
422
- const o = r.some((n) => n.afterStream) ? s.stream.pipeThrough(new TransformStream({
423
- async transform(n, p) {
424
- let g = n;
425
- for (const m of r) {
426
- if (!g) break;
427
- m.afterStream && (g = await m.afterStream(g, t));
528
+ const u = t.some((i) => i.afterStream) ? s.stream.pipeThrough(new TransformStream({
529
+ async transform(i, v) {
530
+ let d = i;
531
+ for (const f of t) {
532
+ if (!d) break;
533
+ f.afterStream && (d = await f.afterStream(d, a));
428
534
  }
429
- g && p.enqueue(g);
535
+ d && v.enqueue(d);
430
536
  }
431
537
  })) : s.stream;
432
- for (const n of r)
433
- n.onFinish && n.onFinish(t, s);
434
- return { stream: o, response: s.response };
538
+ for (const i of t)
539
+ i.onFinish && i.onFinish(a, s);
540
+ return { stream: u, response: s.response };
435
541
  }
436
- } : a;
542
+ } : r;
437
543
  }
438
- function $(a = "vue-llm") {
544
+ function oe(r = "vue-llm") {
439
545
  return {
440
- beforeRequest(r) {
441
- return console.log(`[${a}] → ${r.model}`, r.messages.length, "messages"), r;
546
+ beforeRequest(t) {
547
+ return console.log(`[${r}] → ${t.model}`, t.messages.length, "messages"), t;
442
548
  },
443
- afterStream(r) {
444
- return r.type === "finish" && console.log(`[${a}] ← finish:`, r.finishReason, r.usage ?? ""), r;
549
+ afterStream(t) {
550
+ return t.type === "finish" && console.log(`[${r}] ← finish:`, t.finishReason, t.usage ?? ""), t;
445
551
  },
446
- onError(r) {
447
- console.error(`[${a}] error:`, r.message);
552
+ onError(t) {
553
+ console.error(`[${r}] error:`, t.message);
554
+ }
555
+ };
556
+ }
557
+ function ne(r = {}, t) {
558
+ const e = typeof r == "number" ? { maxRetries: r, initialDelay: t } : r, a = e.maxRetries ?? 3, o = e.initialDelay ?? 1e3, s = e.maxDelay ?? 3e4, l = e.factor ?? 2, u = e.jitter ?? !0, i = e.shouldRetry ?? W;
559
+ return {
560
+ async wrapChat(v, d) {
561
+ for (let f = 1; ; f++)
562
+ try {
563
+ return await v(d);
564
+ } catch (y) {
565
+ const m = y instanceof Error ? y : new Error(String(y));
566
+ if (f > a || d.signal?.aborted || !i(m, f))
567
+ throw m;
568
+ const h = o * l ** (f - 1), g = m instanceof J ? m.retryAfter : void 0, b = Math.min(
569
+ s,
570
+ g ?? (u ? h * (0.5 + Math.random() * 0.5) : h)
571
+ );
572
+ e.onRetry?.({ error: m, attempt: f, delay: b }), await Y(b, d.signal);
573
+ }
448
574
  }
449
575
  };
450
576
  }
451
- function D(a = 3, r = 1e3) {
577
+ function W(r) {
578
+ return r.name === "AbortError" ? !1 : r instanceof J ? r.isRetryable : r instanceof TypeError;
579
+ }
580
+ function se(r) {
581
+ const t = r.interval ?? 6e4, e = [];
582
+ let a = 0;
583
+ const o = /* @__PURE__ */ new Set(), s = () => {
584
+ a--;
585
+ for (const u of [...o]) u();
586
+ }, l = async (u) => {
587
+ for (; ; ) {
588
+ u?.throwIfAborted();
589
+ const i = Date.now();
590
+ for (; e.length > 0 && e[0] <= i - t; ) e.shift();
591
+ const v = r.maxRequests !== void 0 && e.length >= r.maxRequests, d = r.maxConcurrent !== void 0 && a >= r.maxConcurrent;
592
+ if (!v && !d) {
593
+ e.push(i), a++;
594
+ return;
595
+ }
596
+ await new Promise((f, y) => {
597
+ const m = () => {
598
+ clearTimeout(g), o.delete(m), u?.removeEventListener("abort", h), f();
599
+ }, h = () => {
600
+ m(), y(u.reason);
601
+ }, g = v ? setTimeout(m, e[0] + t - i) : void 0;
602
+ o.add(m), u?.addEventListener("abort", h, { once: !0 });
603
+ });
604
+ }
605
+ };
452
606
  return {
453
- async onError(e, t) {
454
- const s = e.message;
455
- if (!(s.includes("429") || s.includes("500") || s.includes("502") || s.includes("503"))) return e;
456
- for (let o = 0; o < a; o++)
457
- await new Promise((n) => setTimeout(n, r * (o + 1))), console.log(`[vue-llm] retry ${o + 1}/${a}`);
458
- return e;
607
+ async wrapChat(u, i) {
608
+ await l(i.signal);
609
+ let v;
610
+ try {
611
+ v = await u(i);
612
+ } catch (d) {
613
+ throw s(), d;
614
+ }
615
+ return { ...v, stream: H(v.stream, s) };
459
616
  }
460
617
  };
461
618
  }
462
- function q(a) {
619
+ function H(r, t) {
620
+ const e = r.getReader();
621
+ let a = !1;
622
+ const o = () => {
623
+ a || (a = !0, t());
624
+ };
625
+ return new ReadableStream({
626
+ async pull(s) {
627
+ try {
628
+ const { done: l, value: u } = await e.read();
629
+ l ? (o(), s.close()) : s.enqueue(u);
630
+ } catch (l) {
631
+ o(), s.error(l);
632
+ }
633
+ },
634
+ cancel(s) {
635
+ return o(), e.cancel(s);
636
+ }
637
+ });
638
+ }
639
+ function Y(r, t) {
640
+ return new Promise((e, a) => {
641
+ if (t?.aborted) return a(t.reason);
642
+ const o = setTimeout(() => {
643
+ t?.removeEventListener("abort", s), e();
644
+ }, r), s = () => {
645
+ clearTimeout(o), a(t.reason);
646
+ };
647
+ t?.addEventListener("abort", s, { once: !0 });
648
+ });
649
+ }
650
+ function le(r) {
463
651
  return {
464
- beforeRequest(r) {
652
+ beforeRequest(t) {
465
653
  return {
466
- ...r,
654
+ ...t,
467
655
  providerOptions: {
468
- ...r.providerOptions,
469
- headers: { ...r.providerOptions?.headers, ...a }
656
+ ...t.providerOptions,
657
+ headers: { ...t.providerOptions?.headers, ...r }
470
658
  }
471
659
  };
472
660
  }
473
661
  };
474
662
  }
663
+ function ie(r = {}) {
664
+ const t = r.prefix ?? "vue-llm:chat:", e = () => r.storage ? r.storage : typeof localStorage < "u" ? localStorage : void 0;
665
+ return {
666
+ load(a) {
667
+ const o = e()?.getItem(t + a);
668
+ if (!o) return null;
669
+ try {
670
+ return B(o);
671
+ } catch {
672
+ return null;
673
+ }
674
+ },
675
+ save(a, o) {
676
+ e()?.setItem(t + a, JSON.stringify(o));
677
+ },
678
+ remove(a) {
679
+ e()?.removeItem(t + a);
680
+ }
681
+ };
682
+ }
683
+ function ce() {
684
+ const r = /* @__PURE__ */ new Map();
685
+ return {
686
+ load(t) {
687
+ const e = r.get(t);
688
+ return e ? B(e) : null;
689
+ },
690
+ save(t, e) {
691
+ r.set(t, JSON.stringify(e));
692
+ },
693
+ remove(t) {
694
+ r.delete(t);
695
+ }
696
+ };
697
+ }
698
+ function B(r) {
699
+ const t = JSON.parse(r);
700
+ return Array.isArray(t) ? t.map((e) => ({
701
+ ...e,
702
+ createdAt: e.createdAt ? new Date(e.createdAt) : void 0
703
+ })) : [];
704
+ }
475
705
  export {
476
- q as headerMiddleware,
477
- $ as loggingMiddleware,
478
- D as retryMiddleware,
479
- j as useChat,
480
- J as useCompletion,
481
- F as useObject,
482
- L as wrapProvider
706
+ J as LLMAPIError,
707
+ q as convertFilesToParts,
708
+ te as createChatPrompt,
709
+ ce as createMemoryStorage,
710
+ k as createPrompt,
711
+ ie as createWebStorage,
712
+ de as fileToDataURL,
713
+ le as headerMiddleware,
714
+ W as isRetryableError,
715
+ oe as loggingMiddleware,
716
+ se as rateLimitMiddleware,
717
+ $ as renderTemplate,
718
+ ne as retryMiddleware,
719
+ Q as useChat,
720
+ X as useCompletion,
721
+ ee as useObject,
722
+ re as usePrompt,
723
+ ae as wrapProvider
483
724
  };