vue-llm 0.2.1 → 0.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/google.d.ts +7 -0
- package/dist/providers.cjs +7 -6
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +299 -156
- package/package.json +1 -1
package/dist/providers.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class
|
|
2
|
-
`);e=
|
|
3
|
-
`+
|
|
4
|
-
`);let
|
|
5
|
-
`+
|
|
6
|
-
`);
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class k extends TransformStream{constructor(){let e="";super({transform(t,u){e+=t;const s=e.split(`
|
|
2
|
+
`);e=s.pop()??"";let o={};for(const c of s){if(c===""){o.data!==void 0&&u.enqueue({event:o.event,data:o.data,id:o.id,retry:o.retry}),o={};continue}if(c.startsWith(":"))continue;const d=c.indexOf(":");if(d===-1)continue;const f=c.slice(0,d),i=c.slice(d+1).replace(/^ /,"");switch(f){case"event":o.event=i;break;case"data":o.data=o.data!==void 0?o.data+`
|
|
3
|
+
`+i:i;break;case"id":o.id=i;break;case"retry":o.retry=parseInt(i,10);break}}},flush(t){if(e.trim()){const u=e.split(`
|
|
4
|
+
`);let s={};for(const o of u){if(o===""&&s.data!==void 0){t.enqueue({event:s.event,data:s.data,id:s.id,retry:s.retry}),s={};continue}const c=o.indexOf(":");if(c===-1||o.startsWith(":"))continue;const d=o.slice(0,c),f=o.slice(c+1).replace(/^ /,"");d==="data"&&(s.data=s.data!==void 0?s.data+`
|
|
5
|
+
`+f:f)}}}})}}function v(p){return{id:"openai",supportsStreaming:!0,validateConfig(){if(!p.apiKey)throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');if(!p.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[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.")},async chat(e){const t=p.baseURL??"https://api.openai.com/v1/chat/completions",u={model:e.model,messages:T(e.messages),stream:!0,stream_options:{include_usage:!0}};e.tools?.length&&(u.tools=e.tools.map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})));const s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${p.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:e.signal});if(!s.ok){const f=await s.text();throw new Error(`[vue-llm] OpenAI API error ${s.status}: ${f}`)}if(!s.body)throw new Error("[vue-llm] No response body from OpenAI");let o;const c=new Promise(f=>{o=f});return{stream:s.body.pipeThrough(new TextDecoderStream).pipeThrough(new k).pipeThrough(new TransformStream({transform(f,i){if(f.data==="[DONE]")return;let m;try{m=JSON.parse(f.data)}catch{return}const l=m.choices?.[0];if(!l){m.usage&&o({finishReason:"stop",usage:{promptTokens:m.usage.prompt_tokens,completionTokens:m.usage.completion_tokens,totalTokens:m.usage.total_tokens}});return}const r=l.delta;if(r.content&&i.enqueue({type:"text-delta",text:r.content}),r.tool_calls)for(const n of r.tool_calls)n.id&&i.enqueue({type:"tool-call-start",toolCallId:n.id,toolName:n.function?.name??""}),n.function?.arguments&&i.enqueue({type:"tool-call-delta",toolCallId:n.id??"",args:n.function.arguments});if(l.finish_reason){const n=r.tool_calls?.filter(a=>a.id)??[];for(const a of n)a.id&&i.enqueue({type:"tool-call-end",toolCallId:a.id});const h=l.finish_reason==="tool_calls"?"tool-calls":l.finish_reason==="length"?"length":"stop";i.enqueue({type:"finish",finishReason:h,usage:void 0})}}})),response:c}}}}function T(p){return p.map(e=>e.role==="tool"?{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.toolCallId}:e.role==="assistant"&&e.toolCalls?.length?{role:"assistant",content:typeof e.content=="string"&&e.content?e.content:null,tool_calls:e.toolCalls.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:typeof t.args=="string"?t.args:JSON.stringify(t.args)}}))}:{role:e.role,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)})}function x(p){return{id:"anthropic",supportsStreaming:!0,validateConfig(){if(!p.apiKey)throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');if(!p.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[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.")},async chat(e){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={model:e.model,messages:_(s),max_tokens:e.providerOptions?.maxTokens??4096,stream:!0};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=>({name:l.name,description:l.description,input_schema:l.parameters})));const c=await fetch(t,{method:"POST",headers:{"x-api-key":p.apiKey,"anthropic-version":"2023-06-01","Content-Type":"application/json"},body:JSON.stringify(o),signal:e.signal});if(!c.ok){const l=await c.text();throw new Error(`[vue-llm] Anthropic API error ${c.status}: ${l}`)}if(!c.body)throw new Error("[vue-llm] No response body from Anthropic");let d;const f=new Promise(l=>{d=l});let i="";return{stream:c.body.pipeThrough(new TextDecoderStream).pipeThrough(new k).pipeThrough(new TransformStream({transform(l,r){let n;try{n=JSON.parse(l.data)}catch{return}switch(l.event??n.type){case"content_block_start":{const a=n.content_block;a?.type==="tool_use"&&(i=a.id,r.enqueue({type:"tool-call-start",toolCallId:i,toolName:a.name}));break}case"content_block_delta":{const a=n.delta;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({type:"tool-call-delta",toolCallId:i,args:a.partial_json});break}case"content_block_stop":{i&&(r.enqueue({type:"tool-call-end",toolCallId:i}),i="");break}case"message_delta":{const a=n.delta,w=n.usage,g=a?.stop_reason==="tool_use"?"tool-calls":a?.stop_reason==="max_tokens"?"length":"stop";r.enqueue({type:"finish",finishReason:g,usage:w?{promptTokens:0,completionTokens:w.output_tokens??0,totalTokens:w.output_tokens??0}:void 0}),d({finishReason:g,usage:void 0});break}case"error":{const a=n.error;r.enqueue({type:"error",error:new Error(`[vue-llm] Anthropic stream error: ${a?.message??"unknown"}`)});break}}}})),response:f}}}}function _(p){return p.map(e=>{if(e.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:e.toolCallId,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)}]};if(e.role==="assistant"&&e.toolCalls?.length){const t=[];typeof e.content=="string"&&e.content&&t.push({type:"text",text:e.content});for(const u of e.toolCalls)t.push({type:"tool_use",id:u.id,name:u.name,input:u.args});return{role:"assistant",content:t}}return{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?{type:"text",text:t.text}:t.type==="image"?{type:"image",source:{type:"url",url:t.url,media_type:t.mediaType??"image/png"}}:t)}})}function b(p){return{id:"google",supportsStreaming:!0,validateConfig(){if(!p.apiKey)throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');if(!p.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[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.")},async chat(e){const u=`${p.baseURL??"https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${p.apiKey}`,s={contents:C(e.messages)},o=e.messages.find(r=>r.role==="system");o&&(s.systemInstruction={parts:[{text:typeof o.content=="string"?o.content:""}]}),e.tools?.length&&(s.tools=[{functionDeclarations:e.tools.map(r=>({name:r.name,description:r.description,parameters:r.parameters}))}]),s.generationConfig={...e.providerOptions?.response_format?.type==="json_object"?{responseMimeType:"application/json"}:{}};const c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:e.signal});if(!c.ok){const r=await c.text();throw new Error(`[vue-llm] Google AI API error ${c.status}: ${r}`)}if(!c.body)throw new Error("[vue-llm] No response body from Google AI");let d;const f=new Promise(r=>{d=r}),i=new Map;let m=0;return{stream:c.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({buffer:"",transform(r,n){this.buffer+=r;const h=this.buffer.split(`
|
|
6
|
+
`);this.buffer=h.pop();for(const a of h)a.startsWith("data: ")&&n.enqueue(a.slice(6))},flush(r){const n=this.buffer.trim();n.startsWith("data: ")&&r.enqueue(n.slice(6))}})).pipeThrough(new TransformStream({transform(r,n){let h;try{h=JSON.parse(r)}catch{return}const a=h.candidates?.[0];if(!a)return;const w=a.content?.parts;if(w){for(const g of w)if(g.text!==void 0&&n.enqueue({type:"text-delta",text:g.text}),g.functionCall){const y=`tc_gemini_${++m}`;i.set(g.functionCall.name,y),n.enqueue({type:"tool-call-start",toolCallId:y,toolName:g.functionCall.name}),n.enqueue({type:"tool-call-delta",toolCallId:y,args:JSON.stringify(g.functionCall.args??{})}),n.enqueue({type:"tool-call-end",toolCallId:y})}}if(a.finishReason){const g=a.finishReason==="STOP"?"stop":a.finishReason==="MAX_TOKENS"?"length":a.finishReason==="TOOL_CALLS"?"tool-calls":"stop",y=h.usageMetadata;n.enqueue({type:"finish",finishReason:g,usage:y?{promptTokens:y.promptTokenCount??0,completionTokens:y.candidatesTokenCount??0,totalTokens:y.totalTokenCount??0}:void 0}),d({finishReason:g,usage:y?{promptTokens:y.promptTokenCount??0,completionTokens:y.candidatesTokenCount??0,totalTokens:y.totalTokenCount??0}:void 0})}}})),response:f}}}}function C(p){const e=[];for(const t of p){if(t.role==="system")continue;if(t.role==="tool"){e.push({role:"function",parts:[{functionResponse:{name:t.toolCallId??"",response:{result:typeof t.content=="string"?JSON.parse(t.content):t.content}}}]});continue}const u=t.role==="assistant"?"model":"user",s=[];if(typeof t.content=="string")t.content&&s.push({text:t.content});else if(Array.isArray(t.content))for(const o of t.content)o.type==="text"&&s.push({text:o.text}),o.type==="image"&&s.push({inlineData:{mimeType:"image/jpeg",data:o.url}});if(t.toolCalls?.length)for(const o of t.toolCalls)s.push({functionCall:{name:o.name,args:typeof o.args=="string"?JSON.parse(o.args):o.args}});s.length>0&&e.push({role:u,parts:s})}return e}function I(p){return{id:"ollama",supportsStreaming:!0,validateConfig(){},async chat(e){const t=(p?.baseURL??"http://localhost:11434")+"/api/chat",u={model:e.model,messages:S(e.messages),stream:!0};e.tools?.length&&(u.tools=e.tools.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.parameters}})));const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:e.signal});if(!s.ok){const i=await s.text();throw new Error(`[vue-llm] Ollama API error ${s.status}: ${i}`)}if(!s.body)throw new Error("[vue-llm] No response body from Ollama");let o;const c=new Promise(i=>{o=i});let d="";return{stream:s.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(i,m){d+=i;const l=d.split(`
|
|
7
|
+
`);d=l.pop()??"";for(const r of l){if(!r.trim())continue;let n;try{n=JSON.parse(r)}catch{continue}if(n.message?.content&&m.enqueue({type:"text-delta",text:n.message.content}),n.message?.tool_calls)for(const h of n.message.tool_calls){const a=`ollama-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;m.enqueue({type:"tool-call-start",toolCallId:a,toolName:h.function.name}),m.enqueue({type:"tool-call-delta",toolCallId:a,args:JSON.stringify(h.function.arguments)}),m.enqueue({type:"tool-call-end",toolCallId:a})}n.done&&(m.enqueue({type:"finish",finishReason:"stop"}),o({finishReason:"stop",usage:n.eval_count?{promptTokens:n.prompt_eval_count??0,completionTokens:n.eval_count,totalTokens:(n.prompt_eval_count??0)+n.eval_count}:void 0}))}}})),response:c}}}}function S(p){return p.map(e=>({role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?t.text:"").join("")}))}exports.createAnthropic=x;exports.createGoogle=b;exports.createOllama=I;exports.createOpenAI=v;
|
package/dist/providers.d.ts
CHANGED
|
@@ -2,5 +2,7 @@ export { createOpenAI } from './providers/openai';
|
|
|
2
2
|
export type { OpenAIConfig } from './providers/openai';
|
|
3
3
|
export { createAnthropic } from './providers/anthropic';
|
|
4
4
|
export type { AnthropicConfig } from './providers/anthropic';
|
|
5
|
+
export { createGoogle } from './providers/google';
|
|
6
|
+
export type { GoogleConfig } from './providers/google';
|
|
5
7
|
export { createOllama } from './providers/ollama';
|
|
6
8
|
export type { OllamaConfig } from './providers/ollama';
|
package/dist/providers.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
class
|
|
1
|
+
class k extends TransformStream {
|
|
2
2
|
constructor() {
|
|
3
3
|
let e = "";
|
|
4
4
|
super({
|
|
5
|
-
transform(t,
|
|
5
|
+
transform(t, u) {
|
|
6
6
|
e += t;
|
|
7
|
-
const
|
|
7
|
+
const s = e.split(`
|
|
8
8
|
`);
|
|
9
|
-
e =
|
|
9
|
+
e = s.pop() ?? "";
|
|
10
10
|
let o = {};
|
|
11
|
-
for (const
|
|
12
|
-
if (
|
|
13
|
-
o.data !== void 0 &&
|
|
11
|
+
for (const c of s) {
|
|
12
|
+
if (c === "") {
|
|
13
|
+
o.data !== void 0 && u.enqueue({
|
|
14
14
|
event: o.event,
|
|
15
15
|
data: o.data,
|
|
16
16
|
id: o.id,
|
|
@@ -18,110 +18,110 @@ class w extends TransformStream {
|
|
|
18
18
|
}), o = {};
|
|
19
19
|
continue;
|
|
20
20
|
}
|
|
21
|
-
if (
|
|
22
|
-
const
|
|
23
|
-
if (
|
|
24
|
-
const
|
|
25
|
-
switch (
|
|
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(/^ /, "");
|
|
25
|
+
switch (f) {
|
|
26
26
|
case "event":
|
|
27
|
-
o.event =
|
|
27
|
+
o.event = i;
|
|
28
28
|
break;
|
|
29
29
|
case "data":
|
|
30
30
|
o.data = o.data !== void 0 ? o.data + `
|
|
31
|
-
` +
|
|
31
|
+
` + i : i;
|
|
32
32
|
break;
|
|
33
33
|
case "id":
|
|
34
|
-
o.id =
|
|
34
|
+
o.id = i;
|
|
35
35
|
break;
|
|
36
36
|
case "retry":
|
|
37
|
-
o.retry = parseInt(
|
|
37
|
+
o.retry = parseInt(i, 10);
|
|
38
38
|
break;
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
},
|
|
42
42
|
flush(t) {
|
|
43
43
|
if (e.trim()) {
|
|
44
|
-
const
|
|
44
|
+
const u = e.split(`
|
|
45
45
|
`);
|
|
46
|
-
let
|
|
47
|
-
for (const o of
|
|
48
|
-
if (o === "" &&
|
|
46
|
+
let s = {};
|
|
47
|
+
for (const o of u) {
|
|
48
|
+
if (o === "" && s.data !== void 0) {
|
|
49
49
|
t.enqueue({
|
|
50
|
-
event:
|
|
51
|
-
data:
|
|
52
|
-
id:
|
|
53
|
-
retry:
|
|
54
|
-
}),
|
|
50
|
+
event: s.event,
|
|
51
|
+
data: s.data,
|
|
52
|
+
id: s.id,
|
|
53
|
+
retry: s.retry
|
|
54
|
+
}), s = {};
|
|
55
55
|
continue;
|
|
56
56
|
}
|
|
57
|
-
const
|
|
58
|
-
if (
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
` +
|
|
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 + `
|
|
61
|
+
` + f : f);
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
65
|
});
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
function
|
|
68
|
+
function b(p) {
|
|
69
69
|
return {
|
|
70
70
|
id: "openai",
|
|
71
71
|
supportsStreaming: !0,
|
|
72
72
|
validateConfig() {
|
|
73
|
-
if (!
|
|
73
|
+
if (!p.apiKey)
|
|
74
74
|
throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');
|
|
75
|
-
if (!
|
|
75
|
+
if (!p.dangerouslyAllowBrowser && typeof window < "u")
|
|
76
76
|
throw new Error(
|
|
77
77
|
"[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
78
|
);
|
|
79
79
|
},
|
|
80
80
|
async chat(e) {
|
|
81
|
-
const t =
|
|
81
|
+
const t = p.baseURL ?? "https://api.openai.com/v1/chat/completions", u = {
|
|
82
82
|
model: e.model,
|
|
83
|
-
messages:
|
|
83
|
+
messages: v(e.messages),
|
|
84
84
|
stream: !0,
|
|
85
85
|
stream_options: { include_usage: !0 }
|
|
86
86
|
};
|
|
87
|
-
e.tools?.length && (
|
|
87
|
+
e.tools?.length && (u.tools = e.tools.map((f) => ({
|
|
88
88
|
type: "function",
|
|
89
89
|
function: {
|
|
90
|
-
name:
|
|
91
|
-
description:
|
|
92
|
-
parameters:
|
|
90
|
+
name: f.name,
|
|
91
|
+
description: f.description,
|
|
92
|
+
parameters: f.parameters
|
|
93
93
|
}
|
|
94
94
|
})));
|
|
95
|
-
const
|
|
95
|
+
const s = await fetch(t, {
|
|
96
96
|
method: "POST",
|
|
97
97
|
headers: {
|
|
98
|
-
Authorization: `Bearer ${
|
|
98
|
+
Authorization: `Bearer ${p.apiKey}`,
|
|
99
99
|
"Content-Type": "application/json"
|
|
100
100
|
},
|
|
101
|
-
body: JSON.stringify(
|
|
101
|
+
body: JSON.stringify(u),
|
|
102
102
|
signal: e.signal
|
|
103
103
|
});
|
|
104
|
-
if (!
|
|
105
|
-
const
|
|
106
|
-
throw new Error(`[vue-llm] OpenAI API error ${
|
|
104
|
+
if (!s.ok) {
|
|
105
|
+
const f = await s.text();
|
|
106
|
+
throw new Error(`[vue-llm] OpenAI API error ${s.status}: ${f}`);
|
|
107
107
|
}
|
|
108
|
-
if (!
|
|
108
|
+
if (!s.body)
|
|
109
109
|
throw new Error("[vue-llm] No response body from OpenAI");
|
|
110
110
|
let o;
|
|
111
|
-
const
|
|
112
|
-
o =
|
|
111
|
+
const c = new Promise((f) => {
|
|
112
|
+
o = f;
|
|
113
113
|
});
|
|
114
|
-
return { stream:
|
|
115
|
-
transform(
|
|
116
|
-
if (
|
|
114
|
+
return { stream: s.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
|
|
115
|
+
transform(f, i) {
|
|
116
|
+
if (f.data === "[DONE]") return;
|
|
117
117
|
let m;
|
|
118
118
|
try {
|
|
119
|
-
m = JSON.parse(
|
|
119
|
+
m = JSON.parse(f.data);
|
|
120
120
|
} catch {
|
|
121
121
|
return;
|
|
122
122
|
}
|
|
123
|
-
const
|
|
124
|
-
if (!
|
|
123
|
+
const l = m.choices?.[0];
|
|
124
|
+
if (!l) {
|
|
125
125
|
m.usage && o({
|
|
126
126
|
finishReason: "stop",
|
|
127
127
|
usage: {
|
|
@@ -132,32 +132,32 @@ function k(c) {
|
|
|
132
132
|
});
|
|
133
133
|
return;
|
|
134
134
|
}
|
|
135
|
-
const
|
|
136
|
-
if (
|
|
137
|
-
for (const
|
|
138
|
-
|
|
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({
|
|
139
139
|
type: "tool-call-start",
|
|
140
|
-
toolCallId:
|
|
141
|
-
toolName:
|
|
142
|
-
}),
|
|
140
|
+
toolCallId: n.id,
|
|
141
|
+
toolName: n.function?.name ?? ""
|
|
142
|
+
}), n.function?.arguments && i.enqueue({
|
|
143
143
|
type: "tool-call-delta",
|
|
144
|
-
toolCallId:
|
|
145
|
-
args:
|
|
144
|
+
toolCallId: n.id ?? "",
|
|
145
|
+
args: n.function.arguments
|
|
146
146
|
});
|
|
147
|
-
if (
|
|
148
|
-
const
|
|
149
|
-
for (const a of
|
|
150
|
-
a.id &&
|
|
151
|
-
const
|
|
152
|
-
|
|
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 });
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
|
-
})), response:
|
|
155
|
+
})), response: c };
|
|
156
156
|
}
|
|
157
157
|
};
|
|
158
158
|
}
|
|
159
|
-
function
|
|
160
|
-
return
|
|
159
|
+
function v(p) {
|
|
160
|
+
return p.map((e) => e.role === "tool" ? {
|
|
161
161
|
role: "tool",
|
|
162
162
|
content: typeof e.content == "string" ? e.content : JSON.stringify(e.content),
|
|
163
163
|
tool_call_id: e.toolCallId
|
|
@@ -177,94 +177,94 @@ function _(c) {
|
|
|
177
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
178
|
});
|
|
179
179
|
}
|
|
180
|
-
function
|
|
180
|
+
function C(p) {
|
|
181
181
|
return {
|
|
182
182
|
id: "anthropic",
|
|
183
183
|
supportsStreaming: !0,
|
|
184
184
|
validateConfig() {
|
|
185
|
-
if (!
|
|
185
|
+
if (!p.apiKey)
|
|
186
186
|
throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');
|
|
187
|
-
if (!
|
|
187
|
+
if (!p.dangerouslyAllowBrowser && typeof window < "u")
|
|
188
188
|
throw new Error(
|
|
189
189
|
"[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
190
|
);
|
|
191
191
|
},
|
|
192
192
|
async chat(e) {
|
|
193
|
-
const t = (
|
|
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 = {
|
|
194
194
|
model: e.model,
|
|
195
|
-
messages:
|
|
195
|
+
messages: x(s),
|
|
196
196
|
max_tokens: e.providerOptions?.maxTokens ?? 4096,
|
|
197
197
|
stream: !0
|
|
198
198
|
};
|
|
199
|
-
|
|
200
|
-
name:
|
|
201
|
-
description:
|
|
202
|
-
input_schema:
|
|
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
|
|
203
203
|
})));
|
|
204
|
-
const
|
|
204
|
+
const c = await fetch(t, {
|
|
205
205
|
method: "POST",
|
|
206
206
|
headers: {
|
|
207
|
-
"x-api-key":
|
|
207
|
+
"x-api-key": p.apiKey,
|
|
208
208
|
"anthropic-version": "2023-06-01",
|
|
209
209
|
"Content-Type": "application/json"
|
|
210
210
|
},
|
|
211
211
|
body: JSON.stringify(o),
|
|
212
212
|
signal: e.signal
|
|
213
213
|
});
|
|
214
|
-
if (!
|
|
215
|
-
const
|
|
216
|
-
throw new Error(`[vue-llm] Anthropic API error ${
|
|
214
|
+
if (!c.ok) {
|
|
215
|
+
const l = await c.text();
|
|
216
|
+
throw new Error(`[vue-llm] Anthropic API error ${c.status}: ${l}`);
|
|
217
217
|
}
|
|
218
|
-
if (!
|
|
218
|
+
if (!c.body)
|
|
219
219
|
throw new Error("[vue-llm] No response body from Anthropic");
|
|
220
|
-
let
|
|
221
|
-
const
|
|
222
|
-
|
|
220
|
+
let d;
|
|
221
|
+
const f = new Promise((l) => {
|
|
222
|
+
d = l;
|
|
223
223
|
});
|
|
224
|
-
let
|
|
225
|
-
return { stream:
|
|
226
|
-
transform(
|
|
227
|
-
let
|
|
224
|
+
let i = "";
|
|
225
|
+
return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
|
|
226
|
+
transform(l, r) {
|
|
227
|
+
let n;
|
|
228
228
|
try {
|
|
229
|
-
|
|
229
|
+
n = JSON.parse(l.data);
|
|
230
230
|
} catch {
|
|
231
231
|
return;
|
|
232
232
|
}
|
|
233
|
-
switch (
|
|
233
|
+
switch (l.event ?? n.type) {
|
|
234
234
|
case "content_block_start": {
|
|
235
|
-
const a =
|
|
236
|
-
a?.type === "tool_use" && (
|
|
235
|
+
const a = n.content_block;
|
|
236
|
+
a?.type === "tool_use" && (i = a.id, r.enqueue({
|
|
237
237
|
type: "tool-call-start",
|
|
238
|
-
toolCallId:
|
|
238
|
+
toolCallId: i,
|
|
239
239
|
toolName: a.name
|
|
240
240
|
}));
|
|
241
241
|
break;
|
|
242
242
|
}
|
|
243
243
|
case "content_block_delta": {
|
|
244
|
-
const a =
|
|
245
|
-
a?.type === "text_delta" && a.text &&
|
|
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({
|
|
246
246
|
type: "tool-call-delta",
|
|
247
|
-
toolCallId:
|
|
247
|
+
toolCallId: i,
|
|
248
248
|
args: a.partial_json
|
|
249
249
|
});
|
|
250
250
|
break;
|
|
251
251
|
}
|
|
252
252
|
case "content_block_stop": {
|
|
253
|
-
|
|
253
|
+
i && (r.enqueue({ type: "tool-call-end", toolCallId: i }), i = "");
|
|
254
254
|
break;
|
|
255
255
|
}
|
|
256
256
|
case "message_delta": {
|
|
257
|
-
const a =
|
|
258
|
-
|
|
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({
|
|
259
259
|
type: "finish",
|
|
260
260
|
finishReason: g,
|
|
261
|
-
usage:
|
|
262
|
-
}),
|
|
261
|
+
usage: w ? { promptTokens: 0, completionTokens: w.output_tokens ?? 0, totalTokens: w.output_tokens ?? 0 } : void 0
|
|
262
|
+
}), d({ finishReason: g, usage: void 0 });
|
|
263
263
|
break;
|
|
264
264
|
}
|
|
265
265
|
case "error": {
|
|
266
|
-
const a =
|
|
267
|
-
|
|
266
|
+
const a = n.error;
|
|
267
|
+
r.enqueue({
|
|
268
268
|
type: "error",
|
|
269
269
|
error: new Error(`[vue-llm] Anthropic stream error: ${a?.message ?? "unknown"}`)
|
|
270
270
|
});
|
|
@@ -272,12 +272,12 @@ function b(c) {
|
|
|
272
272
|
}
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
|
-
})), response:
|
|
275
|
+
})), response: f };
|
|
276
276
|
}
|
|
277
277
|
};
|
|
278
278
|
}
|
|
279
|
-
function
|
|
280
|
-
return
|
|
279
|
+
function x(p) {
|
|
280
|
+
return p.map((e) => {
|
|
281
281
|
if (e.role === "tool")
|
|
282
282
|
return {
|
|
283
283
|
role: "user",
|
|
@@ -290,12 +290,12 @@ function v(c) {
|
|
|
290
290
|
if (e.role === "assistant" && e.toolCalls?.length) {
|
|
291
291
|
const t = [];
|
|
292
292
|
typeof e.content == "string" && e.content && t.push({ type: "text", text: e.content });
|
|
293
|
-
for (const
|
|
293
|
+
for (const u of e.toolCalls)
|
|
294
294
|
t.push({
|
|
295
295
|
type: "tool_use",
|
|
296
|
-
id:
|
|
297
|
-
name:
|
|
298
|
-
input:
|
|
296
|
+
id: u.id,
|
|
297
|
+
name: u.name,
|
|
298
|
+
input: u.args
|
|
299
299
|
});
|
|
300
300
|
return { role: "assistant", content: t };
|
|
301
301
|
}
|
|
@@ -308,92 +308,235 @@ function v(c) {
|
|
|
308
308
|
};
|
|
309
309
|
});
|
|
310
310
|
}
|
|
311
|
-
function
|
|
311
|
+
function I(p) {
|
|
312
|
+
return {
|
|
313
|
+
id: "google",
|
|
314
|
+
supportsStreaming: !0,
|
|
315
|
+
validateConfig() {
|
|
316
|
+
if (!p.apiKey)
|
|
317
|
+
throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');
|
|
318
|
+
if (!p.dangerouslyAllowBrowser && typeof window < "u")
|
|
319
|
+
throw new Error(
|
|
320
|
+
"[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
|
+
);
|
|
322
|
+
},
|
|
323
|
+
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
|
|
334
|
+
}))
|
|
335
|
+
}]), s.generationConfig = {
|
|
336
|
+
...e.providerOptions?.response_format?.type === "json_object" ? { responseMimeType: "application/json" } : {}
|
|
337
|
+
};
|
|
338
|
+
const c = await fetch(u, {
|
|
339
|
+
method: "POST",
|
|
340
|
+
headers: { "Content-Type": "application/json" },
|
|
341
|
+
body: JSON.stringify(s),
|
|
342
|
+
signal: e.signal
|
|
343
|
+
});
|
|
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)
|
|
349
|
+
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({
|
|
356
|
+
buffer: "",
|
|
357
|
+
transform(r, n) {
|
|
358
|
+
this.buffer += r;
|
|
359
|
+
const h = this.buffer.split(`
|
|
360
|
+
`);
|
|
361
|
+
this.buffer = h.pop();
|
|
362
|
+
for (const a of h)
|
|
363
|
+
a.startsWith("data: ") && n.enqueue(a.slice(6));
|
|
364
|
+
},
|
|
365
|
+
flush(r) {
|
|
366
|
+
const n = this.buffer.trim();
|
|
367
|
+
n.startsWith("data: ") && r.enqueue(n.slice(6));
|
|
368
|
+
}
|
|
369
|
+
})).pipeThrough(new TransformStream({
|
|
370
|
+
transform(r, n) {
|
|
371
|
+
let h;
|
|
372
|
+
try {
|
|
373
|
+
h = JSON.parse(r);
|
|
374
|
+
} catch {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const a = h.candidates?.[0];
|
|
378
|
+
if (!a) return;
|
|
379
|
+
const w = a.content?.parts;
|
|
380
|
+
if (w) {
|
|
381
|
+
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({
|
|
385
|
+
type: "tool-call-start",
|
|
386
|
+
toolCallId: y,
|
|
387
|
+
toolName: g.functionCall.name
|
|
388
|
+
}), n.enqueue({
|
|
389
|
+
type: "tool-call-delta",
|
|
390
|
+
toolCallId: y,
|
|
391
|
+
args: JSON.stringify(g.functionCall.args ?? {})
|
|
392
|
+
}), n.enqueue({ type: "tool-call-end", toolCallId: y });
|
|
393
|
+
}
|
|
394
|
+
}
|
|
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({
|
|
398
|
+
type: "finish",
|
|
399
|
+
finishReason: g,
|
|
400
|
+
usage: y ? {
|
|
401
|
+
promptTokens: y.promptTokenCount ?? 0,
|
|
402
|
+
completionTokens: y.candidatesTokenCount ?? 0,
|
|
403
|
+
totalTokens: y.totalTokenCount ?? 0
|
|
404
|
+
} : void 0
|
|
405
|
+
}), d({
|
|
406
|
+
finishReason: g,
|
|
407
|
+
usage: y ? {
|
|
408
|
+
promptTokens: y.promptTokenCount ?? 0,
|
|
409
|
+
completionTokens: y.candidatesTokenCount ?? 0,
|
|
410
|
+
totalTokens: y.totalTokenCount ?? 0
|
|
411
|
+
} : void 0
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
})), response: f };
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
}
|
|
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
|
+
});
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
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({
|
|
444
|
+
functionCall: {
|
|
445
|
+
name: o.name,
|
|
446
|
+
args: typeof o.args == "string" ? JSON.parse(o.args) : o.args
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
s.length > 0 && e.push({ role: u, parts: s });
|
|
450
|
+
}
|
|
451
|
+
return e;
|
|
452
|
+
}
|
|
453
|
+
function S(p) {
|
|
312
454
|
return {
|
|
313
455
|
id: "ollama",
|
|
314
456
|
supportsStreaming: !0,
|
|
315
457
|
validateConfig() {
|
|
316
458
|
},
|
|
317
459
|
async chat(e) {
|
|
318
|
-
const t = (
|
|
460
|
+
const t = (p?.baseURL ?? "http://localhost:11434") + "/api/chat", u = {
|
|
319
461
|
model: e.model,
|
|
320
|
-
messages:
|
|
462
|
+
messages: _(e.messages),
|
|
321
463
|
stream: !0
|
|
322
464
|
};
|
|
323
|
-
e.tools?.length && (
|
|
465
|
+
e.tools?.length && (u.tools = e.tools.map((i) => ({
|
|
324
466
|
type: "function",
|
|
325
467
|
function: {
|
|
326
|
-
name:
|
|
327
|
-
description:
|
|
328
|
-
parameters:
|
|
468
|
+
name: i.name,
|
|
469
|
+
description: i.description,
|
|
470
|
+
parameters: i.parameters
|
|
329
471
|
}
|
|
330
472
|
})));
|
|
331
|
-
const
|
|
473
|
+
const s = await fetch(t, {
|
|
332
474
|
method: "POST",
|
|
333
475
|
headers: { "Content-Type": "application/json" },
|
|
334
|
-
body: JSON.stringify(
|
|
476
|
+
body: JSON.stringify(u),
|
|
335
477
|
signal: e.signal
|
|
336
478
|
});
|
|
337
|
-
if (!
|
|
338
|
-
const
|
|
339
|
-
throw new Error(`[vue-llm] Ollama API error ${
|
|
479
|
+
if (!s.ok) {
|
|
480
|
+
const i = await s.text();
|
|
481
|
+
throw new Error(`[vue-llm] Ollama API error ${s.status}: ${i}`);
|
|
340
482
|
}
|
|
341
|
-
if (!
|
|
483
|
+
if (!s.body)
|
|
342
484
|
throw new Error("[vue-llm] No response body from Ollama");
|
|
343
485
|
let o;
|
|
344
|
-
const
|
|
345
|
-
o =
|
|
486
|
+
const c = new Promise((i) => {
|
|
487
|
+
o = i;
|
|
346
488
|
});
|
|
347
|
-
let
|
|
348
|
-
return { stream:
|
|
349
|
-
transform(
|
|
350
|
-
|
|
351
|
-
const
|
|
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(`
|
|
352
494
|
`);
|
|
353
|
-
|
|
354
|
-
for (const
|
|
355
|
-
if (!
|
|
356
|
-
let
|
|
495
|
+
d = l.pop() ?? "";
|
|
496
|
+
for (const r of l) {
|
|
497
|
+
if (!r.trim()) continue;
|
|
498
|
+
let n;
|
|
357
499
|
try {
|
|
358
|
-
|
|
500
|
+
n = JSON.parse(r);
|
|
359
501
|
} catch {
|
|
360
502
|
continue;
|
|
361
503
|
}
|
|
362
|
-
if (
|
|
363
|
-
for (const
|
|
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) {
|
|
364
506
|
const a = `ollama-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
365
507
|
m.enqueue({
|
|
366
508
|
type: "tool-call-start",
|
|
367
509
|
toolCallId: a,
|
|
368
|
-
toolName:
|
|
510
|
+
toolName: h.function.name
|
|
369
511
|
}), m.enqueue({
|
|
370
512
|
type: "tool-call-delta",
|
|
371
513
|
toolCallId: a,
|
|
372
|
-
args: JSON.stringify(
|
|
514
|
+
args: JSON.stringify(h.function.arguments)
|
|
373
515
|
}), m.enqueue({ type: "tool-call-end", toolCallId: a });
|
|
374
516
|
}
|
|
375
|
-
|
|
517
|
+
n.done && (m.enqueue({ type: "finish", finishReason: "stop" }), o({
|
|
376
518
|
finishReason: "stop",
|
|
377
|
-
usage:
|
|
378
|
-
promptTokens:
|
|
379
|
-
completionTokens:
|
|
380
|
-
totalTokens: (
|
|
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
|
|
381
523
|
} : void 0
|
|
382
524
|
}));
|
|
383
525
|
}
|
|
384
526
|
}
|
|
385
|
-
})), response:
|
|
527
|
+
})), response: c };
|
|
386
528
|
}
|
|
387
529
|
};
|
|
388
530
|
}
|
|
389
|
-
function
|
|
390
|
-
return
|
|
531
|
+
function _(p) {
|
|
532
|
+
return p.map((e) => ({
|
|
391
533
|
role: e.role,
|
|
392
534
|
content: typeof e.content == "string" ? e.content : e.content.map((t) => t.type === "text" ? t.text : "").join("")
|
|
393
535
|
}));
|
|
394
536
|
}
|
|
395
537
|
export {
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
538
|
+
C as createAnthropic,
|
|
539
|
+
I as createGoogle,
|
|
540
|
+
S as createOllama,
|
|
541
|
+
b as createOpenAI
|
|
399
542
|
};
|