vue-llm 0.3.0 → 0.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/index.cjs +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +308 -228
- package/dist/middleware.d.ts +11 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("vue");class I{constructor(r,e,t){this.messages=r,this.status=e,this.generateId=t}messages;status;generateId;async processStream(r,e,t){this.status.value="streaming";const s=this.getOrCreateAssistantMessage(),i=new Map,o=[];let n="stop",b;const m=r.getReader();try{for(;!e.aborted;){const{done:p,value:g}=await m.read();if(p)break;if(this.applyChunk(s,g,i),g.type==="tool-call-end"){const S=i.get(g.toolCallId)??"{}";let C;try{C=JSON.parse(S)}catch{C=S}const y={toolCallId:g.toolCallId,toolName:this.getToolName(s,g.toolCallId),args:C};if(o.push(y),t.onToolCall){const f=this.findToolCallPart(s,g.toolCallId);f&&(f.state="running",f.args=C),this.triggerReactivity();try{const w=await t.onToolCall(y);w!==void 0&&f&&(f.state="result",f.result=w,this.triggerReactivity())}catch(w){f&&(f.state="error",f.error=w instanceof Error?w.message:String(w),this.triggerReactivity())}}}if(g.type==="finish"&&(n=g.finishReason,b=g.usage),g.type==="error")throw g.error;this.triggerReactivity()}}catch(p){if(!e.aborted){const g=p instanceof Error?p:new Error(String(p));throw t.onError?.(g),g}}finally{m.releaseLock()}return this.finalizeTextParts(s),this.triggerReactivity(),t.onFinish?.(s,{finishReason:n,usage:b}),{finishReason:n,usage:b,toolCalls:o}}getOrCreateAssistantMessage(){const r=this.messages.value,e=r[r.length-1];if(e?.role==="assistant")return e;const t={id:this.generateId(),role:"assistant",parts:[],createdAt:new Date};return r.push(t),t}applyChunk(r,e,t){switch(e.type){case"text-delta":{const s=r.parts[r.parts.length-1];s?.type==="text"&&s.state==="streaming"?s.text+=e.text:r.parts.push({type:"text",text:e.text,state:"streaming"});break}case"reasoning-delta":{const s=r.parts[r.parts.length-1];s?.type==="reasoning"&&s.state==="streaming"?s.text+=e.text:r.parts.push({type:"reasoning",text:e.text,state:"streaming"});break}case"tool-call-start":r.parts.push({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,args:void 0,state:"pending"}),t.set(e.toolCallId,"");break;case"tool-call-delta":t.set(e.toolCallId,(t.get(e.toolCallId)??"")+e.args);break}}finalizeTextParts(r){for(const e of r.parts)(e.type==="text"||e.type==="reasoning")&&e.state==="streaming"&&(e.state="done")}findToolCallPart(r,e){return r.parts.find(t=>t.type==="tool-call"&&t.toolCallId===e)}getToolName(r,e){return this.findToolCallPart(r,e)?.toolName??""}triggerReactivity(){this.messages.value=[...this.messages.value]}}const O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function R(a=16){const r=crypto.getRandomValues(new Uint8Array(a));let e="";for(let t=0;t<a;t++)e+=O[r[t]%O.length];return e}function T(a){const r=a.id??R(),e=d.ref(a.initialMessages??[]),t=d.ref("ready"),s=d.ref(void 0),i=d.ref("");let o=null;const n=new I(e,t,R),b=()=>{const l=[];a.system&&l.push({role:"system",content:a.system});for(const v of e.value){if(v.role==="system")continue;const c=v.parts.filter(h=>h.type==="text").map(h=>h.text).join(""),E=v.parts.filter(h=>h.type==="tool-call").map(h=>({id:h.toolCallId,name:h.toolName,args:h.args}));if(v.role==="user")l.push({role:"user",content:c});else if(v.role==="assistant"){l.push({role:"assistant",content:c,toolCalls:E.length>0?E:void 0});for(const h of v.parts)h.type!=="tool-call"||h.state!=="result"||l.push({role:"tool",content:JSON.stringify(h.result),toolCallId:h.toolCallId})}}return l},m=async l=>{const v=a.maxToolRoundtrips??5;let u=0;for(;u<v;){const c=b();a.provider.validateConfig();const{stream:E}=await a.provider.chat({model:a.model,messages:c,tools:a.tools,signal:l,providerOptions:{...a.providerOptions,...d.toValue(a.body)}}),h=await n.processStream(E,l,{onFinish:a.onFinish,onError:a.onError,onToolCall:a.onToolCall});if(h.finishReason!=="tool-calls"||h.toolCalls.length===0)break;u++}},p=async l=>{const v=typeof l=="string"?l:l?.text??i.value;if(!v.trim())return;(typeof l!="object"||l===null||!("text"in l))&&(i.value="");const u={id:R(),role:"user",parts:[{type:"text",text:v,state:"done"}],createdAt:new Date};e.value=[...e.value,u],s.value=void 0,t.value="submitted",o?.abort(),o=new AbortController;try{await m(o.signal),t.value="ready"}catch(c){if(o.signal.aborted){t.value="ready";return}s.value=c instanceof Error?c:new Error(String(c)),t.value="error"}},g=async()=>{const l=e.value,v=l.reduce((u,c,E)=>c.role==="assistant"?E:u,-1);if(v!==-1){e.value=l.slice(0,v),s.value=void 0,t.value="submitted",o?.abort(),o=new AbortController;try{await m(o.signal),t.value="ready"}catch(u){if(o.signal.aborted){t.value="ready";return}s.value=u instanceof Error?u:new Error(String(u)),t.value="error"}}},S=()=>{o?.abort(),o=null,t.value="ready"},C=l=>{e.value=typeof l=="function"?l(e.value):l},y=l=>{l?.preventDefault?.(),i.value.trim()&&p()},f=d.computed(()=>t.value==="submitted"||t.value==="streaming"),w=({toolCallId:l,result:v})=>{for(const u of e.value)for(const c of u.parts)if(c.type==="tool-call"&&c.toolCallId===l){c.state="result",c.result=v,e.value=[...e.value];return}},x=()=>{s.value=void 0,t.value==="error"&&(t.value="ready")};return d.onScopeDispose(()=>{o?.abort()}),{messages:e,status:d.computed(()=>t.value),error:s,id:r,input:i,sendMessage:p,regenerate:g,stop:S,setMessages:C,handleSubmit:y,isLoading:f,addToolResult:w,clearError:x}}function M(a){const r=a.id??R(),e=d.ref(""),t=d.ref("ready"),s=d.ref(void 0),i=d.ref("");let o=null;const n=async S=>{const C=S??i.value;if(!C.trim())return e.value;S||(i.value=""),e.value="",s.value=void 0,t.value="submitted",o?.abort(),o=new AbortController;try{a.provider.validateConfig();const y=a.system?[{role:"system",content:a.system},{role:"user",content:C}]:[{role:"user",content:C}],{stream:f}=await a.provider.chat({model:a.model,messages:y,signal:o.signal});t.value="streaming";const w=f.getReader();let x="stop",l;for(;!o.signal.aborted;){const{done:v,value:u}=await w.read();if(v)break;if(u.type==="text-delta")e.value+=u.text;else if(u.type==="finish")x=u.finishReason,l=u.usage;else if(u.type==="error")throw u.error}return w.releaseLock(),t.value="ready",a.onFinish?.(e.value,{finishReason:x,usage:l}),e.value}catch(y){if(!o||o.signal.aborted)return t.value="ready",e.value;const f=y instanceof Error?y:new Error(String(y));return s.value=f,t.value="error",a.onError?.(f),e.value}},b=()=>{o?.abort(),o=null,t.value="ready"},m=()=>{s.value=void 0,t.value==="error"&&(t.value="ready")},p=S=>{S?.preventDefault?.(),i.value.trim()&&n()},g=d.computed(()=>t.value==="submitted"||t.value==="streaming");return d.onScopeDispose(()=>{o?.abort()}),{completion:e,status:d.computed(()=>t.value),error:s,isLoading:g,id:r,input:i,complete:n,stop:b,clearError:m,handleSubmit:p}}function P(a){const r=a.id??R(),e=d.ref(void 0),t=d.ref(void 0),s=d.ref("ready"),i=d.ref(void 0),o=d.ref("");let n=null;const b=async S=>{const C=S??o.value;if(!C.trim())return e.value;S||(o.value=""),e.value=void 0,t.value=void 0,i.value=void 0,s.value="submitted",n?.abort(),n=new AbortController;try{a.provider.validateConfig();const y=[a.system??"","Respond with valid JSON matching this schema:",JSON.stringify(a.schema,null,2),"Output ONLY the JSON object, no other text."].filter(Boolean).join(`
|
|
2
2
|
|
|
3
|
-
`),{stream:
|
|
3
|
+
`),{stream:f}=await a.provider.chat({model:a.model,messages:[{role:"system",content:y},{role:"user",content:C}],signal:n.signal,providerOptions:{response_format:{type:"json_object"}}});s.value="streaming";const w=f.getReader();let x="",l="stop",v;for(;!n.signal.aborted;){const{done:u,value:c}=await w.read();if(u)break;if(c.type==="text-delta"){x+=c.text;try{t.value=N(x)}catch{}}else if(c.type==="finish")l=c.finishReason,v=c.usage;else if(c.type==="error")throw c.error}w.releaseLock();try{e.value=JSON.parse(x),t.value=e.value}catch{throw new Error(`Failed to parse JSON response: ${x.slice(0,200)}`)}return s.value="ready",a.onFinish?.(e.value,{finishReason:l,usage:v}),e.value}catch(y){if(n.signal.aborted)return s.value="ready",e.value;const f=y instanceof Error?y:new Error(String(y));i.value=f,s.value="error",a.onError?.(f);return}},m=()=>{n?.abort(),n=null,s.value="ready"},p=()=>{i.value=void 0,s.value==="error"&&(s.value="ready")},g=d.computed(()=>s.value==="submitted"||s.value==="streaming");return d.onScopeDispose(()=>{n?.abort()}),{object:e,partialObject:t,status:d.computed(()=>s.value),error:i,isLoading:g,id:r,input:o,submit:b,stop:m,clearError:p}}function N(a){let r=a.trim();if(!r.startsWith("{"))return;let e=0,t=!1,s=!1;for(let i=0;i<r.length;i++){const o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){t=!t;continue}t||(o==="{"&&e++,o==="}"&&e--)}for(;e>0;)r+="}",e--;try{return JSON.parse(r)}catch{return}}function A(a,r){return r.length?{id:a.id,supportsStreaming:a.supportsStreaming,validateConfig(){a.validateConfig()},async chat(e){let t=e;for(const n of r)n.beforeRequest&&(t=await n.beforeRequest(t,a));let s;try{s=await a.chat(t)}catch(n){let b=n instanceof Error?n:new Error(String(n));for(const m of r)if(m.onError){const p=await m.onError(b,t);p instanceof Error&&(b=p)}throw b}const o=r.some(n=>n.afterStream)?s.stream.pipeThrough(new TransformStream({async transform(n,b){let m=n;for(const p of r){if(!m)break;p.afterStream&&(m=await p.afterStream(m,t))}m&&b.enqueue(m)}})):s.stream;for(const n of r)n.onFinish&&n.onFinish(t,s);return{stream:o,response:s.response}}}:a}function j(a="vue-llm"){return{beforeRequest(r){return console.log(`[${a}] → ${r.model}`,r.messages.length,"messages"),r},afterStream(r){return r.type==="finish"&&console.log(`[${a}] ← finish:`,r.finishReason,r.usage??""),r},onError(r){console.error(`[${a}] error:`,r.message)}}}function J(a=3,r=1e3){return{async onError(e,t){const s=e.message;if(!(s.includes("429")||s.includes("500")||s.includes("502")||s.includes("503")))return e;for(let o=0;o<a;o++)await new Promise(n=>setTimeout(n,r*(o+1))),console.log(`[vue-llm] retry ${o+1}/${a}`);return e}}}function F(a){return{beforeRequest(r){return{...r,providerOptions:{...r.providerOptions,headers:{...r.providerOptions?.headers,...a}}}}}}exports.headerMiddleware=F;exports.loggingMiddleware=j;exports.retryMiddleware=J;exports.useChat=T;exports.useCompletion=M;exports.useObject=P;exports.wrapProvider=A;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,5 +4,7 @@ export { useCompletion } from './composables/use-completion';
|
|
|
4
4
|
export type { UseCompletionOptions, UseCompletionReturn } from './composables/use-completion';
|
|
5
5
|
export { useObject } from './composables/use-object';
|
|
6
6
|
export type { UseObjectOptions, UseObjectReturn } from './composables/use-object';
|
|
7
|
+
export { wrapProvider, loggingMiddleware, retryMiddleware, headerMiddleware } from './middleware';
|
|
8
|
+
export type { Middleware } from './middleware';
|
|
7
9
|
export type { UIMessage, UIMessagePart, TextPart, ReasoningPart, ToolCallPart, FilePart, SourcePart, ToolDefinition, ChatStatus, FinishReason, Usage, } from './types';
|
|
8
10
|
export type { LLMProvider, ChatRequest, ChatMessage, ChatStreamResult, ChatStreamChunk, ChatResponse, } from './providers/types';
|
package/dist/index.js
CHANGED
|
@@ -1,302 +1,302 @@
|
|
|
1
|
-
import { ref as
|
|
1
|
+
import { ref as C, computed as R, onScopeDispose as I, toValue as N } from "vue";
|
|
2
2
|
class P {
|
|
3
|
-
constructor(
|
|
4
|
-
this.messages =
|
|
3
|
+
constructor(r, e, t) {
|
|
4
|
+
this.messages = r, this.status = e, this.generateId = t;
|
|
5
5
|
}
|
|
6
6
|
messages;
|
|
7
7
|
status;
|
|
8
8
|
generateId;
|
|
9
|
-
async processStream(
|
|
9
|
+
async processStream(r, e, t) {
|
|
10
10
|
this.status.value = "streaming";
|
|
11
|
-
const
|
|
12
|
-
let
|
|
13
|
-
const
|
|
11
|
+
const s = this.getOrCreateAssistantMessage(), i = /* @__PURE__ */ new Map(), o = [];
|
|
12
|
+
let n = "stop", p;
|
|
13
|
+
const g = r.getReader();
|
|
14
14
|
try {
|
|
15
|
-
for (; !
|
|
16
|
-
const { done:
|
|
17
|
-
if (
|
|
18
|
-
if (this.applyChunk(
|
|
19
|
-
const
|
|
20
|
-
let
|
|
15
|
+
for (; !e.aborted; ) {
|
|
16
|
+
const { done: m, value: v } = await g.read();
|
|
17
|
+
if (m) break;
|
|
18
|
+
if (this.applyChunk(s, v, i), v.type === "tool-call-end") {
|
|
19
|
+
const S = i.get(v.toolCallId) ?? "{}";
|
|
20
|
+
let w;
|
|
21
21
|
try {
|
|
22
|
-
|
|
22
|
+
w = JSON.parse(S);
|
|
23
23
|
} catch {
|
|
24
|
-
|
|
24
|
+
w = S;
|
|
25
25
|
}
|
|
26
|
-
const y = { toolCallId: v.toolCallId, toolName: this.getToolName(
|
|
27
|
-
if (o.push(y),
|
|
28
|
-
const
|
|
29
|
-
|
|
26
|
+
const y = { toolCallId: v.toolCallId, toolName: this.getToolName(s, v.toolCallId), args: w };
|
|
27
|
+
if (o.push(y), t.onToolCall) {
|
|
28
|
+
const d = this.findToolCallPart(s, v.toolCallId);
|
|
29
|
+
d && (d.state = "running", d.args = w), this.triggerReactivity();
|
|
30
30
|
try {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
} catch (
|
|
34
|
-
|
|
31
|
+
const b = await t.onToolCall(y);
|
|
32
|
+
b !== void 0 && d && (d.state = "result", d.result = b, this.triggerReactivity());
|
|
33
|
+
} catch (b) {
|
|
34
|
+
d && (d.state = "error", d.error = b instanceof Error ? b.message : String(b), this.triggerReactivity());
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
if (v.type === "finish" && (
|
|
38
|
+
if (v.type === "finish" && (n = v.finishReason, p = v.usage), v.type === "error")
|
|
39
39
|
throw v.error;
|
|
40
40
|
this.triggerReactivity();
|
|
41
41
|
}
|
|
42
|
-
} catch (
|
|
43
|
-
if (!
|
|
44
|
-
const v =
|
|
45
|
-
throw
|
|
42
|
+
} catch (m) {
|
|
43
|
+
if (!e.aborted) {
|
|
44
|
+
const v = m instanceof Error ? m : new Error(String(m));
|
|
45
|
+
throw t.onError?.(v), v;
|
|
46
46
|
}
|
|
47
47
|
} finally {
|
|
48
|
-
|
|
48
|
+
g.releaseLock();
|
|
49
49
|
}
|
|
50
|
-
return this.finalizeTextParts(
|
|
50
|
+
return this.finalizeTextParts(s), this.triggerReactivity(), t.onFinish?.(s, { finishReason: n, usage: p }), { finishReason: n, usage: p, toolCalls: o };
|
|
51
51
|
}
|
|
52
52
|
getOrCreateAssistantMessage() {
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
55
|
-
const
|
|
53
|
+
const r = this.messages.value, e = r[r.length - 1];
|
|
54
|
+
if (e?.role === "assistant") return e;
|
|
55
|
+
const t = {
|
|
56
56
|
id: this.generateId(),
|
|
57
57
|
role: "assistant",
|
|
58
58
|
parts: [],
|
|
59
59
|
createdAt: /* @__PURE__ */ new Date()
|
|
60
60
|
};
|
|
61
|
-
return
|
|
61
|
+
return r.push(t), t;
|
|
62
62
|
}
|
|
63
|
-
applyChunk(
|
|
64
|
-
switch (
|
|
63
|
+
applyChunk(r, e, t) {
|
|
64
|
+
switch (e.type) {
|
|
65
65
|
case "text-delta": {
|
|
66
|
-
const
|
|
67
|
-
|
|
66
|
+
const s = r.parts[r.parts.length - 1];
|
|
67
|
+
s?.type === "text" && s.state === "streaming" ? s.text += e.text : r.parts.push({ type: "text", text: e.text, state: "streaming" });
|
|
68
68
|
break;
|
|
69
69
|
}
|
|
70
70
|
case "reasoning-delta": {
|
|
71
|
-
const
|
|
72
|
-
|
|
71
|
+
const s = r.parts[r.parts.length - 1];
|
|
72
|
+
s?.type === "reasoning" && s.state === "streaming" ? s.text += e.text : r.parts.push({ type: "reasoning", text: e.text, state: "streaming" });
|
|
73
73
|
break;
|
|
74
74
|
}
|
|
75
75
|
case "tool-call-start":
|
|
76
|
-
|
|
76
|
+
r.parts.push({
|
|
77
77
|
type: "tool-call",
|
|
78
|
-
toolCallId:
|
|
79
|
-
toolName:
|
|
78
|
+
toolCallId: e.toolCallId,
|
|
79
|
+
toolName: e.toolName,
|
|
80
80
|
args: void 0,
|
|
81
81
|
state: "pending"
|
|
82
|
-
}),
|
|
82
|
+
}), t.set(e.toolCallId, "");
|
|
83
83
|
break;
|
|
84
84
|
case "tool-call-delta":
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
(
|
|
85
|
+
t.set(
|
|
86
|
+
e.toolCallId,
|
|
87
|
+
(t.get(e.toolCallId) ?? "") + e.args
|
|
88
88
|
);
|
|
89
89
|
break;
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
|
-
finalizeTextParts(
|
|
93
|
-
for (const
|
|
94
|
-
(
|
|
92
|
+
finalizeTextParts(r) {
|
|
93
|
+
for (const e of r.parts)
|
|
94
|
+
(e.type === "text" || e.type === "reasoning") && e.state === "streaming" && (e.state = "done");
|
|
95
95
|
}
|
|
96
|
-
findToolCallPart(
|
|
97
|
-
return
|
|
98
|
-
(
|
|
96
|
+
findToolCallPart(r, e) {
|
|
97
|
+
return r.parts.find(
|
|
98
|
+
(t) => t.type === "tool-call" && t.toolCallId === e
|
|
99
99
|
);
|
|
100
100
|
}
|
|
101
|
-
getToolName(
|
|
102
|
-
return this.findToolCallPart(
|
|
101
|
+
getToolName(r, e) {
|
|
102
|
+
return this.findToolCallPart(r, e)?.toolName ?? "";
|
|
103
103
|
}
|
|
104
104
|
triggerReactivity() {
|
|
105
105
|
this.messages.value = [...this.messages.value];
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
|
-
const
|
|
109
|
-
function
|
|
110
|
-
const
|
|
111
|
-
let
|
|
112
|
-
for (let
|
|
113
|
-
|
|
114
|
-
return
|
|
108
|
+
const T = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
109
|
+
function O(a = 16) {
|
|
110
|
+
const r = crypto.getRandomValues(new Uint8Array(a));
|
|
111
|
+
let e = "";
|
|
112
|
+
for (let t = 0; t < a; t++)
|
|
113
|
+
e += T[r[t] % T.length];
|
|
114
|
+
return e;
|
|
115
115
|
}
|
|
116
116
|
function j(a) {
|
|
117
|
-
const
|
|
117
|
+
const r = a.id ?? O(), e = C(a.initialMessages ?? []), t = C("ready"), s = C(void 0), i = C("");
|
|
118
118
|
let o = null;
|
|
119
|
-
const
|
|
119
|
+
const n = new P(e, t, O), p = () => {
|
|
120
120
|
const l = [];
|
|
121
121
|
a.system && l.push({ role: "system", content: a.system });
|
|
122
|
-
for (const
|
|
123
|
-
if (
|
|
124
|
-
const
|
|
125
|
-
if (
|
|
126
|
-
l.push({ role: "user", content:
|
|
127
|
-
else if (
|
|
122
|
+
for (const f of e.value) {
|
|
123
|
+
if (f.role === "system") continue;
|
|
124
|
+
const c = f.parts.filter((h) => h.type === "text").map((h) => h.text).join(""), E = f.parts.filter((h) => h.type === "tool-call").map((h) => ({ id: h.toolCallId, name: h.toolName, args: h.args }));
|
|
125
|
+
if (f.role === "user")
|
|
126
|
+
l.push({ role: "user", content: c });
|
|
127
|
+
else if (f.role === "assistant") {
|
|
128
128
|
l.push({
|
|
129
129
|
role: "assistant",
|
|
130
|
-
content:
|
|
130
|
+
content: c,
|
|
131
131
|
toolCalls: E.length > 0 ? E : void 0
|
|
132
132
|
});
|
|
133
|
-
for (const
|
|
134
|
-
|
|
133
|
+
for (const h of f.parts)
|
|
134
|
+
h.type !== "tool-call" || h.state !== "result" || l.push({
|
|
135
135
|
role: "tool",
|
|
136
|
-
content: JSON.stringify(
|
|
137
|
-
toolCallId:
|
|
136
|
+
content: JSON.stringify(h.result),
|
|
137
|
+
toolCallId: h.toolCallId
|
|
138
138
|
});
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
141
|
return l;
|
|
142
|
-
},
|
|
143
|
-
const
|
|
144
|
-
let
|
|
145
|
-
for (;
|
|
146
|
-
const
|
|
142
|
+
}, g = async (l) => {
|
|
143
|
+
const f = a.maxToolRoundtrips ?? 5;
|
|
144
|
+
let u = 0;
|
|
145
|
+
for (; u < f; ) {
|
|
146
|
+
const c = p();
|
|
147
147
|
a.provider.validateConfig();
|
|
148
148
|
const { stream: E } = await a.provider.chat({
|
|
149
149
|
model: a.model,
|
|
150
|
-
messages:
|
|
150
|
+
messages: c,
|
|
151
151
|
tools: a.tools,
|
|
152
152
|
signal: l,
|
|
153
153
|
providerOptions: {
|
|
154
154
|
...a.providerOptions,
|
|
155
|
-
...
|
|
155
|
+
...N(a.body)
|
|
156
156
|
}
|
|
157
|
-
}),
|
|
157
|
+
}), h = await n.processStream(E, l, {
|
|
158
158
|
onFinish: a.onFinish,
|
|
159
159
|
onError: a.onError,
|
|
160
160
|
onToolCall: a.onToolCall
|
|
161
161
|
});
|
|
162
|
-
if (
|
|
162
|
+
if (h.finishReason !== "tool-calls" || h.toolCalls.length === 0)
|
|
163
163
|
break;
|
|
164
|
-
|
|
164
|
+
u++;
|
|
165
165
|
}
|
|
166
|
-
},
|
|
167
|
-
const
|
|
168
|
-
if (!
|
|
169
|
-
(typeof l != "object" || l === null || !("text" in l)) && (
|
|
170
|
-
const
|
|
171
|
-
id:
|
|
166
|
+
}, m = async (l) => {
|
|
167
|
+
const f = typeof l == "string" ? l : l?.text ?? i.value;
|
|
168
|
+
if (!f.trim()) return;
|
|
169
|
+
(typeof l != "object" || l === null || !("text" in l)) && (i.value = "");
|
|
170
|
+
const u = {
|
|
171
|
+
id: O(),
|
|
172
172
|
role: "user",
|
|
173
|
-
parts: [{ type: "text", text:
|
|
173
|
+
parts: [{ type: "text", text: f, state: "done" }],
|
|
174
174
|
createdAt: /* @__PURE__ */ new Date()
|
|
175
175
|
};
|
|
176
|
-
|
|
176
|
+
e.value = [...e.value, u], s.value = void 0, t.value = "submitted", o?.abort(), o = new AbortController();
|
|
177
177
|
try {
|
|
178
|
-
await
|
|
179
|
-
} catch (
|
|
178
|
+
await g(o.signal), t.value = "ready";
|
|
179
|
+
} catch (c) {
|
|
180
180
|
if (o.signal.aborted) {
|
|
181
|
-
|
|
181
|
+
t.value = "ready";
|
|
182
182
|
return;
|
|
183
183
|
}
|
|
184
|
-
|
|
184
|
+
s.value = c instanceof Error ? c : new Error(String(c)), t.value = "error";
|
|
185
185
|
}
|
|
186
186
|
}, v = async () => {
|
|
187
|
-
const l =
|
|
188
|
-
if (
|
|
189
|
-
|
|
187
|
+
const l = e.value, f = l.reduce((u, c, E) => c.role === "assistant" ? E : u, -1);
|
|
188
|
+
if (f !== -1) {
|
|
189
|
+
e.value = l.slice(0, f), s.value = void 0, t.value = "submitted", o?.abort(), o = new AbortController();
|
|
190
190
|
try {
|
|
191
|
-
await
|
|
192
|
-
} catch (
|
|
191
|
+
await g(o.signal), t.value = "ready";
|
|
192
|
+
} catch (u) {
|
|
193
193
|
if (o.signal.aborted) {
|
|
194
|
-
|
|
194
|
+
t.value = "ready";
|
|
195
195
|
return;
|
|
196
196
|
}
|
|
197
|
-
|
|
197
|
+
s.value = u instanceof Error ? u : new Error(String(u)), t.value = "error";
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
|
-
},
|
|
201
|
-
o?.abort(), o = null,
|
|
202
|
-
},
|
|
203
|
-
|
|
200
|
+
}, S = () => {
|
|
201
|
+
o?.abort(), o = null, t.value = "ready";
|
|
202
|
+
}, w = (l) => {
|
|
203
|
+
e.value = typeof l == "function" ? l(e.value) : l;
|
|
204
204
|
}, y = (l) => {
|
|
205
|
-
l?.preventDefault?.(),
|
|
206
|
-
},
|
|
207
|
-
for (const
|
|
208
|
-
for (const
|
|
209
|
-
if (
|
|
210
|
-
|
|
205
|
+
l?.preventDefault?.(), i.value.trim() && m();
|
|
206
|
+
}, d = R(() => t.value === "submitted" || t.value === "streaming"), b = ({ toolCallId: l, result: f }) => {
|
|
207
|
+
for (const u of e.value)
|
|
208
|
+
for (const c of u.parts)
|
|
209
|
+
if (c.type === "tool-call" && c.toolCallId === l) {
|
|
210
|
+
c.state = "result", c.result = f, e.value = [...e.value];
|
|
211
211
|
return;
|
|
212
212
|
}
|
|
213
|
-
},
|
|
214
|
-
|
|
213
|
+
}, x = () => {
|
|
214
|
+
s.value = void 0, t.value === "error" && (t.value = "ready");
|
|
215
215
|
};
|
|
216
|
-
return
|
|
216
|
+
return I(() => {
|
|
217
217
|
o?.abort();
|
|
218
218
|
}), {
|
|
219
|
-
messages:
|
|
220
|
-
status: R(() =>
|
|
221
|
-
error:
|
|
222
|
-
id:
|
|
223
|
-
input:
|
|
224
|
-
sendMessage:
|
|
219
|
+
messages: e,
|
|
220
|
+
status: R(() => t.value),
|
|
221
|
+
error: s,
|
|
222
|
+
id: r,
|
|
223
|
+
input: i,
|
|
224
|
+
sendMessage: m,
|
|
225
225
|
regenerate: v,
|
|
226
|
-
stop:
|
|
227
|
-
setMessages:
|
|
226
|
+
stop: S,
|
|
227
|
+
setMessages: w,
|
|
228
228
|
handleSubmit: y,
|
|
229
|
-
isLoading:
|
|
230
|
-
addToolResult:
|
|
231
|
-
clearError:
|
|
229
|
+
isLoading: d,
|
|
230
|
+
addToolResult: b,
|
|
231
|
+
clearError: x
|
|
232
232
|
};
|
|
233
233
|
}
|
|
234
234
|
function J(a) {
|
|
235
|
-
const
|
|
235
|
+
const r = a.id ?? O(), e = C(""), t = C("ready"), s = C(void 0), i = C("");
|
|
236
236
|
let o = null;
|
|
237
|
-
const
|
|
238
|
-
const
|
|
239
|
-
if (!
|
|
240
|
-
|
|
237
|
+
const n = async (S) => {
|
|
238
|
+
const w = S ?? i.value;
|
|
239
|
+
if (!w.trim()) return e.value;
|
|
240
|
+
S || (i.value = ""), e.value = "", s.value = void 0, t.value = "submitted", o?.abort(), o = new AbortController();
|
|
241
241
|
try {
|
|
242
242
|
a.provider.validateConfig();
|
|
243
243
|
const y = a.system ? [
|
|
244
244
|
{ role: "system", content: a.system },
|
|
245
|
-
{ role: "user", content:
|
|
246
|
-
] : [{ role: "user", content:
|
|
245
|
+
{ role: "user", content: w }
|
|
246
|
+
] : [{ role: "user", content: w }], { stream: d } = await a.provider.chat({
|
|
247
247
|
model: a.model,
|
|
248
248
|
messages: y,
|
|
249
249
|
signal: o.signal
|
|
250
250
|
});
|
|
251
|
-
|
|
252
|
-
const
|
|
253
|
-
let
|
|
251
|
+
t.value = "streaming";
|
|
252
|
+
const b = d.getReader();
|
|
253
|
+
let x = "stop", l;
|
|
254
254
|
for (; !o.signal.aborted; ) {
|
|
255
|
-
const { done:
|
|
256
|
-
if (
|
|
257
|
-
if (
|
|
258
|
-
|
|
259
|
-
else if (
|
|
260
|
-
|
|
261
|
-
else if (
|
|
262
|
-
throw
|
|
255
|
+
const { done: f, value: u } = await b.read();
|
|
256
|
+
if (f) break;
|
|
257
|
+
if (u.type === "text-delta")
|
|
258
|
+
e.value += u.text;
|
|
259
|
+
else if (u.type === "finish")
|
|
260
|
+
x = u.finishReason, l = u.usage;
|
|
261
|
+
else if (u.type === "error")
|
|
262
|
+
throw u.error;
|
|
263
263
|
}
|
|
264
|
-
return
|
|
264
|
+
return b.releaseLock(), t.value = "ready", a.onFinish?.(e.value, { finishReason: x, usage: l }), e.value;
|
|
265
265
|
} catch (y) {
|
|
266
266
|
if (!o || o.signal.aborted)
|
|
267
|
-
return
|
|
268
|
-
const
|
|
269
|
-
return
|
|
267
|
+
return t.value = "ready", e.value;
|
|
268
|
+
const d = y instanceof Error ? y : new Error(String(y));
|
|
269
|
+
return s.value = d, t.value = "error", a.onError?.(d), e.value;
|
|
270
270
|
}
|
|
271
|
-
},
|
|
272
|
-
o?.abort(), o = null,
|
|
273
|
-
},
|
|
274
|
-
|
|
275
|
-
},
|
|
276
|
-
|
|
277
|
-
}, v = R(() =>
|
|
278
|
-
return
|
|
271
|
+
}, p = () => {
|
|
272
|
+
o?.abort(), o = null, t.value = "ready";
|
|
273
|
+
}, g = () => {
|
|
274
|
+
s.value = void 0, t.value === "error" && (t.value = "ready");
|
|
275
|
+
}, m = (S) => {
|
|
276
|
+
S?.preventDefault?.(), i.value.trim() && n();
|
|
277
|
+
}, v = R(() => t.value === "submitted" || t.value === "streaming");
|
|
278
|
+
return I(() => {
|
|
279
279
|
o?.abort();
|
|
280
280
|
}), {
|
|
281
|
-
completion:
|
|
282
|
-
status: R(() =>
|
|
283
|
-
error:
|
|
281
|
+
completion: e,
|
|
282
|
+
status: R(() => t.value),
|
|
283
|
+
error: s,
|
|
284
284
|
isLoading: v,
|
|
285
|
-
id:
|
|
286
|
-
input:
|
|
287
|
-
complete:
|
|
288
|
-
stop:
|
|
289
|
-
clearError:
|
|
290
|
-
handleSubmit:
|
|
285
|
+
id: r,
|
|
286
|
+
input: i,
|
|
287
|
+
complete: n,
|
|
288
|
+
stop: p,
|
|
289
|
+
clearError: g,
|
|
290
|
+
handleSubmit: m
|
|
291
291
|
};
|
|
292
292
|
}
|
|
293
|
-
function
|
|
294
|
-
const
|
|
295
|
-
let
|
|
296
|
-
const
|
|
297
|
-
const
|
|
298
|
-
if (!
|
|
299
|
-
|
|
293
|
+
function F(a) {
|
|
294
|
+
const r = a.id ?? O(), e = C(void 0), t = C(void 0), s = C("ready"), i = C(void 0), o = C("");
|
|
295
|
+
let n = null;
|
|
296
|
+
const p = async (S) => {
|
|
297
|
+
const w = S ?? o.value;
|
|
298
|
+
if (!w.trim()) return e.value;
|
|
299
|
+
S || (o.value = ""), e.value = void 0, t.value = void 0, i.value = void 0, s.value = "submitted", n?.abort(), n = new AbortController();
|
|
300
300
|
try {
|
|
301
301
|
a.provider.validateConfig();
|
|
302
302
|
const y = [
|
|
@@ -306,98 +306,178 @@ function L(a) {
|
|
|
306
306
|
"Output ONLY the JSON object, no other text."
|
|
307
307
|
].filter(Boolean).join(`
|
|
308
308
|
|
|
309
|
-
`), { stream:
|
|
309
|
+
`), { stream: d } = await a.provider.chat({
|
|
310
310
|
model: a.model,
|
|
311
311
|
messages: [
|
|
312
312
|
{ role: "system", content: y },
|
|
313
|
-
{ role: "user", content:
|
|
313
|
+
{ role: "user", content: w }
|
|
314
314
|
],
|
|
315
|
-
signal:
|
|
315
|
+
signal: n.signal,
|
|
316
316
|
providerOptions: {
|
|
317
317
|
response_format: { type: "json_object" }
|
|
318
318
|
}
|
|
319
319
|
});
|
|
320
|
-
|
|
321
|
-
const
|
|
322
|
-
let
|
|
323
|
-
for (; !
|
|
324
|
-
const { done:
|
|
325
|
-
if (
|
|
326
|
-
if (
|
|
327
|
-
|
|
320
|
+
s.value = "streaming";
|
|
321
|
+
const b = d.getReader();
|
|
322
|
+
let x = "", l = "stop", f;
|
|
323
|
+
for (; !n.signal.aborted; ) {
|
|
324
|
+
const { done: u, value: c } = await b.read();
|
|
325
|
+
if (u) break;
|
|
326
|
+
if (c.type === "text-delta") {
|
|
327
|
+
x += c.text;
|
|
328
328
|
try {
|
|
329
|
-
|
|
329
|
+
t.value = M(x);
|
|
330
330
|
} catch {
|
|
331
331
|
}
|
|
332
|
-
} else if (
|
|
333
|
-
l =
|
|
334
|
-
else if (
|
|
335
|
-
throw
|
|
332
|
+
} else if (c.type === "finish")
|
|
333
|
+
l = c.finishReason, f = c.usage;
|
|
334
|
+
else if (c.type === "error")
|
|
335
|
+
throw c.error;
|
|
336
336
|
}
|
|
337
|
-
|
|
337
|
+
b.releaseLock();
|
|
338
338
|
try {
|
|
339
|
-
|
|
339
|
+
e.value = JSON.parse(x), t.value = e.value;
|
|
340
340
|
} catch {
|
|
341
|
-
throw new Error(`Failed to parse JSON response: ${
|
|
341
|
+
throw new Error(`Failed to parse JSON response: ${x.slice(0, 200)}`);
|
|
342
342
|
}
|
|
343
|
-
return
|
|
343
|
+
return s.value = "ready", a.onFinish?.(e.value, { finishReason: l, usage: f }), e.value;
|
|
344
344
|
} catch (y) {
|
|
345
|
-
if (
|
|
346
|
-
return
|
|
347
|
-
const
|
|
348
|
-
|
|
345
|
+
if (n.signal.aborted)
|
|
346
|
+
return s.value = "ready", e.value;
|
|
347
|
+
const d = y instanceof Error ? y : new Error(String(y));
|
|
348
|
+
i.value = d, s.value = "error", a.onError?.(d);
|
|
349
349
|
return;
|
|
350
350
|
}
|
|
351
|
-
},
|
|
352
|
-
|
|
353
|
-
},
|
|
354
|
-
|
|
355
|
-
}, v = R(() =>
|
|
356
|
-
return
|
|
357
|
-
|
|
351
|
+
}, g = () => {
|
|
352
|
+
n?.abort(), n = null, s.value = "ready";
|
|
353
|
+
}, m = () => {
|
|
354
|
+
i.value = void 0, s.value === "error" && (s.value = "ready");
|
|
355
|
+
}, v = R(() => s.value === "submitted" || s.value === "streaming");
|
|
356
|
+
return I(() => {
|
|
357
|
+
n?.abort();
|
|
358
358
|
}), {
|
|
359
|
-
object:
|
|
360
|
-
partialObject:
|
|
361
|
-
status: R(() =>
|
|
362
|
-
error:
|
|
359
|
+
object: e,
|
|
360
|
+
partialObject: t,
|
|
361
|
+
status: R(() => s.value),
|
|
362
|
+
error: i,
|
|
363
363
|
isLoading: v,
|
|
364
|
-
id:
|
|
364
|
+
id: r,
|
|
365
365
|
input: o,
|
|
366
|
-
submit:
|
|
367
|
-
stop:
|
|
368
|
-
clearError:
|
|
366
|
+
submit: p,
|
|
367
|
+
stop: g,
|
|
368
|
+
clearError: m
|
|
369
369
|
};
|
|
370
370
|
}
|
|
371
|
-
function
|
|
372
|
-
let
|
|
373
|
-
if (!
|
|
374
|
-
let
|
|
375
|
-
for (let
|
|
376
|
-
const o =
|
|
377
|
-
if (
|
|
378
|
-
|
|
371
|
+
function M(a) {
|
|
372
|
+
let r = a.trim();
|
|
373
|
+
if (!r.startsWith("{")) return;
|
|
374
|
+
let e = 0, t = !1, s = !1;
|
|
375
|
+
for (let i = 0; i < r.length; i++) {
|
|
376
|
+
const o = r[i];
|
|
377
|
+
if (s) {
|
|
378
|
+
s = !1;
|
|
379
379
|
continue;
|
|
380
380
|
}
|
|
381
381
|
if (o === "\\") {
|
|
382
|
-
|
|
382
|
+
s = !0;
|
|
383
383
|
continue;
|
|
384
384
|
}
|
|
385
385
|
if (o === '"') {
|
|
386
|
-
|
|
386
|
+
t = !t;
|
|
387
387
|
continue;
|
|
388
388
|
}
|
|
389
|
-
|
|
389
|
+
t || (o === "{" && e++, o === "}" && e--);
|
|
390
390
|
}
|
|
391
|
-
for (;
|
|
392
|
-
|
|
391
|
+
for (; e > 0; )
|
|
392
|
+
r += "}", e--;
|
|
393
393
|
try {
|
|
394
|
-
return JSON.parse(
|
|
394
|
+
return JSON.parse(r);
|
|
395
395
|
} catch {
|
|
396
396
|
return;
|
|
397
397
|
}
|
|
398
398
|
}
|
|
399
|
+
function L(a, r) {
|
|
400
|
+
return r.length ? {
|
|
401
|
+
id: a.id,
|
|
402
|
+
supportsStreaming: a.supportsStreaming,
|
|
403
|
+
validateConfig() {
|
|
404
|
+
a.validateConfig();
|
|
405
|
+
},
|
|
406
|
+
async chat(e) {
|
|
407
|
+
let t = e;
|
|
408
|
+
for (const n of r)
|
|
409
|
+
n.beforeRequest && (t = await n.beforeRequest(t, a));
|
|
410
|
+
let s;
|
|
411
|
+
try {
|
|
412
|
+
s = await a.chat(t);
|
|
413
|
+
} catch (n) {
|
|
414
|
+
let p = n instanceof Error ? n : new Error(String(n));
|
|
415
|
+
for (const g of r)
|
|
416
|
+
if (g.onError) {
|
|
417
|
+
const m = await g.onError(p, t);
|
|
418
|
+
m instanceof Error && (p = m);
|
|
419
|
+
}
|
|
420
|
+
throw p;
|
|
421
|
+
}
|
|
422
|
+
const o = r.some((n) => n.afterStream) ? s.stream.pipeThrough(new TransformStream({
|
|
423
|
+
async transform(n, p) {
|
|
424
|
+
let g = n;
|
|
425
|
+
for (const m of r) {
|
|
426
|
+
if (!g) break;
|
|
427
|
+
m.afterStream && (g = await m.afterStream(g, t));
|
|
428
|
+
}
|
|
429
|
+
g && p.enqueue(g);
|
|
430
|
+
}
|
|
431
|
+
})) : s.stream;
|
|
432
|
+
for (const n of r)
|
|
433
|
+
n.onFinish && n.onFinish(t, s);
|
|
434
|
+
return { stream: o, response: s.response };
|
|
435
|
+
}
|
|
436
|
+
} : a;
|
|
437
|
+
}
|
|
438
|
+
function $(a = "vue-llm") {
|
|
439
|
+
return {
|
|
440
|
+
beforeRequest(r) {
|
|
441
|
+
return console.log(`[${a}] → ${r.model}`, r.messages.length, "messages"), r;
|
|
442
|
+
},
|
|
443
|
+
afterStream(r) {
|
|
444
|
+
return r.type === "finish" && console.log(`[${a}] ← finish:`, r.finishReason, r.usage ?? ""), r;
|
|
445
|
+
},
|
|
446
|
+
onError(r) {
|
|
447
|
+
console.error(`[${a}] error:`, r.message);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
function D(a = 3, r = 1e3) {
|
|
452
|
+
return {
|
|
453
|
+
async onError(e, t) {
|
|
454
|
+
const s = e.message;
|
|
455
|
+
if (!(s.includes("429") || s.includes("500") || s.includes("502") || s.includes("503"))) return e;
|
|
456
|
+
for (let o = 0; o < a; o++)
|
|
457
|
+
await new Promise((n) => setTimeout(n, r * (o + 1))), console.log(`[vue-llm] retry ${o + 1}/${a}`);
|
|
458
|
+
return e;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function q(a) {
|
|
463
|
+
return {
|
|
464
|
+
beforeRequest(r) {
|
|
465
|
+
return {
|
|
466
|
+
...r,
|
|
467
|
+
providerOptions: {
|
|
468
|
+
...r.providerOptions,
|
|
469
|
+
headers: { ...r.providerOptions?.headers, ...a }
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
}
|
|
399
475
|
export {
|
|
476
|
+
q as headerMiddleware,
|
|
477
|
+
$ as loggingMiddleware,
|
|
478
|
+
D as retryMiddleware,
|
|
400
479
|
j as useChat,
|
|
401
480
|
J as useCompletion,
|
|
402
|
-
|
|
481
|
+
F as useObject,
|
|
482
|
+
L as wrapProvider
|
|
403
483
|
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ChatRequest, ChatStreamResult, ChatStreamChunk, LLMProvider } from './providers/types';
|
|
2
|
+
export interface Middleware {
|
|
3
|
+
beforeRequest?: (request: ChatRequest, provider: LLMProvider) => ChatRequest | Promise<ChatRequest>;
|
|
4
|
+
afterStream?: (chunk: ChatStreamChunk, request: ChatRequest) => ChatStreamChunk | null | Promise<ChatStreamChunk | null>;
|
|
5
|
+
onError?: (error: Error, request: ChatRequest) => Error | void | Promise<Error | void>;
|
|
6
|
+
onFinish?: (request: ChatRequest, response: ChatStreamResult) => void | Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare function wrapProvider(provider: LLMProvider, middlewares: Middleware[]): LLMProvider;
|
|
9
|
+
export declare function loggingMiddleware(label?: string): Middleware;
|
|
10
|
+
export declare function retryMiddleware(maxRetries?: number, delay?: number): Middleware;
|
|
11
|
+
export declare function headerMiddleware(headers: Record<string, string>): Middleware;
|