vue-llm 1.2.0 → 1.3.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/providers.js CHANGED
@@ -1,121 +1,121 @@
1
- import { S as k } from "./sse-DU5m1n6r.js";
2
- import { c as L } from "./sse-DU5m1n6r.js";
3
- import { r as T, i as b, d as v } from "./file-x_kW7BHa.js";
4
- import { c as _ } from "./errors-B3A_zmVE.js";
5
- function U(o) {
1
+ import { S as N } from "./sse-DU5m1n6r.js";
2
+ import { c as le } from "./sse-DU5m1n6r.js";
3
+ import { r as x, i as O, d as I } from "./file-x_kW7BHa.js";
4
+ import { c as S } from "./errors-B3A_zmVE.js";
5
+ function te(t) {
6
6
  return {
7
7
  id: "openai",
8
8
  supportsStreaming: !0,
9
9
  validateConfig() {
10
- if (!o.apiKey)
10
+ if (!t.apiKey)
11
11
  throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');
12
- if (!o.dangerouslyAllowBrowser && typeof window < "u")
12
+ if (!t.dangerouslyAllowBrowser && typeof window < "u")
13
13
  throw new Error(
14
14
  "[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true."
15
15
  );
16
16
  },
17
17
  async chat(e) {
18
- const t = o.baseURL ?? "https://api.openai.com/v1/chat/completions", a = {
18
+ const o = t.baseURL ?? "https://api.openai.com/v1/chat/completions", a = {
19
19
  model: e.model,
20
- messages: x(e.messages),
20
+ messages: L(e.messages),
21
21
  stream: !0,
22
22
  stream_options: { include_usage: !0 }
23
23
  };
24
- e.providerOptions?.response_format && (a.response_format = e.providerOptions.response_format), e.tools?.length && (a.tools = e.tools.map((m) => ({
24
+ e.providerOptions?.response_format && (a.response_format = e.providerOptions.response_format), e.tools?.length && (a.tools = e.tools.map((f) => ({
25
25
  type: "function",
26
26
  function: {
27
- name: m.name,
28
- description: m.description,
29
- parameters: m.parameters
27
+ name: f.name,
28
+ description: f.description,
29
+ parameters: f.parameters
30
30
  }
31
31
  })));
32
- const c = await fetch(t, {
32
+ const i = await fetch(o, {
33
33
  method: "POST",
34
34
  headers: {
35
- Authorization: `Bearer ${o.apiKey}`,
35
+ Authorization: `Bearer ${t.apiKey}`,
36
36
  "Content-Type": "application/json",
37
37
  ...e.providerOptions?.headers
38
38
  },
39
39
  body: JSON.stringify(a),
40
40
  signal: e.signal
41
41
  });
42
- if (!c.ok)
43
- throw await _("openai", "OpenAI API", c);
44
- if (!c.body)
42
+ if (!i.ok)
43
+ throw await S("openai", "OpenAI API", i);
44
+ if (!i.body)
45
45
  throw new Error("[vue-llm] No response body from OpenAI");
46
- let r;
47
- const n = new Promise((m) => {
48
- r = m;
46
+ let s;
47
+ const n = new Promise((f) => {
48
+ s = f;
49
49
  });
50
- return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
51
- transform(m, y) {
52
- if (m.data === "[DONE]") return;
53
- let d;
50
+ return { stream: i.body.pipeThrough(new TextDecoderStream()).pipeThrough(new N()).pipeThrough(new TransformStream({
51
+ transform(f, y) {
52
+ if (f.data === "[DONE]") return;
53
+ let m;
54
54
  try {
55
- d = JSON.parse(m.data);
55
+ m = JSON.parse(f.data);
56
56
  } catch {
57
57
  return;
58
58
  }
59
- const p = d.choices?.[0];
60
- if (!p) {
61
- d.usage && r({
59
+ const c = m.choices?.[0];
60
+ if (!c) {
61
+ m.usage && s({
62
62
  finishReason: "stop",
63
63
  usage: {
64
- promptTokens: d.usage.prompt_tokens,
65
- completionTokens: d.usage.completion_tokens,
66
- totalTokens: d.usage.total_tokens
64
+ promptTokens: m.usage.prompt_tokens,
65
+ completionTokens: m.usage.completion_tokens,
66
+ totalTokens: m.usage.total_tokens
67
67
  }
68
68
  });
69
69
  return;
70
70
  }
71
- const i = p.delta;
72
- if (i.content && y.enqueue({ type: "text-delta", text: i.content }), i.tool_calls)
73
- for (const l of i.tool_calls)
74
- l.id && y.enqueue({
71
+ const l = c.delta;
72
+ if (l.content && y.enqueue({ type: "text-delta", text: l.content }), l.tool_calls)
73
+ for (const p of l.tool_calls)
74
+ p.id && y.enqueue({
75
75
  type: "tool-call-start",
76
- toolCallId: l.id,
77
- toolName: l.function?.name ?? ""
78
- }), l.function?.arguments && y.enqueue({
76
+ toolCallId: p.id,
77
+ toolName: p.function?.name ?? ""
78
+ }), p.function?.arguments && y.enqueue({
79
79
  type: "tool-call-delta",
80
- toolCallId: l.id ?? "",
81
- args: l.function.arguments
80
+ toolCallId: p.id ?? "",
81
+ args: p.function.arguments
82
82
  });
83
- if (p.finish_reason) {
84
- const l = i.tool_calls?.filter((s) => s.id) ?? [];
85
- for (const s of l)
86
- s.id && y.enqueue({ type: "tool-call-end", toolCallId: s.id });
87
- const u = p.finish_reason === "tool_calls" ? "tool-calls" : p.finish_reason === "length" ? "length" : "stop";
88
- y.enqueue({ type: "finish", finishReason: u, usage: void 0 });
83
+ if (c.finish_reason) {
84
+ const p = l.tool_calls?.filter((r) => r.id) ?? [];
85
+ for (const r of p)
86
+ r.id && y.enqueue({ type: "tool-call-end", toolCallId: r.id });
87
+ const d = c.finish_reason === "tool_calls" ? "tool-calls" : c.finish_reason === "length" ? "length" : "stop";
88
+ y.enqueue({ type: "finish", finishReason: d, usage: void 0 });
89
89
  }
90
90
  }
91
91
  })), response: n };
92
92
  }
93
93
  };
94
94
  }
95
- function x(o) {
96
- return o.map((e) => e.role === "tool" ? {
95
+ function L(t) {
96
+ return t.map((e) => e.role === "tool" ? {
97
97
  role: "tool",
98
98
  content: typeof e.content == "string" ? e.content : JSON.stringify(e.content),
99
99
  tool_call_id: e.toolCallId
100
100
  } : e.role === "assistant" && e.toolCalls?.length ? {
101
101
  role: "assistant",
102
102
  content: typeof e.content == "string" && e.content ? e.content : null,
103
- tool_calls: e.toolCalls.map((t) => ({
104
- id: t.id,
103
+ tool_calls: e.toolCalls.map((o) => ({
104
+ id: o.id,
105
105
  type: "function",
106
106
  function: {
107
- name: t.name,
108
- arguments: typeof t.args == "string" ? t.args : JSON.stringify(t.args)
107
+ name: o.name,
108
+ arguments: typeof o.args == "string" ? o.args : JSON.stringify(o.args)
109
109
  }
110
110
  }))
111
111
  } : {
112
112
  role: e.role,
113
- content: typeof e.content == "string" ? e.content : e.content.map(C)
113
+ content: typeof e.content == "string" ? e.content : e.content.map(M)
114
114
  });
115
115
  }
116
- function C(o) {
117
- if (o.type === "text") return { type: "text", text: o.text };
118
- const e = T(o);
116
+ function M(t) {
117
+ if (t.type === "text") return { type: "text", text: t.text };
118
+ const e = x(t);
119
119
  if (e.mediaType.startsWith("image/"))
120
120
  return { type: "image_url", image_url: { url: e.url } };
121
121
  if (!e.base64)
@@ -125,119 +125,119 @@ function C(o) {
125
125
  type: "file",
126
126
  file: { filename: e.filename ?? "document.pdf", file_data: e.url }
127
127
  };
128
- const t = O[e.mediaType];
129
- if (t)
130
- return { type: "input_audio", input_audio: { data: e.base64, format: t } };
131
- if (b(e.mediaType))
132
- return { type: "text", text: v(e.base64) };
128
+ const o = J[e.mediaType];
129
+ if (o)
130
+ return { type: "input_audio", input_audio: { data: e.base64, format: o } };
131
+ if (O(e.mediaType))
132
+ return { type: "text", text: I(e.base64) };
133
133
  throw new Error(`[vue-llm] OpenAI does not support ${e.mediaType} attachments`);
134
134
  }
135
- const O = {
135
+ const J = {
136
136
  "audio/wav": "wav",
137
137
  "audio/x-wav": "wav",
138
138
  "audio/mpeg": "mp3",
139
139
  "audio/mp3": "mp3"
140
140
  };
141
- function M(o) {
141
+ function oe(t) {
142
142
  return {
143
143
  id: "anthropic",
144
144
  supportsStreaming: !0,
145
145
  validateConfig() {
146
- if (!o.apiKey)
146
+ if (!t.apiKey)
147
147
  throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');
148
- if (!o.dangerouslyAllowBrowser && typeof window < "u")
148
+ if (!t.dangerouslyAllowBrowser && typeof window < "u")
149
149
  throw new Error(
150
150
  "[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true."
151
151
  );
152
152
  },
153
153
  async chat(e) {
154
- const t = (o.baseURL ?? "https://api.anthropic.com") + "/v1/messages", a = e.messages.find((p) => p.role === "system"), c = e.messages.filter((p) => p.role !== "system"), r = {
154
+ const o = (t.baseURL ?? "https://api.anthropic.com") + "/v1/messages", a = e.messages.find((c) => c.role === "system"), i = e.messages.filter((c) => c.role !== "system"), s = {
155
155
  model: e.model,
156
- messages: I(c),
156
+ messages: U(i),
157
157
  max_tokens: e.providerOptions?.maxTokens ?? 4096,
158
158
  stream: !0
159
159
  };
160
- a && (r.system = typeof a.content == "string" ? a.content : a.content.map((p) => ({ type: "text", text: p.type === "text" ? p.text : "" }))), e.tools?.length && (r.tools = e.tools.map((p) => ({
161
- name: p.name,
162
- description: p.description,
163
- input_schema: p.parameters
160
+ a && (s.system = typeof a.content == "string" ? a.content : a.content.map((c) => ({ type: "text", text: c.type === "text" ? c.text : "" }))), e.tools?.length && (s.tools = e.tools.map((c) => ({
161
+ name: c.name,
162
+ description: c.description,
163
+ input_schema: c.parameters
164
164
  })));
165
- const n = await fetch(t, {
165
+ const n = await fetch(o, {
166
166
  method: "POST",
167
167
  headers: {
168
- "x-api-key": o.apiKey,
168
+ "x-api-key": t.apiKey,
169
169
  "anthropic-version": "2023-06-01",
170
170
  "Content-Type": "application/json",
171
171
  ...e.providerOptions?.headers
172
172
  },
173
- body: JSON.stringify(r),
173
+ body: JSON.stringify(s),
174
174
  signal: e.signal
175
175
  });
176
176
  if (!n.ok)
177
- throw await _("anthropic", "Anthropic API", n);
177
+ throw await S("anthropic", "Anthropic API", n);
178
178
  if (!n.body)
179
179
  throw new Error("[vue-llm] No response body from Anthropic");
180
- let f;
181
- const m = new Promise((p) => {
182
- f = p;
180
+ let u;
181
+ const f = new Promise((c) => {
182
+ u = c;
183
183
  });
184
184
  let y = "";
185
- return { stream: n.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
186
- transform(p, i) {
187
- let l;
185
+ return { stream: n.body.pipeThrough(new TextDecoderStream()).pipeThrough(new N()).pipeThrough(new TransformStream({
186
+ transform(c, l) {
187
+ let p;
188
188
  try {
189
- l = JSON.parse(p.data);
189
+ p = JSON.parse(c.data);
190
190
  } catch {
191
191
  return;
192
192
  }
193
- switch (p.event ?? l.type) {
193
+ switch (c.event ?? p.type) {
194
194
  case "content_block_start": {
195
- const s = l.content_block;
196
- s?.type === "tool_use" && (y = s.id, i.enqueue({
195
+ const r = p.content_block;
196
+ r?.type === "tool_use" && (y = r.id, l.enqueue({
197
197
  type: "tool-call-start",
198
198
  toolCallId: y,
199
- toolName: s.name
199
+ toolName: r.name
200
200
  }));
201
201
  break;
202
202
  }
203
203
  case "content_block_delta": {
204
- const s = l.delta;
205
- s?.type === "text_delta" && s.text && i.enqueue({ type: "text-delta", text: s.text }), s?.type === "thinking_delta" && s.text && i.enqueue({ type: "reasoning-delta", text: s.text }), s?.type === "input_json_delta" && s.partial_json && i.enqueue({
204
+ const r = p.delta;
205
+ r?.type === "text_delta" && r.text && l.enqueue({ type: "text-delta", text: r.text }), r?.type === "thinking_delta" && r.text && l.enqueue({ type: "reasoning-delta", text: r.text }), r?.type === "input_json_delta" && r.partial_json && l.enqueue({
206
206
  type: "tool-call-delta",
207
207
  toolCallId: y,
208
- args: s.partial_json
208
+ args: r.partial_json
209
209
  });
210
210
  break;
211
211
  }
212
212
  case "content_block_stop": {
213
- y && (i.enqueue({ type: "tool-call-end", toolCallId: y }), y = "");
213
+ y && (l.enqueue({ type: "tool-call-end", toolCallId: y }), y = "");
214
214
  break;
215
215
  }
216
216
  case "message_delta": {
217
- const s = l.delta, w = l.usage, g = s?.stop_reason === "tool_use" ? "tool-calls" : s?.stop_reason === "max_tokens" ? "length" : "stop";
218
- i.enqueue({
217
+ const r = p.delta, w = p.usage, _ = r?.stop_reason === "tool_use" ? "tool-calls" : r?.stop_reason === "max_tokens" ? "length" : "stop";
218
+ l.enqueue({
219
219
  type: "finish",
220
- finishReason: g,
220
+ finishReason: _,
221
221
  usage: w ? { promptTokens: 0, completionTokens: w.output_tokens ?? 0, totalTokens: w.output_tokens ?? 0 } : void 0
222
- }), f({ finishReason: g, usage: void 0 });
222
+ }), u({ finishReason: _, usage: void 0 });
223
223
  break;
224
224
  }
225
225
  case "error": {
226
- const s = l.error;
227
- i.enqueue({
226
+ const r = p.error;
227
+ l.enqueue({
228
228
  type: "error",
229
- error: new Error(`[vue-llm] Anthropic stream error: ${s?.message ?? "unknown"}`)
229
+ error: new Error(`[vue-llm] Anthropic stream error: ${r?.message ?? "unknown"}`)
230
230
  });
231
231
  break;
232
232
  }
233
233
  }
234
234
  }
235
- })), response: m };
235
+ })), response: f };
236
236
  }
237
237
  };
238
238
  }
239
- function I(o) {
240
- return o.map((e) => {
239
+ function U(t) {
240
+ return t.map((e) => {
241
241
  if (e.role === "tool")
242
242
  return {
243
243
  role: "user",
@@ -248,63 +248,63 @@ function I(o) {
248
248
  }]
249
249
  };
250
250
  if (e.role === "assistant" && e.toolCalls?.length) {
251
- const t = [];
252
- typeof e.content == "string" && e.content && t.push({ type: "text", text: e.content });
251
+ const o = [];
252
+ typeof e.content == "string" && e.content && o.push({ type: "text", text: e.content });
253
253
  for (const a of e.toolCalls)
254
- t.push({
254
+ o.push({
255
255
  type: "tool_use",
256
256
  id: a.id,
257
257
  name: a.name,
258
258
  input: a.args
259
259
  });
260
- return { role: "assistant", content: t };
260
+ return { role: "assistant", content: o };
261
261
  }
262
262
  return {
263
263
  role: e.role,
264
- content: typeof e.content == "string" ? e.content : e.content.map(A)
264
+ content: typeof e.content == "string" ? e.content : e.content.map($)
265
265
  };
266
266
  });
267
267
  }
268
- function A(o) {
269
- if (o.type === "text") return { type: "text", text: o.text };
270
- const e = T(o), t = e.base64 ? { type: "base64", media_type: e.mediaType, data: e.base64 } : { type: "url", url: e.url };
268
+ function $(t) {
269
+ if (t.type === "text") return { type: "text", text: t.text };
270
+ const e = x(t), o = e.base64 ? { type: "base64", media_type: e.mediaType, data: e.base64 } : { type: "url", url: e.url };
271
271
  if (e.mediaType.startsWith("image/"))
272
- return { type: "image", source: t };
272
+ return { type: "image", source: o };
273
273
  if (e.mediaType === "application/pdf")
274
- return { type: "document", source: t, ...e.filename ? { title: e.filename } : {} };
275
- if (b(e.mediaType) && e.base64)
274
+ return { type: "document", source: o, ...e.filename ? { title: e.filename } : {} };
275
+ if (O(e.mediaType) && e.base64)
276
276
  return {
277
277
  type: "document",
278
- source: { type: "text", media_type: "text/plain", data: v(e.base64) },
278
+ source: { type: "text", media_type: "text/plain", data: I(e.base64) },
279
279
  ...e.filename ? { title: e.filename } : {}
280
280
  };
281
281
  throw new Error(`[vue-llm] Anthropic does not support ${e.mediaType} attachments`);
282
282
  }
283
- function $(o) {
283
+ function ne(t) {
284
284
  return {
285
285
  id: "google",
286
286
  supportsStreaming: !0,
287
287
  validateConfig() {
288
- if (!o.apiKey)
288
+ if (!t.apiKey)
289
289
  throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');
290
- if (!o.dangerouslyAllowBrowser && typeof window < "u")
290
+ if (!t.dangerouslyAllowBrowser && typeof window < "u")
291
291
  throw new Error(
292
292
  "[vue-llm] API keys must not be used in the browser. Use a server proxy to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true."
293
293
  );
294
294
  },
295
295
  async chat(e) {
296
- const a = `${o.baseURL ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${o.apiKey}`, c = {
297
- contents: S(e.messages)
298
- }, r = e.messages.find((i) => i.role === "system");
299
- r && (c.systemInstruction = {
300
- parts: [{ text: typeof r.content == "string" ? r.content : "" }]
301
- }), e.tools?.length && (c.tools = [{
302
- functionDeclarations: e.tools.map((i) => ({
303
- name: i.name,
304
- description: i.description,
305
- parameters: i.parameters
296
+ const a = `${t.baseURL ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${t.apiKey}`, i = {
297
+ contents: W(e.messages)
298
+ }, s = e.messages.find((l) => l.role === "system");
299
+ s && (i.systemInstruction = {
300
+ parts: [{ text: typeof s.content == "string" ? s.content : "" }]
301
+ }), e.tools?.length && (i.tools = [{
302
+ functionDeclarations: e.tools.map((l) => ({
303
+ name: l.name,
304
+ description: l.description,
305
+ parameters: l.parameters
306
306
  }))
307
- }]), c.generationConfig = {
307
+ }]), i.generationConfig = {
308
308
  ...e.providerOptions?.response_format?.type === "json_object" ? { responseMimeType: "application/json" } : {}
309
309
  };
310
310
  const n = await fetch(a, {
@@ -313,149 +313,149 @@ function $(o) {
313
313
  "Content-Type": "application/json",
314
314
  ...e.providerOptions?.headers
315
315
  },
316
- body: JSON.stringify(c),
316
+ body: JSON.stringify(i),
317
317
  signal: e.signal
318
318
  });
319
319
  if (!n.ok)
320
- throw await _("google", "Google AI API", n);
320
+ throw await S("google", "Google AI API", n);
321
321
  if (!n.body)
322
322
  throw new Error("[vue-llm] No response body from Google AI");
323
- let f;
324
- const m = new Promise((i) => {
325
- f = i;
323
+ let u;
324
+ const f = new Promise((l) => {
325
+ u = l;
326
326
  });
327
- let y = 0, d = !1;
327
+ let y = 0, m = !1;
328
328
  return { stream: n.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
329
329
  buffer: "",
330
- transform(i, l) {
331
- this.buffer += i;
332
- const u = this.buffer.split(`
330
+ transform(l, p) {
331
+ this.buffer += l;
332
+ const d = this.buffer.split(`
333
333
  `);
334
- this.buffer = u.pop();
335
- for (const s of u)
336
- s.startsWith("data: ") && l.enqueue(s.slice(6));
334
+ this.buffer = d.pop();
335
+ for (const r of d)
336
+ r.startsWith("data: ") && p.enqueue(r.slice(6));
337
337
  },
338
- flush(i) {
339
- const l = this.buffer.trim();
340
- l.startsWith("data: ") && i.enqueue(l.slice(6));
338
+ flush(l) {
339
+ const p = this.buffer.trim();
340
+ p.startsWith("data: ") && l.enqueue(p.slice(6));
341
341
  }
342
342
  })).pipeThrough(new TransformStream({
343
- transform(i, l) {
344
- let u;
343
+ transform(l, p) {
344
+ let d;
345
345
  try {
346
- u = JSON.parse(i);
346
+ d = JSON.parse(l);
347
347
  } catch {
348
348
  return;
349
349
  }
350
- const s = u.candidates?.[0];
351
- if (!s) return;
352
- const w = s.content?.parts;
350
+ const r = d.candidates?.[0];
351
+ if (!r) return;
352
+ const w = r.content?.parts;
353
353
  if (w) {
354
- for (const g of w)
355
- if (g.text !== void 0 && l.enqueue({ type: "text-delta", text: g.text }), g.functionCall) {
356
- const h = `tc_gemini_${++y}`;
357
- d = !0, l.enqueue({
354
+ for (const _ of w)
355
+ if (_.text !== void 0 && p.enqueue({ type: "text-delta", text: _.text }), _.functionCall) {
356
+ const g = `tc_gemini_${++y}`;
357
+ m = !0, p.enqueue({
358
358
  type: "tool-call-start",
359
- toolCallId: h,
360
- toolName: g.functionCall.name
361
- }), l.enqueue({
359
+ toolCallId: g,
360
+ toolName: _.functionCall.name
361
+ }), p.enqueue({
362
362
  type: "tool-call-delta",
363
- toolCallId: h,
364
- args: JSON.stringify(g.functionCall.args ?? {})
365
- }), l.enqueue({ type: "tool-call-end", toolCallId: h });
363
+ toolCallId: g,
364
+ args: JSON.stringify(_.functionCall.args ?? {})
365
+ }), p.enqueue({ type: "tool-call-end", toolCallId: g });
366
366
  }
367
367
  }
368
- if (s.finishReason) {
369
- const g = d ? "tool-calls" : s.finishReason === "MAX_TOKENS" ? "length" : "stop", h = u.usageMetadata;
370
- l.enqueue({
368
+ if (r.finishReason) {
369
+ const _ = m ? "tool-calls" : r.finishReason === "MAX_TOKENS" ? "length" : "stop", g = d.usageMetadata;
370
+ p.enqueue({
371
371
  type: "finish",
372
- finishReason: g,
373
- usage: h ? {
374
- promptTokens: h.promptTokenCount ?? 0,
375
- completionTokens: h.candidatesTokenCount ?? 0,
376
- totalTokens: h.totalTokenCount ?? 0
372
+ finishReason: _,
373
+ usage: g ? {
374
+ promptTokens: g.promptTokenCount ?? 0,
375
+ completionTokens: g.candidatesTokenCount ?? 0,
376
+ totalTokens: g.totalTokenCount ?? 0
377
377
  } : void 0
378
- }), f({
379
- finishReason: g,
380
- usage: h ? {
381
- promptTokens: h.promptTokenCount ?? 0,
382
- completionTokens: h.candidatesTokenCount ?? 0,
383
- totalTokens: h.totalTokenCount ?? 0
378
+ }), u({
379
+ finishReason: _,
380
+ usage: g ? {
381
+ promptTokens: g.promptTokenCount ?? 0,
382
+ completionTokens: g.candidatesTokenCount ?? 0,
383
+ totalTokens: g.totalTokenCount ?? 0
384
384
  } : void 0
385
385
  });
386
386
  }
387
387
  }
388
- })), response: m };
388
+ })), response: f };
389
389
  }
390
390
  };
391
391
  }
392
- function S(o) {
393
- const e = [], t = /* @__PURE__ */ new Map();
394
- for (const a of o) {
392
+ function W(t) {
393
+ const e = [], o = /* @__PURE__ */ new Map();
394
+ for (const a of t) {
395
395
  if (a.role === "system") continue;
396
396
  if (a.role === "tool") {
397
397
  const n = {
398
398
  functionResponse: {
399
- name: t.get(a.toolCallId ?? "") ?? a.toolCallId ?? "",
400
- response: { result: P(a.content) }
399
+ name: o.get(a.toolCallId ?? "") ?? a.toolCallId ?? "",
400
+ response: { result: j(a.content) }
401
401
  }
402
- }, f = e.at(-1);
403
- f?.role === "user" && f.parts.every((m) => m.functionResponse) ? f.parts.push(n) : e.push({ role: "user", parts: [n] });
402
+ }, u = e.at(-1);
403
+ u?.role === "user" && u.parts.every((f) => f.functionResponse) ? u.parts.push(n) : e.push({ role: "user", parts: [n] });
404
404
  continue;
405
405
  }
406
406
  for (const n of a.toolCalls ?? [])
407
- t.set(n.id, n.name);
408
- const c = a.role === "assistant" ? "model" : "user", r = [];
407
+ o.set(n.id, n.name);
408
+ const i = a.role === "assistant" ? "model" : "user", s = [];
409
409
  if (typeof a.content == "string")
410
- a.content && r.push({ text: a.content });
410
+ a.content && s.push({ text: a.content });
411
411
  else if (Array.isArray(a.content)) {
412
412
  for (const n of a.content)
413
- if (n.type === "text" && r.push({ text: n.text }), n.type === "image" || n.type === "file") {
414
- const f = T(n);
415
- r.push(f.base64 ? { inlineData: { mimeType: f.mediaType, data: f.base64 } } : { fileData: { mimeType: f.mediaType, fileUri: f.url } });
413
+ if (n.type === "text" && s.push({ text: n.text }), n.type === "image" || n.type === "file") {
414
+ const u = x(n);
415
+ s.push(u.base64 ? { inlineData: { mimeType: u.mediaType, data: u.base64 } } : { fileData: { mimeType: u.mediaType, fileUri: u.url } });
416
416
  }
417
417
  }
418
418
  if (a.toolCalls?.length)
419
419
  for (const n of a.toolCalls)
420
- r.push({
420
+ s.push({
421
421
  functionCall: {
422
422
  name: n.name,
423
423
  args: typeof n.args == "string" ? JSON.parse(n.args) : n.args
424
424
  }
425
425
  });
426
- r.length > 0 && e.push({ role: c, parts: r });
426
+ s.length > 0 && e.push({ role: i, parts: s });
427
427
  }
428
428
  return e;
429
429
  }
430
- function P(o) {
431
- if (typeof o != "string") return o;
430
+ function j(t) {
431
+ if (typeof t != "string") return t;
432
432
  try {
433
- return JSON.parse(o);
433
+ return JSON.parse(t);
434
434
  } catch {
435
- return o;
435
+ return t;
436
436
  }
437
437
  }
438
- function j(o) {
438
+ function ae(t) {
439
439
  return {
440
440
  id: "ollama",
441
441
  supportsStreaming: !0,
442
442
  validateConfig() {
443
443
  },
444
444
  async chat(e) {
445
- const t = (o?.baseURL ?? "http://localhost:11434") + "/api/chat", a = {
445
+ const o = (t?.baseURL ?? "http://localhost:11434") + "/api/chat", a = {
446
446
  model: e.model,
447
- messages: N(e.messages),
447
+ messages: G(e.messages),
448
448
  stream: !0
449
449
  };
450
- e.tools?.length && (a.tools = e.tools.map((d) => ({
450
+ e.tools?.length && (a.tools = e.tools.map((m) => ({
451
451
  type: "function",
452
452
  function: {
453
- name: d.name,
454
- description: d.description,
455
- parameters: d.parameters
453
+ name: m.name,
454
+ description: m.description,
455
+ parameters: m.parameters
456
456
  }
457
457
  })));
458
- const c = await fetch(t, {
458
+ const i = await fetch(o, {
459
459
  method: "POST",
460
460
  headers: {
461
461
  "Content-Type": "application/json",
@@ -464,51 +464,51 @@ function j(o) {
464
464
  body: JSON.stringify(a),
465
465
  signal: e.signal
466
466
  });
467
- if (!c.ok)
468
- throw await _("ollama", "Ollama API", c);
469
- if (!c.body)
467
+ if (!i.ok)
468
+ throw await S("ollama", "Ollama API", i);
469
+ if (!i.body)
470
470
  throw new Error("[vue-llm] No response body from Ollama");
471
- let r;
472
- const n = new Promise((d) => {
473
- r = d;
471
+ let s;
472
+ const n = new Promise((m) => {
473
+ s = m;
474
474
  });
475
- let f = "", m = !1;
476
- return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
477
- transform(d, p) {
478
- f += d;
479
- const i = f.split(`
475
+ let u = "", f = !1;
476
+ return { stream: i.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
477
+ transform(m, c) {
478
+ u += m;
479
+ const l = u.split(`
480
480
  `);
481
- f = i.pop() ?? "";
482
- for (const l of i) {
483
- if (!l.trim()) continue;
484
- let u;
481
+ u = l.pop() ?? "";
482
+ for (const p of l) {
483
+ if (!p.trim()) continue;
484
+ let d;
485
485
  try {
486
- u = JSON.parse(l);
486
+ d = JSON.parse(p);
487
487
  } catch {
488
488
  continue;
489
489
  }
490
- if (u.message?.content && p.enqueue({ type: "text-delta", text: u.message.content }), u.message?.tool_calls)
491
- for (const s of u.message.tool_calls) {
492
- m = !0;
490
+ if (d.message?.content && c.enqueue({ type: "text-delta", text: d.message.content }), d.message?.tool_calls)
491
+ for (const r of d.message.tool_calls) {
492
+ f = !0;
493
493
  const w = `ollama-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
494
- p.enqueue({
494
+ c.enqueue({
495
495
  type: "tool-call-start",
496
496
  toolCallId: w,
497
- toolName: s.function.name
498
- }), p.enqueue({
497
+ toolName: r.function.name
498
+ }), c.enqueue({
499
499
  type: "tool-call-delta",
500
500
  toolCallId: w,
501
- args: JSON.stringify(s.function.arguments)
502
- }), p.enqueue({ type: "tool-call-end", toolCallId: w });
501
+ args: JSON.stringify(r.function.arguments)
502
+ }), c.enqueue({ type: "tool-call-end", toolCallId: w });
503
503
  }
504
- if (u.done) {
505
- const s = m ? "tool-calls" : "stop";
506
- p.enqueue({ type: "finish", finishReason: s }), r({
507
- finishReason: s,
508
- usage: u.eval_count ? {
509
- promptTokens: u.prompt_eval_count ?? 0,
510
- completionTokens: u.eval_count,
511
- totalTokens: (u.prompt_eval_count ?? 0) + u.eval_count
504
+ if (d.done) {
505
+ const r = f ? "tool-calls" : "stop";
506
+ c.enqueue({ type: "finish", finishReason: r }), s({
507
+ finishReason: r,
508
+ usage: d.eval_count ? {
509
+ promptTokens: d.prompt_eval_count ?? 0,
510
+ completionTokens: d.eval_count,
511
+ totalTokens: (d.prompt_eval_count ?? 0) + d.eval_count
512
512
  } : void 0
513
513
  });
514
514
  }
@@ -518,59 +518,278 @@ function j(o) {
518
518
  }
519
519
  };
520
520
  }
521
- function N(o) {
521
+ function G(t) {
522
522
  const e = /* @__PURE__ */ new Map();
523
- return o.map((t) => {
524
- if (t.role === "tool")
523
+ return t.map((o) => {
524
+ if (o.role === "tool")
525
525
  return {
526
526
  role: "tool",
527
- content: typeof t.content == "string" ? t.content : JSON.stringify(t.content),
528
- tool_name: e.get(t.toolCallId ?? "")
527
+ content: typeof o.content == "string" ? o.content : JSON.stringify(o.content),
528
+ tool_name: e.get(o.toolCallId ?? "")
529
529
  };
530
- if (t.role === "assistant" && t.toolCalls?.length) {
531
- for (const r of t.toolCalls) e.set(r.id, r.name);
530
+ if (o.role === "assistant" && o.toolCalls?.length) {
531
+ for (const s of o.toolCalls) e.set(s.id, s.name);
532
532
  return {
533
533
  role: "assistant",
534
- content: typeof t.content == "string" ? t.content : "",
535
- tool_calls: t.toolCalls.map((r) => ({
534
+ content: typeof o.content == "string" ? o.content : "",
535
+ tool_calls: o.toolCalls.map((s) => ({
536
536
  function: {
537
- name: r.name,
538
- arguments: typeof r.args == "string" ? JSON.parse(r.args) : r.args
537
+ name: s.name,
538
+ arguments: typeof s.args == "string" ? JSON.parse(s.args) : s.args
539
539
  }
540
540
  }))
541
541
  };
542
542
  }
543
- if (typeof t.content == "string")
544
- return { role: t.role, content: t.content };
545
- const a = [], c = [];
546
- for (const r of t.content) {
547
- if (r.type === "text") {
548
- a.push(r.text);
543
+ if (typeof o.content == "string")
544
+ return { role: o.role, content: o.content };
545
+ const a = [], i = [];
546
+ for (const s of o.content) {
547
+ if (s.type === "text") {
548
+ a.push(s.text);
549
549
  continue;
550
550
  }
551
- const n = T(r);
551
+ const n = x(s);
552
552
  if (!n.base64)
553
553
  throw new Error("[vue-llm] Ollama requires attachments as data URLs, got a remote URL");
554
554
  if (n.mediaType.startsWith("image/"))
555
- c.push(n.base64);
556
- else if (b(n.mediaType))
557
- a.push(v(n.base64));
555
+ i.push(n.base64);
556
+ else if (O(n.mediaType))
557
+ a.push(I(n.base64));
558
558
  else
559
559
  throw new Error(`[vue-llm] Ollama does not support ${n.mediaType} attachments`);
560
560
  }
561
561
  return {
562
- role: t.role,
562
+ role: o.role,
563
563
  content: a.join(`
564
564
 
565
565
  `),
566
- ...c.length > 0 ? { images: c } : {}
566
+ ...i.length > 0 ? { images: i } : {}
567
567
  };
568
568
  });
569
569
  }
570
+ function D() {
571
+ return typeof navigator < "u" && "gpu" in navigator && !!navigator.gpu;
572
+ }
573
+ function se(t) {
574
+ let e, o, a;
575
+ const i = (n) => t.onProgress?.(n);
576
+ function s(n) {
577
+ if (o === n && !a) return Promise.resolve();
578
+ const f = (a ?? Promise.resolve()).catch(() => {
579
+ }).then(async () => {
580
+ if (o !== n) {
581
+ if (e)
582
+ o = void 0, await (await e).reload(n, t.chatOptions);
583
+ else {
584
+ e = t.createEngine(
585
+ n,
586
+ { ...t.engineConfig, initProgressCallback: i },
587
+ t.chatOptions
588
+ );
589
+ try {
590
+ await e;
591
+ } catch (m) {
592
+ throw e = void 0, m;
593
+ }
594
+ }
595
+ o = n;
596
+ }
597
+ });
598
+ a = f;
599
+ const y = () => {
600
+ a === f && (a = void 0);
601
+ };
602
+ return f.then(y, y), f;
603
+ }
604
+ return {
605
+ id: "webllm",
606
+ supportsStreaming: !0,
607
+ get loadedModel() {
608
+ return o;
609
+ },
610
+ validateConfig() {
611
+ if (typeof t.createEngine != "function")
612
+ throw new Error(
613
+ "[vue-llm] createWebLLM requires an engine factory. Pass createWebLLM({ createEngine: CreateMLCEngine }) from @mlc-ai/web-llm"
614
+ );
615
+ if (!D())
616
+ throw new Error("[vue-llm] In-browser models require WebGPU, which this browser does not support");
617
+ },
618
+ load: s,
619
+ async unload() {
620
+ const n = e;
621
+ e = void 0, o = void 0, n && await (await n).unload();
622
+ },
623
+ async chat(n) {
624
+ await s(n.model);
625
+ const u = await e;
626
+ if (n.signal?.aborted)
627
+ throw n.signal.reason ?? new DOMException("Aborted", "AbortError");
628
+ const f = {
629
+ ...B(n.providerOptions),
630
+ messages: F(n.messages),
631
+ stream: !0,
632
+ stream_options: { include_usage: !0 }
633
+ };
634
+ n.providerOptions?.response_format && (f.response_format = n.providerOptions.response_format), n.tools?.length && (f.tools = n.tools.map((h) => ({
635
+ type: "function",
636
+ function: { name: h.name, description: h.description, parameters: h.parameters }
637
+ })));
638
+ const y = await u.chat.completions.create(f), m = () => {
639
+ u.interruptGenerate();
640
+ };
641
+ n.signal?.addEventListener("abort", m, { once: !0 });
642
+ let c, l;
643
+ const p = new Promise((h, T) => {
644
+ c = h, l = T;
645
+ });
646
+ p.catch(() => {
647
+ });
648
+ const d = y[Symbol.asyncIterator](), r = q(), w = /* @__PURE__ */ new Map();
649
+ let _ = "stop", g;
650
+ const A = () => n.signal?.removeEventListener("abort", m), E = (h) => {
651
+ h.usage && (g = {
652
+ promptTokens: h.usage.prompt_tokens,
653
+ completionTokens: h.usage.completion_tokens,
654
+ totalTokens: h.usage.total_tokens
655
+ });
656
+ const T = h.choices?.[0];
657
+ if (!T) return [];
658
+ const v = [];
659
+ T.delta?.content && v.push(...r.push(T.delta.content));
660
+ for (const [C, b] of (T.delta?.tool_calls ?? []).entries()) {
661
+ const P = b.index ?? C;
662
+ let k = w.get(P);
663
+ if (k || (k = b.id ?? `webllm-call-${P}-${Date.now().toString(36)}`, w.set(P, k), v.push({ type: "tool-call-start", toolCallId: k, toolName: b.function?.name ?? "" })), b.function?.arguments) {
664
+ const R = typeof b.function.arguments == "string" ? b.function.arguments : JSON.stringify(b.function.arguments);
665
+ v.push({ type: "tool-call-delta", toolCallId: k, args: R });
666
+ }
667
+ }
668
+ return T.finish_reason && (_ = T.finish_reason === "tool_calls" ? "tool-calls" : T.finish_reason === "length" ? "length" : "stop"), v;
669
+ };
670
+ return { stream: new ReadableStream({
671
+ async pull(h) {
672
+ try {
673
+ for (; ; ) {
674
+ const { done: T, value: v } = await d.next();
675
+ if (T) {
676
+ for (const b of r.flush()) h.enqueue(b);
677
+ for (const b of w.values()) h.enqueue({ type: "tool-call-end", toolCallId: b });
678
+ w.clear(), h.enqueue({ type: "finish", finishReason: _, usage: g }), h.close(), A(), c({ finishReason: _, usage: g });
679
+ return;
680
+ }
681
+ const C = E(v);
682
+ for (const b of C) h.enqueue(b);
683
+ if (C.length) return;
684
+ }
685
+ } catch (T) {
686
+ A(), l(T), h.error(T);
687
+ }
688
+ },
689
+ async cancel() {
690
+ A(), await u.interruptGenerate(), await d.return?.(), c({ finishReason: "stop", usage: g });
691
+ }
692
+ }), response: p };
693
+ }
694
+ };
695
+ }
696
+ const K = [
697
+ "temperature",
698
+ "top_p",
699
+ "max_tokens",
700
+ "frequency_penalty",
701
+ "presence_penalty",
702
+ "seed",
703
+ "stop",
704
+ "logit_bias",
705
+ "extra_body"
706
+ ];
707
+ function B(t) {
708
+ const e = {};
709
+ if (!t) return e;
710
+ for (const o of K)
711
+ t[o] !== void 0 && (e[o] = t[o]);
712
+ return t.maxTokens !== void 0 && e.max_tokens === void 0 && (e.max_tokens = t.maxTokens), e;
713
+ }
714
+ function F(t) {
715
+ return t.map((e) => {
716
+ if (e.role === "tool")
717
+ return {
718
+ role: "tool",
719
+ content: typeof e.content == "string" ? e.content : JSON.stringify(e.content),
720
+ tool_call_id: e.toolCallId
721
+ };
722
+ if (e.role === "assistant" && e.toolCalls?.length)
723
+ return {
724
+ role: "assistant",
725
+ content: typeof e.content == "string" ? e.content : "",
726
+ tool_calls: e.toolCalls.map((a) => ({
727
+ id: a.id,
728
+ type: "function",
729
+ function: {
730
+ name: a.name,
731
+ arguments: typeof a.args == "string" ? a.args : JSON.stringify(a.args)
732
+ }
733
+ }))
734
+ };
735
+ if (typeof e.content == "string")
736
+ return { role: e.role, content: e.content };
737
+ const o = e.content.map(H);
738
+ return e.role !== "user" || o.every((a) => a.type === "text") ? { role: e.role, content: o.map((a) => a.type === "text" ? a.text : "").join(`
739
+ `) } : { role: e.role, content: o };
740
+ });
741
+ }
742
+ function H(t) {
743
+ if (t.type === "text") return { type: "text", text: t.text };
744
+ const e = x(t);
745
+ if (e.mediaType.startsWith("image/"))
746
+ return { type: "image_url", image_url: { url: e.url } };
747
+ if (e.base64 && O(e.mediaType))
748
+ return { type: "text", text: I(e.base64) };
749
+ throw new Error(`[vue-llm] In-browser models do not support ${e.mediaType} attachments`);
750
+ }
751
+ const z = "<think>", X = "</think>";
752
+ function q() {
753
+ let t = "", e = !1, o = !1;
754
+ const a = (i, s) => {
755
+ i && s.push(e ? { type: "reasoning-delta", text: i } : { type: "text-delta", text: i });
756
+ };
757
+ return {
758
+ push(i) {
759
+ const s = [];
760
+ for (t += i; t; ) {
761
+ if (o) {
762
+ if (t = t.replace(/^\s+/, ""), !t) break;
763
+ o = !1;
764
+ }
765
+ const n = e ? X : z, u = t.indexOf(n);
766
+ if (u !== -1) {
767
+ a(t.slice(0, u), s), t = t.slice(u + n.length), e = !e, o = !0;
768
+ continue;
769
+ }
770
+ const f = Q(t, n);
771
+ a(t.slice(0, t.length - f), s), t = t.slice(t.length - f);
772
+ break;
773
+ }
774
+ return s;
775
+ },
776
+ flush() {
777
+ const i = [];
778
+ return a(t, i), t = "", i;
779
+ }
780
+ };
781
+ }
782
+ function Q(t, e) {
783
+ for (let o = Math.min(e.length - 1, t.length); o > 0; o--)
784
+ if (e.startsWith(t.slice(-o))) return o;
785
+ return 0;
786
+ }
570
787
  export {
571
- M as createAnthropic,
572
- $ as createGoogle,
573
- j as createOllama,
574
- U as createOpenAI,
575
- L as createSSEProvider
788
+ oe as createAnthropic,
789
+ ne as createGoogle,
790
+ ae as createOllama,
791
+ te as createOpenAI,
792
+ le as createSSEProvider,
793
+ se as createWebLLM,
794
+ D as isWebGPUSupported
576
795
  };