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/providers.js CHANGED
@@ -1,63 +1,65 @@
1
+ import { r as T, i as _, d as b } from "./file-x_kW7BHa.js";
2
+ import { c as v } from "./errors-B3A_zmVE.js";
1
3
  class k extends TransformStream {
2
4
  constructor() {
3
5
  let e = "";
4
6
  super({
5
- transform(t, u) {
6
- e += t;
7
- const s = e.split(`
7
+ transform(n, a) {
8
+ e += n;
9
+ const i = e.split(`
8
10
  `);
9
- e = s.pop() ?? "";
10
- let o = {};
11
- for (const c of s) {
12
- if (c === "") {
13
- o.data !== void 0 && u.enqueue({
14
- event: o.event,
15
- data: o.data,
16
- id: o.id,
17
- retry: o.retry
18
- }), o = {};
11
+ e = i.pop() ?? "";
12
+ let t = {};
13
+ for (const o of i) {
14
+ if (o === "") {
15
+ t.data !== void 0 && a.enqueue({
16
+ event: t.event,
17
+ data: t.data,
18
+ id: t.id,
19
+ retry: t.retry
20
+ }), t = {};
19
21
  continue;
20
22
  }
21
- if (c.startsWith(":")) continue;
22
- const d = c.indexOf(":");
23
- if (d === -1) continue;
24
- const f = c.slice(0, d), i = c.slice(d + 1).replace(/^ /, "");
23
+ if (o.startsWith(":")) continue;
24
+ const u = o.indexOf(":");
25
+ if (u === -1) continue;
26
+ const f = o.slice(0, u), d = o.slice(u + 1).replace(/^ /, "");
25
27
  switch (f) {
26
28
  case "event":
27
- o.event = i;
29
+ t.event = d;
28
30
  break;
29
31
  case "data":
30
- o.data = o.data !== void 0 ? o.data + `
31
- ` + i : i;
32
+ t.data = t.data !== void 0 ? t.data + `
33
+ ` + d : d;
32
34
  break;
33
35
  case "id":
34
- o.id = i;
36
+ t.id = d;
35
37
  break;
36
38
  case "retry":
37
- o.retry = parseInt(i, 10);
39
+ t.retry = parseInt(d, 10);
38
40
  break;
39
41
  }
40
42
  }
41
43
  },
42
- flush(t) {
44
+ flush(n) {
43
45
  if (e.trim()) {
44
- const u = e.split(`
46
+ const a = e.split(`
45
47
  `);
46
- let s = {};
47
- for (const o of u) {
48
- if (o === "" && s.data !== void 0) {
49
- t.enqueue({
50
- event: s.event,
51
- data: s.data,
52
- id: s.id,
53
- retry: s.retry
54
- }), s = {};
48
+ let i = {};
49
+ for (const t of a) {
50
+ if (t === "" && i.data !== void 0) {
51
+ n.enqueue({
52
+ event: i.event,
53
+ data: i.data,
54
+ id: i.id,
55
+ retry: i.retry
56
+ }), i = {};
55
57
  continue;
56
58
  }
57
- const c = o.indexOf(":");
58
- if (c === -1 || o.startsWith(":")) continue;
59
- const d = o.slice(0, c), f = o.slice(c + 1).replace(/^ /, "");
60
- d === "data" && (s.data = s.data !== void 0 ? s.data + `
59
+ const o = t.indexOf(":");
60
+ if (o === -1 || t.startsWith(":")) continue;
61
+ const u = t.slice(0, o), f = t.slice(o + 1).replace(/^ /, "");
62
+ u === "data" && (i.data = i.data !== void 0 ? i.data + `
61
63
  ` + f : f);
62
64
  }
63
65
  }
@@ -65,26 +67,26 @@ class k extends TransformStream {
65
67
  });
66
68
  }
67
69
  }
68
- function b(p) {
70
+ function J(s) {
69
71
  return {
70
72
  id: "openai",
71
73
  supportsStreaming: !0,
72
74
  validateConfig() {
73
- if (!p.apiKey)
75
+ if (!s.apiKey)
74
76
  throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');
75
- if (!p.dangerouslyAllowBrowser && typeof window < "u")
77
+ if (!s.dangerouslyAllowBrowser && typeof window < "u")
76
78
  throw new Error(
77
79
  "[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."
78
80
  );
79
81
  },
80
82
  async chat(e) {
81
- const t = p.baseURL ?? "https://api.openai.com/v1/chat/completions", u = {
83
+ const n = s.baseURL ?? "https://api.openai.com/v1/chat/completions", a = {
82
84
  model: e.model,
83
- messages: v(e.messages),
85
+ messages: x(e.messages),
84
86
  stream: !0,
85
87
  stream_options: { include_usage: !0 }
86
88
  };
87
- e.tools?.length && (u.tools = e.tools.map((f) => ({
89
+ e.providerOptions?.response_format && (a.response_format = e.providerOptions.response_format), e.tools?.length && (a.tools = e.tools.map((f) => ({
88
90
  type: "function",
89
91
  function: {
90
92
  name: f.name,
@@ -92,181 +94,204 @@ function b(p) {
92
94
  parameters: f.parameters
93
95
  }
94
96
  })));
95
- const s = await fetch(t, {
97
+ const i = await fetch(n, {
96
98
  method: "POST",
97
99
  headers: {
98
- Authorization: `Bearer ${p.apiKey}`,
99
- "Content-Type": "application/json"
100
+ Authorization: `Bearer ${s.apiKey}`,
101
+ "Content-Type": "application/json",
102
+ ...e.providerOptions?.headers
100
103
  },
101
- body: JSON.stringify(u),
104
+ body: JSON.stringify(a),
102
105
  signal: e.signal
103
106
  });
104
- if (!s.ok) {
105
- const f = await s.text();
106
- throw new Error(`[vue-llm] OpenAI API error ${s.status}: ${f}`);
107
- }
108
- if (!s.body)
107
+ if (!i.ok)
108
+ throw await v("openai", "OpenAI API", i);
109
+ if (!i.body)
109
110
  throw new Error("[vue-llm] No response body from OpenAI");
110
- let o;
111
- const c = new Promise((f) => {
112
- o = f;
111
+ let t;
112
+ const o = new Promise((f) => {
113
+ t = f;
113
114
  });
114
- return { stream: s.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
115
- transform(f, i) {
115
+ return { stream: i.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
116
+ transform(f, d) {
116
117
  if (f.data === "[DONE]") return;
117
- let m;
118
+ let y;
118
119
  try {
119
- m = JSON.parse(f.data);
120
+ y = JSON.parse(f.data);
120
121
  } catch {
121
122
  return;
122
123
  }
123
- const l = m.choices?.[0];
124
- if (!l) {
125
- m.usage && o({
124
+ const c = y.choices?.[0];
125
+ if (!c) {
126
+ y.usage && t({
126
127
  finishReason: "stop",
127
128
  usage: {
128
- promptTokens: m.usage.prompt_tokens,
129
- completionTokens: m.usage.completion_tokens,
130
- totalTokens: m.usage.total_tokens
129
+ promptTokens: y.usage.prompt_tokens,
130
+ completionTokens: y.usage.completion_tokens,
131
+ totalTokens: y.usage.total_tokens
131
132
  }
132
133
  });
133
134
  return;
134
135
  }
135
- const r = l.delta;
136
- if (r.content && i.enqueue({ type: "text-delta", text: r.content }), r.tool_calls)
137
- for (const n of r.tool_calls)
138
- n.id && i.enqueue({
136
+ const l = c.delta;
137
+ if (l.content && d.enqueue({ type: "text-delta", text: l.content }), l.tool_calls)
138
+ for (const p of l.tool_calls)
139
+ p.id && d.enqueue({
139
140
  type: "tool-call-start",
140
- toolCallId: n.id,
141
- toolName: n.function?.name ?? ""
142
- }), n.function?.arguments && i.enqueue({
141
+ toolCallId: p.id,
142
+ toolName: p.function?.name ?? ""
143
+ }), p.function?.arguments && d.enqueue({
143
144
  type: "tool-call-delta",
144
- toolCallId: n.id ?? "",
145
- args: n.function.arguments
145
+ toolCallId: p.id ?? "",
146
+ args: p.function.arguments
146
147
  });
147
- if (l.finish_reason) {
148
- const n = r.tool_calls?.filter((a) => a.id) ?? [];
149
- for (const a of n)
150
- a.id && i.enqueue({ type: "tool-call-end", toolCallId: a.id });
151
- const h = l.finish_reason === "tool_calls" ? "tool-calls" : l.finish_reason === "length" ? "length" : "stop";
152
- i.enqueue({ type: "finish", finishReason: h, usage: void 0 });
148
+ if (c.finish_reason) {
149
+ const p = l.tool_calls?.filter((r) => r.id) ?? [];
150
+ for (const r of p)
151
+ r.id && d.enqueue({ type: "tool-call-end", toolCallId: r.id });
152
+ const m = c.finish_reason === "tool_calls" ? "tool-calls" : c.finish_reason === "length" ? "length" : "stop";
153
+ d.enqueue({ type: "finish", finishReason: m, usage: void 0 });
153
154
  }
154
155
  }
155
- })), response: c };
156
+ })), response: o };
156
157
  }
157
158
  };
158
159
  }
159
- function v(p) {
160
- return p.map((e) => e.role === "tool" ? {
160
+ function x(s) {
161
+ return s.map((e) => e.role === "tool" ? {
161
162
  role: "tool",
162
163
  content: typeof e.content == "string" ? e.content : JSON.stringify(e.content),
163
164
  tool_call_id: e.toolCallId
164
165
  } : e.role === "assistant" && e.toolCalls?.length ? {
165
166
  role: "assistant",
166
167
  content: typeof e.content == "string" && e.content ? e.content : null,
167
- tool_calls: e.toolCalls.map((t) => ({
168
- id: t.id,
168
+ tool_calls: e.toolCalls.map((n) => ({
169
+ id: n.id,
169
170
  type: "function",
170
171
  function: {
171
- name: t.name,
172
- arguments: typeof t.args == "string" ? t.args : JSON.stringify(t.args)
172
+ name: n.name,
173
+ arguments: typeof n.args == "string" ? n.args : JSON.stringify(n.args)
173
174
  }
174
175
  }))
175
176
  } : {
176
177
  role: e.role,
177
- content: typeof e.content == "string" ? e.content : e.content.map((t) => t.type === "text" ? { type: "text", text: t.text } : t.type === "image" ? { type: "image_url", image_url: { url: t.url } } : t)
178
+ content: typeof e.content == "string" ? e.content : e.content.map(C)
178
179
  });
179
180
  }
180
- function C(p) {
181
+ function C(s) {
182
+ if (s.type === "text") return { type: "text", text: s.text };
183
+ const e = T(s);
184
+ if (e.mediaType.startsWith("image/"))
185
+ return { type: "image_url", image_url: { url: e.url } };
186
+ if (!e.base64)
187
+ throw new Error(`[vue-llm] OpenAI requires ${e.mediaType} attachments as data URLs, got a remote URL`);
188
+ if (e.mediaType === "application/pdf")
189
+ return {
190
+ type: "file",
191
+ file: { filename: e.filename ?? "document.pdf", file_data: e.url }
192
+ };
193
+ const n = O[e.mediaType];
194
+ if (n)
195
+ return { type: "input_audio", input_audio: { data: e.base64, format: n } };
196
+ if (_(e.mediaType))
197
+ return { type: "text", text: b(e.base64) };
198
+ throw new Error(`[vue-llm] OpenAI does not support ${e.mediaType} attachments`);
199
+ }
200
+ const O = {
201
+ "audio/wav": "wav",
202
+ "audio/x-wav": "wav",
203
+ "audio/mpeg": "mp3",
204
+ "audio/mp3": "mp3"
205
+ };
206
+ function U(s) {
181
207
  return {
182
208
  id: "anthropic",
183
209
  supportsStreaming: !0,
184
210
  validateConfig() {
185
- if (!p.apiKey)
211
+ if (!s.apiKey)
186
212
  throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');
187
- if (!p.dangerouslyAllowBrowser && typeof window < "u")
213
+ if (!s.dangerouslyAllowBrowser && typeof window < "u")
188
214
  throw new Error(
189
215
  "[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."
190
216
  );
191
217
  },
192
218
  async chat(e) {
193
- const t = (p.baseURL ?? "https://api.anthropic.com") + "/v1/messages", u = e.messages.find((l) => l.role === "system"), s = e.messages.filter((l) => l.role !== "system"), o = {
219
+ const n = (s.baseURL ?? "https://api.anthropic.com") + "/v1/messages", a = e.messages.find((c) => c.role === "system"), i = e.messages.filter((c) => c.role !== "system"), t = {
194
220
  model: e.model,
195
- messages: x(s),
221
+ messages: I(i),
196
222
  max_tokens: e.providerOptions?.maxTokens ?? 4096,
197
223
  stream: !0
198
224
  };
199
- u && (o.system = typeof u.content == "string" ? u.content : u.content.map((l) => ({ type: "text", text: l.type === "text" ? l.text : "" }))), e.tools?.length && (o.tools = e.tools.map((l) => ({
200
- name: l.name,
201
- description: l.description,
202
- input_schema: l.parameters
225
+ a && (t.system = typeof a.content == "string" ? a.content : a.content.map((c) => ({ type: "text", text: c.type === "text" ? c.text : "" }))), e.tools?.length && (t.tools = e.tools.map((c) => ({
226
+ name: c.name,
227
+ description: c.description,
228
+ input_schema: c.parameters
203
229
  })));
204
- const c = await fetch(t, {
230
+ const o = await fetch(n, {
205
231
  method: "POST",
206
232
  headers: {
207
- "x-api-key": p.apiKey,
233
+ "x-api-key": s.apiKey,
208
234
  "anthropic-version": "2023-06-01",
209
- "Content-Type": "application/json"
235
+ "Content-Type": "application/json",
236
+ ...e.providerOptions?.headers
210
237
  },
211
- body: JSON.stringify(o),
238
+ body: JSON.stringify(t),
212
239
  signal: e.signal
213
240
  });
214
- if (!c.ok) {
215
- const l = await c.text();
216
- throw new Error(`[vue-llm] Anthropic API error ${c.status}: ${l}`);
217
- }
218
- if (!c.body)
241
+ if (!o.ok)
242
+ throw await v("anthropic", "Anthropic API", o);
243
+ if (!o.body)
219
244
  throw new Error("[vue-llm] No response body from Anthropic");
220
- let d;
221
- const f = new Promise((l) => {
222
- d = l;
245
+ let u;
246
+ const f = new Promise((c) => {
247
+ u = c;
223
248
  });
224
- let i = "";
225
- return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
226
- transform(l, r) {
227
- let n;
249
+ let d = "";
250
+ return { stream: o.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
251
+ transform(c, l) {
252
+ let p;
228
253
  try {
229
- n = JSON.parse(l.data);
254
+ p = JSON.parse(c.data);
230
255
  } catch {
231
256
  return;
232
257
  }
233
- switch (l.event ?? n.type) {
258
+ switch (c.event ?? p.type) {
234
259
  case "content_block_start": {
235
- const a = n.content_block;
236
- a?.type === "tool_use" && (i = a.id, r.enqueue({
260
+ const r = p.content_block;
261
+ r?.type === "tool_use" && (d = r.id, l.enqueue({
237
262
  type: "tool-call-start",
238
- toolCallId: i,
239
- toolName: a.name
263
+ toolCallId: d,
264
+ toolName: r.name
240
265
  }));
241
266
  break;
242
267
  }
243
268
  case "content_block_delta": {
244
- const a = n.delta;
245
- a?.type === "text_delta" && a.text && r.enqueue({ type: "text-delta", text: a.text }), a?.type === "thinking_delta" && a.text && r.enqueue({ type: "reasoning-delta", text: a.text }), a?.type === "input_json_delta" && a.partial_json && r.enqueue({
269
+ const r = p.delta;
270
+ 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({
246
271
  type: "tool-call-delta",
247
- toolCallId: i,
248
- args: a.partial_json
272
+ toolCallId: d,
273
+ args: r.partial_json
249
274
  });
250
275
  break;
251
276
  }
252
277
  case "content_block_stop": {
253
- i && (r.enqueue({ type: "tool-call-end", toolCallId: i }), i = "");
278
+ d && (l.enqueue({ type: "tool-call-end", toolCallId: d }), d = "");
254
279
  break;
255
280
  }
256
281
  case "message_delta": {
257
- const a = n.delta, w = n.usage, g = a?.stop_reason === "tool_use" ? "tool-calls" : a?.stop_reason === "max_tokens" ? "length" : "stop";
258
- r.enqueue({
282
+ const r = p.delta, w = p.usage, g = r?.stop_reason === "tool_use" ? "tool-calls" : r?.stop_reason === "max_tokens" ? "length" : "stop";
283
+ l.enqueue({
259
284
  type: "finish",
260
285
  finishReason: g,
261
286
  usage: w ? { promptTokens: 0, completionTokens: w.output_tokens ?? 0, totalTokens: w.output_tokens ?? 0 } : void 0
262
- }), d({ finishReason: g, usage: void 0 });
287
+ }), u({ finishReason: g, usage: void 0 });
263
288
  break;
264
289
  }
265
290
  case "error": {
266
- const a = n.error;
267
- r.enqueue({
291
+ const r = p.error;
292
+ l.enqueue({
268
293
  type: "error",
269
- error: new Error(`[vue-llm] Anthropic stream error: ${a?.message ?? "unknown"}`)
294
+ error: new Error(`[vue-llm] Anthropic stream error: ${r?.message ?? "unknown"}`)
270
295
  });
271
296
  break;
272
297
  }
@@ -276,8 +301,8 @@ function C(p) {
276
301
  }
277
302
  };
278
303
  }
279
- function x(p) {
280
- return p.map((e) => {
304
+ function I(s) {
305
+ return s.map((e) => {
281
306
  if (e.role === "tool")
282
307
  return {
283
308
  role: "user",
@@ -288,126 +313,139 @@ function x(p) {
288
313
  }]
289
314
  };
290
315
  if (e.role === "assistant" && e.toolCalls?.length) {
291
- const t = [];
292
- typeof e.content == "string" && e.content && t.push({ type: "text", text: e.content });
293
- for (const u of e.toolCalls)
294
- t.push({
316
+ const n = [];
317
+ typeof e.content == "string" && e.content && n.push({ type: "text", text: e.content });
318
+ for (const a of e.toolCalls)
319
+ n.push({
295
320
  type: "tool_use",
296
- id: u.id,
297
- name: u.name,
298
- input: u.args
321
+ id: a.id,
322
+ name: a.name,
323
+ input: a.args
299
324
  });
300
- return { role: "assistant", content: t };
325
+ return { role: "assistant", content: n };
301
326
  }
302
327
  return {
303
328
  role: e.role,
304
- content: typeof e.content == "string" ? e.content : e.content.map((t) => t.type === "text" ? { type: "text", text: t.text } : t.type === "image" ? {
305
- type: "image",
306
- source: { type: "url", url: t.url, media_type: t.mediaType ?? "image/png" }
307
- } : t)
329
+ content: typeof e.content == "string" ? e.content : e.content.map(A)
308
330
  };
309
331
  });
310
332
  }
311
- function I(p) {
333
+ function A(s) {
334
+ if (s.type === "text") return { type: "text", text: s.text };
335
+ const e = T(s), n = e.base64 ? { type: "base64", media_type: e.mediaType, data: e.base64 } : { type: "url", url: e.url };
336
+ if (e.mediaType.startsWith("image/"))
337
+ return { type: "image", source: n };
338
+ if (e.mediaType === "application/pdf")
339
+ return { type: "document", source: n, ...e.filename ? { title: e.filename } : {} };
340
+ if (_(e.mediaType) && e.base64)
341
+ return {
342
+ type: "document",
343
+ source: { type: "text", media_type: "text/plain", data: b(e.base64) },
344
+ ...e.filename ? { title: e.filename } : {}
345
+ };
346
+ throw new Error(`[vue-llm] Anthropic does not support ${e.mediaType} attachments`);
347
+ }
348
+ function M(s) {
312
349
  return {
313
350
  id: "google",
314
351
  supportsStreaming: !0,
315
352
  validateConfig() {
316
- if (!p.apiKey)
353
+ if (!s.apiKey)
317
354
  throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');
318
- if (!p.dangerouslyAllowBrowser && typeof window < "u")
355
+ if (!s.dangerouslyAllowBrowser && typeof window < "u")
319
356
  throw new Error(
320
357
  "[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."
321
358
  );
322
359
  },
323
360
  async chat(e) {
324
- const u = `${p.baseURL ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${p.apiKey}`, s = {
325
- contents: T(e.messages)
326
- }, o = e.messages.find((r) => r.role === "system");
327
- o && (s.systemInstruction = {
328
- parts: [{ text: typeof o.content == "string" ? o.content : "" }]
329
- }), e.tools?.length && (s.tools = [{
330
- functionDeclarations: e.tools.map((r) => ({
331
- name: r.name,
332
- description: r.description,
333
- parameters: r.parameters
361
+ const a = `${s.baseURL ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${s.apiKey}`, i = {
362
+ contents: S(e.messages)
363
+ }, t = e.messages.find((l) => l.role === "system");
364
+ t && (i.systemInstruction = {
365
+ parts: [{ text: typeof t.content == "string" ? t.content : "" }]
366
+ }), e.tools?.length && (i.tools = [{
367
+ functionDeclarations: e.tools.map((l) => ({
368
+ name: l.name,
369
+ description: l.description,
370
+ parameters: l.parameters
334
371
  }))
335
- }]), s.generationConfig = {
372
+ }]), i.generationConfig = {
336
373
  ...e.providerOptions?.response_format?.type === "json_object" ? { responseMimeType: "application/json" } : {}
337
374
  };
338
- const c = await fetch(u, {
375
+ const o = await fetch(a, {
339
376
  method: "POST",
340
- headers: { "Content-Type": "application/json" },
341
- body: JSON.stringify(s),
377
+ headers: {
378
+ "Content-Type": "application/json",
379
+ ...e.providerOptions?.headers
380
+ },
381
+ body: JSON.stringify(i),
342
382
  signal: e.signal
343
383
  });
344
- if (!c.ok) {
345
- const r = await c.text();
346
- throw new Error(`[vue-llm] Google AI API error ${c.status}: ${r}`);
347
- }
348
- if (!c.body)
384
+ if (!o.ok)
385
+ throw await v("google", "Google AI API", o);
386
+ if (!o.body)
349
387
  throw new Error("[vue-llm] No response body from Google AI");
350
- let d;
351
- const f = new Promise((r) => {
352
- d = r;
353
- }), i = /* @__PURE__ */ new Map();
354
- let m = 0;
355
- return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
388
+ let u;
389
+ const f = new Promise((l) => {
390
+ u = l;
391
+ });
392
+ let d = 0, y = !1;
393
+ return { stream: o.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
356
394
  buffer: "",
357
- transform(r, n) {
358
- this.buffer += r;
359
- const h = this.buffer.split(`
395
+ transform(l, p) {
396
+ this.buffer += l;
397
+ const m = this.buffer.split(`
360
398
  `);
361
- this.buffer = h.pop();
362
- for (const a of h)
363
- a.startsWith("data: ") && n.enqueue(a.slice(6));
399
+ this.buffer = m.pop();
400
+ for (const r of m)
401
+ r.startsWith("data: ") && p.enqueue(r.slice(6));
364
402
  },
365
- flush(r) {
366
- const n = this.buffer.trim();
367
- n.startsWith("data: ") && r.enqueue(n.slice(6));
403
+ flush(l) {
404
+ const p = this.buffer.trim();
405
+ p.startsWith("data: ") && l.enqueue(p.slice(6));
368
406
  }
369
407
  })).pipeThrough(new TransformStream({
370
- transform(r, n) {
371
- let h;
408
+ transform(l, p) {
409
+ let m;
372
410
  try {
373
- h = JSON.parse(r);
411
+ m = JSON.parse(l);
374
412
  } catch {
375
413
  return;
376
414
  }
377
- const a = h.candidates?.[0];
378
- if (!a) return;
379
- const w = a.content?.parts;
415
+ const r = m.candidates?.[0];
416
+ if (!r) return;
417
+ const w = r.content?.parts;
380
418
  if (w) {
381
419
  for (const g of w)
382
- if (g.text !== void 0 && n.enqueue({ type: "text-delta", text: g.text }), g.functionCall) {
383
- const y = `tc_gemini_${++m}`;
384
- i.set(g.functionCall.name, y), n.enqueue({
420
+ if (g.text !== void 0 && p.enqueue({ type: "text-delta", text: g.text }), g.functionCall) {
421
+ const h = `tc_gemini_${++d}`;
422
+ y = !0, p.enqueue({
385
423
  type: "tool-call-start",
386
- toolCallId: y,
424
+ toolCallId: h,
387
425
  toolName: g.functionCall.name
388
- }), n.enqueue({
426
+ }), p.enqueue({
389
427
  type: "tool-call-delta",
390
- toolCallId: y,
428
+ toolCallId: h,
391
429
  args: JSON.stringify(g.functionCall.args ?? {})
392
- }), n.enqueue({ type: "tool-call-end", toolCallId: y });
430
+ }), p.enqueue({ type: "tool-call-end", toolCallId: h });
393
431
  }
394
432
  }
395
- if (a.finishReason) {
396
- const g = a.finishReason === "STOP" ? "stop" : a.finishReason === "MAX_TOKENS" ? "length" : a.finishReason === "TOOL_CALLS" ? "tool-calls" : "stop", y = h.usageMetadata;
397
- n.enqueue({
433
+ if (r.finishReason) {
434
+ const g = y ? "tool-calls" : r.finishReason === "MAX_TOKENS" ? "length" : "stop", h = m.usageMetadata;
435
+ p.enqueue({
398
436
  type: "finish",
399
437
  finishReason: g,
400
- usage: y ? {
401
- promptTokens: y.promptTokenCount ?? 0,
402
- completionTokens: y.candidatesTokenCount ?? 0,
403
- totalTokens: y.totalTokenCount ?? 0
438
+ usage: h ? {
439
+ promptTokens: h.promptTokenCount ?? 0,
440
+ completionTokens: h.candidatesTokenCount ?? 0,
441
+ totalTokens: h.totalTokenCount ?? 0
404
442
  } : void 0
405
- }), d({
443
+ }), u({
406
444
  finishReason: g,
407
- usage: y ? {
408
- promptTokens: y.promptTokenCount ?? 0,
409
- completionTokens: y.candidatesTokenCount ?? 0,
410
- totalTokens: y.totalTokenCount ?? 0
445
+ usage: h ? {
446
+ promptTokens: h.promptTokenCount ?? 0,
447
+ completionTokens: h.candidatesTokenCount ?? 0,
448
+ totalTokens: h.totalTokenCount ?? 0
411
449
  } : void 0
412
450
  });
413
451
  }
@@ -416,127 +454,187 @@ function I(p) {
416
454
  }
417
455
  };
418
456
  }
419
- function T(p) {
420
- const e = [];
421
- for (const t of p) {
422
- if (t.role === "system") continue;
423
- if (t.role === "tool") {
424
- e.push({
425
- role: "function",
426
- parts: [{
427
- functionResponse: {
428
- name: t.toolCallId ?? "",
429
- response: { result: typeof t.content == "string" ? JSON.parse(t.content) : t.content }
430
- }
431
- }]
432
- });
457
+ function S(s) {
458
+ const e = [], n = /* @__PURE__ */ new Map();
459
+ for (const a of s) {
460
+ if (a.role === "system") continue;
461
+ if (a.role === "tool") {
462
+ const o = {
463
+ functionResponse: {
464
+ name: n.get(a.toolCallId ?? "") ?? a.toolCallId ?? "",
465
+ response: { result: P(a.content) }
466
+ }
467
+ }, u = e.at(-1);
468
+ u?.role === "user" && u.parts.every((f) => f.functionResponse) ? u.parts.push(o) : e.push({ role: "user", parts: [o] });
433
469
  continue;
434
470
  }
435
- const u = t.role === "assistant" ? "model" : "user", s = [];
436
- if (typeof t.content == "string")
437
- t.content && s.push({ text: t.content });
438
- else if (Array.isArray(t.content))
439
- for (const o of t.content)
440
- o.type === "text" && s.push({ text: o.text }), o.type === "image" && s.push({ inlineData: { mimeType: "image/jpeg", data: o.url } });
441
- if (t.toolCalls?.length)
442
- for (const o of t.toolCalls)
443
- s.push({
471
+ for (const o of a.toolCalls ?? [])
472
+ n.set(o.id, o.name);
473
+ const i = a.role === "assistant" ? "model" : "user", t = [];
474
+ if (typeof a.content == "string")
475
+ a.content && t.push({ text: a.content });
476
+ else if (Array.isArray(a.content)) {
477
+ for (const o of a.content)
478
+ if (o.type === "text" && t.push({ text: o.text }), o.type === "image" || o.type === "file") {
479
+ const u = T(o);
480
+ t.push(u.base64 ? { inlineData: { mimeType: u.mediaType, data: u.base64 } } : { fileData: { mimeType: u.mediaType, fileUri: u.url } });
481
+ }
482
+ }
483
+ if (a.toolCalls?.length)
484
+ for (const o of a.toolCalls)
485
+ t.push({
444
486
  functionCall: {
445
487
  name: o.name,
446
488
  args: typeof o.args == "string" ? JSON.parse(o.args) : o.args
447
489
  }
448
490
  });
449
- s.length > 0 && e.push({ role: u, parts: s });
491
+ t.length > 0 && e.push({ role: i, parts: t });
450
492
  }
451
493
  return e;
452
494
  }
453
- function S(p) {
495
+ function P(s) {
496
+ if (typeof s != "string") return s;
497
+ try {
498
+ return JSON.parse(s);
499
+ } catch {
500
+ return s;
501
+ }
502
+ }
503
+ function $(s) {
454
504
  return {
455
505
  id: "ollama",
456
506
  supportsStreaming: !0,
457
507
  validateConfig() {
458
508
  },
459
509
  async chat(e) {
460
- const t = (p?.baseURL ?? "http://localhost:11434") + "/api/chat", u = {
510
+ const n = (s?.baseURL ?? "http://localhost:11434") + "/api/chat", a = {
461
511
  model: e.model,
462
- messages: _(e.messages),
512
+ messages: N(e.messages),
463
513
  stream: !0
464
514
  };
465
- e.tools?.length && (u.tools = e.tools.map((i) => ({
515
+ e.tools?.length && (a.tools = e.tools.map((y) => ({
466
516
  type: "function",
467
517
  function: {
468
- name: i.name,
469
- description: i.description,
470
- parameters: i.parameters
518
+ name: y.name,
519
+ description: y.description,
520
+ parameters: y.parameters
471
521
  }
472
522
  })));
473
- const s = await fetch(t, {
523
+ const i = await fetch(n, {
474
524
  method: "POST",
475
- headers: { "Content-Type": "application/json" },
476
- body: JSON.stringify(u),
525
+ headers: {
526
+ "Content-Type": "application/json",
527
+ ...e.providerOptions?.headers
528
+ },
529
+ body: JSON.stringify(a),
477
530
  signal: e.signal
478
531
  });
479
- if (!s.ok) {
480
- const i = await s.text();
481
- throw new Error(`[vue-llm] Ollama API error ${s.status}: ${i}`);
482
- }
483
- if (!s.body)
532
+ if (!i.ok)
533
+ throw await v("ollama", "Ollama API", i);
534
+ if (!i.body)
484
535
  throw new Error("[vue-llm] No response body from Ollama");
485
- let o;
486
- const c = new Promise((i) => {
487
- o = i;
536
+ let t;
537
+ const o = new Promise((y) => {
538
+ t = y;
488
539
  });
489
- let d = "";
490
- return { stream: s.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
491
- transform(i, m) {
492
- d += i;
493
- const l = d.split(`
540
+ let u = "", f = !1;
541
+ return { stream: i.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
542
+ transform(y, c) {
543
+ u += y;
544
+ const l = u.split(`
494
545
  `);
495
- d = l.pop() ?? "";
496
- for (const r of l) {
497
- if (!r.trim()) continue;
498
- let n;
546
+ u = l.pop() ?? "";
547
+ for (const p of l) {
548
+ if (!p.trim()) continue;
549
+ let m;
499
550
  try {
500
- n = JSON.parse(r);
551
+ m = JSON.parse(p);
501
552
  } catch {
502
553
  continue;
503
554
  }
504
- if (n.message?.content && m.enqueue({ type: "text-delta", text: n.message.content }), n.message?.tool_calls)
505
- for (const h of n.message.tool_calls) {
506
- const a = `ollama-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
507
- m.enqueue({
555
+ if (m.message?.content && c.enqueue({ type: "text-delta", text: m.message.content }), m.message?.tool_calls)
556
+ for (const r of m.message.tool_calls) {
557
+ f = !0;
558
+ const w = `ollama-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
559
+ c.enqueue({
508
560
  type: "tool-call-start",
509
- toolCallId: a,
510
- toolName: h.function.name
511
- }), m.enqueue({
561
+ toolCallId: w,
562
+ toolName: r.function.name
563
+ }), c.enqueue({
512
564
  type: "tool-call-delta",
513
- toolCallId: a,
514
- args: JSON.stringify(h.function.arguments)
515
- }), m.enqueue({ type: "tool-call-end", toolCallId: a });
565
+ toolCallId: w,
566
+ args: JSON.stringify(r.function.arguments)
567
+ }), c.enqueue({ type: "tool-call-end", toolCallId: w });
516
568
  }
517
- n.done && (m.enqueue({ type: "finish", finishReason: "stop" }), o({
518
- finishReason: "stop",
519
- usage: n.eval_count ? {
520
- promptTokens: n.prompt_eval_count ?? 0,
521
- completionTokens: n.eval_count,
522
- totalTokens: (n.prompt_eval_count ?? 0) + n.eval_count
523
- } : void 0
524
- }));
569
+ if (m.done) {
570
+ const r = f ? "tool-calls" : "stop";
571
+ c.enqueue({ type: "finish", finishReason: r }), t({
572
+ finishReason: r,
573
+ usage: m.eval_count ? {
574
+ promptTokens: m.prompt_eval_count ?? 0,
575
+ completionTokens: m.eval_count,
576
+ totalTokens: (m.prompt_eval_count ?? 0) + m.eval_count
577
+ } : void 0
578
+ });
579
+ }
525
580
  }
526
581
  }
527
- })), response: c };
582
+ })), response: o };
528
583
  }
529
584
  };
530
585
  }
531
- function _(p) {
532
- return p.map((e) => ({
533
- role: e.role,
534
- content: typeof e.content == "string" ? e.content : e.content.map((t) => t.type === "text" ? t.text : "").join("")
535
- }));
586
+ function N(s) {
587
+ const e = /* @__PURE__ */ new Map();
588
+ return s.map((n) => {
589
+ if (n.role === "tool")
590
+ return {
591
+ role: "tool",
592
+ content: typeof n.content == "string" ? n.content : JSON.stringify(n.content),
593
+ tool_name: e.get(n.toolCallId ?? "")
594
+ };
595
+ if (n.role === "assistant" && n.toolCalls?.length) {
596
+ for (const t of n.toolCalls) e.set(t.id, t.name);
597
+ return {
598
+ role: "assistant",
599
+ content: typeof n.content == "string" ? n.content : "",
600
+ tool_calls: n.toolCalls.map((t) => ({
601
+ function: {
602
+ name: t.name,
603
+ arguments: typeof t.args == "string" ? JSON.parse(t.args) : t.args
604
+ }
605
+ }))
606
+ };
607
+ }
608
+ if (typeof n.content == "string")
609
+ return { role: n.role, content: n.content };
610
+ const a = [], i = [];
611
+ for (const t of n.content) {
612
+ if (t.type === "text") {
613
+ a.push(t.text);
614
+ continue;
615
+ }
616
+ const o = T(t);
617
+ if (!o.base64)
618
+ throw new Error("[vue-llm] Ollama requires attachments as data URLs, got a remote URL");
619
+ if (o.mediaType.startsWith("image/"))
620
+ i.push(o.base64);
621
+ else if (_(o.mediaType))
622
+ a.push(b(o.base64));
623
+ else
624
+ throw new Error(`[vue-llm] Ollama does not support ${o.mediaType} attachments`);
625
+ }
626
+ return {
627
+ role: n.role,
628
+ content: a.join(`
629
+
630
+ `),
631
+ ...i.length > 0 ? { images: i } : {}
632
+ };
633
+ });
536
634
  }
537
635
  export {
538
- C as createAnthropic,
539
- I as createGoogle,
540
- S as createOllama,
541
- b as createOpenAI
636
+ U as createAnthropic,
637
+ M as createGoogle,
638
+ $ as createOllama,
639
+ J as createOpenAI
542
640
  };