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