vue-llm 1.6.0 → 1.8.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/components/MessageParts.vue.d.ts +6 -1
- package/dist/components.cjs +5 -5
- package/dist/components.js +84 -77
- package/dist/composables/use-chat.d.ts +7 -2
- package/dist/index.cjs +3 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +515 -488
- package/dist/providers/sse.d.ts +2 -0
- package/dist/providers/types.d.ts +21 -1
- package/dist/providers.cjs +1 -1
- package/dist/providers.js +2 -2
- package/dist/server.cjs +1 -1
- package/dist/server.js +1 -1
- package/dist/{sse-DU5m1n6r.js → sse-CbFKaVA2.js} +1 -1
- package/dist/{sse-PZGBuYKy.cjs → sse-QNG6DnpI.cjs} +1 -1
- package/dist/types.d.ts +16 -1
- package/dist/vue-llm.css +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Component } from 'vue';
|
|
2
|
-
import type { ToolCallPart, UIMessage } from '../types.js';
|
|
2
|
+
import type { DataPart, ToolCallPart, UIMessage } from '../types.js';
|
|
3
3
|
type __VLS_Props = {
|
|
4
4
|
message: UIMessage;
|
|
5
5
|
/** Components that render tool calls, keyed by tool name (Generative UI) */
|
|
6
6
|
components?: Record<string, Component>;
|
|
7
|
+
/** Components that render data parts, keyed by their `name` */
|
|
8
|
+
dataComponents?: Record<string, Component>;
|
|
7
9
|
/** Markdown renderer for text parts, see StreamMarkdown */
|
|
8
10
|
render?: (markdown: string) => string;
|
|
9
11
|
};
|
|
@@ -12,6 +14,9 @@ type __VLS_Slots = {
|
|
|
12
14
|
part: ToolCallPart;
|
|
13
15
|
addResult: (result: unknown) => void;
|
|
14
16
|
}) => unknown;
|
|
17
|
+
data?: (props: {
|
|
18
|
+
part: DataPart;
|
|
19
|
+
}) => unknown;
|
|
15
20
|
};
|
|
16
21
|
declare const __VLS_component: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
|
|
17
22
|
"tool-result": (payload: {
|
package/dist/components.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),C=/^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;function h(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function B(s){const t=s.replace(/\r\n?/g,`
|
|
2
2
|
`).split(`
|
|
3
|
-
`),l=[];let n=0;for(;n<t.length;){const
|
|
4
|
-
`))}</code></pre>`);continue}if(!
|
|
5
|
-
`))}</blockquote>`);continue}if(v(t,n)){const a
|
|
6
|
-
`)}function p(
|
|
3
|
+
`),l=[];let n=0;for(;n<t.length;){const i=t[n],r=/^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(i);if(r){const a=[];for(n++;n<t.length&&!t[n].trimStart().startsWith(r[1]);)a.push(t[n]),n++;n++;const u=r[2]?` class="language-${h(r[2])}"`:"";l.push(`<pre><code${u}>${h(a.join(`
|
|
4
|
+
`))}</code></pre>`);continue}if(!i.trim()){n++;continue}const m=/^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(i);if(m){const a=m[1].length;l.push(`<h${a}>${p(m[2])}</h${a}>`),n++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(i)){l.push("<hr>"),n++;continue}if(/^\s*>/.test(i)){const a=[];for(;n<t.length&&/^\s*>/.test(t[n]);)a.push(t[n].replace(/^\s*>\s?/,"")),n++;l.push(`<blockquote>${B(a.join(`
|
|
5
|
+
`))}</blockquote>`);continue}if(v(t,n)){const a=y(t[n]),u=y(t[n+1]).map(c=>c.endsWith(":")?c.startsWith(":")?"center":"right":c.startsWith(":")?"left":"");n+=2;const d=[];for(;n<t.length&&t[n].includes("|")&&t[n].trim();)d.push(y(t[n])),n++;const f=(c,$,g)=>{const E=u[g]?` style="text-align:${u[g]}"`:"";return`<${c}${E}>${p($)}</${c}>`};l.push("<table><thead><tr>"+a.map((c,$)=>f("th",c,$)).join("")+"</tr></thead><tbody>"+d.map(c=>"<tr>"+a.map(($,g)=>f("td",c[g]??"",g)).join("")+"</tr>").join("")+"</tbody></table>");continue}const o=/^\s*([-*+]|\d+[.)])\s+/.exec(i);if(o){const a=/\d/.test(o[1]),u=[];for(;n<t.length;){const c=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(t[n]);if(c&&/\d/.test(c[1])===a)u.push(c[2]);else if(t[n].trim()&&/^\s{2,}/.test(t[n])&&u.length>0)u[u.length-1]+=" "+t[n].trim();else break;n++}const d=a?"ol":"ul",f=a&&parseInt(o[1],10)!==1?` start="${parseInt(o[1],10)}"`:"";l.push(`<${d}${f}>${u.map(c=>`<li>${p(c)}</li>`).join("")}</${d}>`);continue}const k=[];for(;n<t.length&&t[n].trim()&&!b(t,n);)k.push(t[n].trim()),n++;l.push(`<p>${k.map(p).join("<br>")}</p>`)}return l.join(`
|
|
6
|
+
`)}function p(s){return s.split(/(`+[^`]*`+)/).map((t,l)=>l%2===1?`<code>${h(t.replace(/^`+|`+$/g,""))}</code>`:M(h(t))).join("")}function M(s){return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(t,l,n)=>_(n)?`<img src="${n}" alt="${l}">`:l).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(t,l,n)=>_(n)?`<a href="${n}" target="_blank" rel="noopener noreferrer">${l}</a>`:l).replace(new RegExp("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1","g"),"<strong>$2</strong>").replace(new RegExp("(?<![\\w*])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![\\w*])","g"),"<em>$1</em>").replace(new RegExp("(?<![\\w_])_(?=\\S)(.+?)(?<=\\S)_(?![\\w_])","g"),"<em>$1</em>").replace(new RegExp("~~(?=\\S)(.+?)(?<=\\S)~~","g"),"<del>$1</del>")}function _(s){const t=s.replace(/&/g,"&").replace(/&#(x?[0-9a-f]+);?/gi,"?");return C.test(t.trim())}function y(s){return s.trim().replace(/^\||\|$/g,"").split("|").map(t=>t.trim())}function v(s,t){return s[t].includes("|")&&t+1<s.length&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(s[t+1])}function b(s,t){const l=s[t];return/^\s*(`{3,}|~{3,})/.test(l)||/^#{1,6}\s/.test(l)||/^\s*>/.test(l)||/^\s*([-*+]|\d+[.)])\s+/.test(l)||/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)||v(s,t)}const x=["innerHTML"],I={key:0,class:"vue-llm-cursor","aria-hidden":"true"},j=e.defineComponent({__name:"StreamMarkdown",props:{content:{},streaming:{type:Boolean},render:{type:Function}},setup(s){const t=s,l=e.computed(()=>(t.render??B)(t.content));return(n,i)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createElementVNode("div",{class:"vue-llm-markdown",innerHTML:l.value},null,8,x),s.streaming?(e.openBlock(),e.createElementBlock("span",I,"▊")):e.createCommentVNode("",!0)],64))}}),S=(s,t)=>{const l=s.__vccOpts||s;for(const[n,i]of t)l[n]=i;return l},w=S(j,[["__scopeId","data-v-f225ccf4"]]),F=["data-role"],N={key:0,class:"vue-llm-text"},T=["open"],L=["src","alt"],R={key:1,class:"vue-llm-file"},D=["href"],P=e.defineComponent({__name:"MessageParts",props:{message:{},components:{},dataComponents:{},render:{type:Function}},emits:["tool-result"],setup(s,{emit:t}){const l=t,n=(r,m)=>r.type==="tool-call"?r.toolCallId:r.type==="data"&&r.id!==void 0?`data:${r.name}:${r.id}`:m,i=r=>({toolCallId:r.toolCallId,toolName:r.toolName,args:r.args,state:r.state,result:r.result,error:r.error,addResult:m=>l("tool-result",{toolCallId:r.toolCallId,result:m})});return(r,m)=>(e.openBlock(),e.createElementBlock("div",{class:"vue-llm-message","data-role":s.message.role},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.message.parts,(o,k)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:n(o,k)},[o.type==="text"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[s.message.role==="user"?(e.openBlock(),e.createElementBlock("div",N,e.toDisplayString(o.text),1)):(e.openBlock(),e.createBlock(w,{key:1,content:o.text,streaming:o.state==="streaming",render:s.render},null,8,["content","streaming","render"]))],64)):o.type==="reasoning"?(e.openBlock(),e.createElementBlock("details",{key:1,class:"vue-llm-reasoning",open:o.state==="streaming"},[m[0]||(m[0]=e.createElementVNode("summary",null,"Reasoning",-1)),e.createElementVNode("div",null,e.toDisplayString(o.text),1)],8,T)):o.type==="tool-call"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[s.components?.[o.toolName]?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(s.components[o.toolName]),e.mergeProps({key:0,ref_for:!0},i(o)),null,16)):e.renderSlot(r.$slots,"tool",{part:o,addResult:i(o).addResult},void 0,!0,1)],64)):o.type==="data"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[s.dataComponents?.[o.name]?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(s.dataComponents[o.name]),{key:0,name:o.name,data:o.data},null,8,["name","data"])):e.renderSlot(r.$slots,"data",{part:o},void 0,!0,1)],64)):o.type==="file"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:4},[o.mediaType.startsWith("image/")?(e.openBlock(),e.createElementBlock("img",{key:0,class:"vue-llm-file",src:o.url,alt:o.filename??""},null,8,L)):(e.openBlock(),e.createElementBlock("span",R,e.toDisplayString(o.filename??o.mediaType),1))],64)):o.type==="source"&&/^https?:/i.test(o.url)?(e.openBlock(),e.createElementBlock("a",{key:5,class:"vue-llm-source",href:o.url,target:"_blank",rel:"noopener noreferrer"},e.toDisplayString(o.title??o.url),9,D)):e.createCommentVNode("",!0)],64))),128))],8,F))}}),q=S(P,[["__scopeId","data-v-3868ad67"]]);exports.MessageParts=q;exports.StreamMarkdown=w;exports.escapeHTML=h;exports.renderInline=p;exports.renderMarkdown=B;
|
package/dist/components.js
CHANGED
|
@@ -1,112 +1,112 @@
|
|
|
1
|
-
import { defineComponent as
|
|
1
|
+
import { defineComponent as j, computed as B, openBlock as r, createElementBlock as i, Fragment as g, createElementVNode as x, createCommentVNode as M, renderList as W, toDisplayString as _, createBlock as w, resolveDynamicComponent as C, mergeProps as q, renderSlot as b } from "vue";
|
|
2
2
|
const E = /^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;
|
|
3
|
-
function
|
|
3
|
+
function v(s) {
|
|
4
4
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
5
5
|
}
|
|
6
|
-
function
|
|
6
|
+
function R(s) {
|
|
7
7
|
const e = s.replace(/\r\n?/g, `
|
|
8
8
|
`).split(`
|
|
9
9
|
`), o = [];
|
|
10
10
|
let t = 0;
|
|
11
11
|
for (; t < e.length; ) {
|
|
12
|
-
const
|
|
13
|
-
if (
|
|
12
|
+
const u = e[t], l = /^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(u);
|
|
13
|
+
if (l) {
|
|
14
14
|
const c = [];
|
|
15
|
-
for (t++; t < e.length && !e[t].trimStart().startsWith(
|
|
15
|
+
for (t++; t < e.length && !e[t].trimStart().startsWith(l[1]); )
|
|
16
16
|
c.push(e[t]), t++;
|
|
17
17
|
t++;
|
|
18
|
-
const
|
|
19
|
-
o.push(`<pre><code${
|
|
18
|
+
const d = l[2] ? ` class="language-${v(l[2])}"` : "";
|
|
19
|
+
o.push(`<pre><code${d}>${v(c.join(`
|
|
20
20
|
`))}</code></pre>`);
|
|
21
21
|
continue;
|
|
22
22
|
}
|
|
23
|
-
if (!
|
|
23
|
+
if (!u.trim()) {
|
|
24
24
|
t++;
|
|
25
25
|
continue;
|
|
26
26
|
}
|
|
27
|
-
const
|
|
28
|
-
if (
|
|
29
|
-
const c =
|
|
30
|
-
o.push(`<h${c}>${
|
|
27
|
+
const m = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(u);
|
|
28
|
+
if (m) {
|
|
29
|
+
const c = m[1].length;
|
|
30
|
+
o.push(`<h${c}>${k(m[2])}</h${c}>`), t++;
|
|
31
31
|
continue;
|
|
32
32
|
}
|
|
33
|
-
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(
|
|
33
|
+
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(u)) {
|
|
34
34
|
o.push("<hr>"), t++;
|
|
35
35
|
continue;
|
|
36
36
|
}
|
|
37
|
-
if (/^\s*>/.test(
|
|
37
|
+
if (/^\s*>/.test(u)) {
|
|
38
38
|
const c = [];
|
|
39
39
|
for (; t < e.length && /^\s*>/.test(e[t]); )
|
|
40
40
|
c.push(e[t].replace(/^\s*>\s?/, "")), t++;
|
|
41
|
-
o.push(`<blockquote>${
|
|
41
|
+
o.push(`<blockquote>${R(c.join(`
|
|
42
42
|
`))}</blockquote>`);
|
|
43
43
|
continue;
|
|
44
44
|
}
|
|
45
|
-
if (
|
|
46
|
-
const c =
|
|
45
|
+
if (L(e, t)) {
|
|
46
|
+
const c = S(e[t]), d = S(e[t + 1]).map((a) => a.endsWith(":") ? a.startsWith(":") ? "center" : "right" : a.startsWith(":") ? "left" : "");
|
|
47
47
|
t += 2;
|
|
48
48
|
const h = [];
|
|
49
49
|
for (; t < e.length && e[t].includes("|") && e[t].trim(); )
|
|
50
|
-
h.push(
|
|
51
|
-
const
|
|
52
|
-
const
|
|
53
|
-
return `<${
|
|
50
|
+
h.push(S(e[t])), t++;
|
|
51
|
+
const $ = (a, y, p) => {
|
|
52
|
+
const T = d[p] ? ` style="text-align:${d[p]}"` : "";
|
|
53
|
+
return `<${a}${T}>${k(y)}</${a}>`;
|
|
54
54
|
};
|
|
55
55
|
o.push(
|
|
56
|
-
"<table><thead><tr>" + c.map((
|
|
56
|
+
"<table><thead><tr>" + c.map((a, y) => $("th", a, y)).join("") + "</tr></thead><tbody>" + h.map((a) => "<tr>" + c.map((y, p) => $("td", a[p] ?? "", p)).join("") + "</tr>").join("") + "</tbody></table>"
|
|
57
57
|
);
|
|
58
58
|
continue;
|
|
59
59
|
}
|
|
60
|
-
const
|
|
61
|
-
if (
|
|
62
|
-
const c = /\d/.test(
|
|
60
|
+
const n = /^\s*([-*+]|\d+[.)])\s+/.exec(u);
|
|
61
|
+
if (n) {
|
|
62
|
+
const c = /\d/.test(n[1]), d = [];
|
|
63
63
|
for (; t < e.length; ) {
|
|
64
|
-
const
|
|
65
|
-
if (
|
|
66
|
-
|
|
67
|
-
else if (e[t].trim() && /^\s{2,}/.test(e[t]) &&
|
|
68
|
-
|
|
64
|
+
const a = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(e[t]);
|
|
65
|
+
if (a && /\d/.test(a[1]) === c)
|
|
66
|
+
d.push(a[2]);
|
|
67
|
+
else if (e[t].trim() && /^\s{2,}/.test(e[t]) && d.length > 0)
|
|
68
|
+
d[d.length - 1] += " " + e[t].trim();
|
|
69
69
|
else
|
|
70
70
|
break;
|
|
71
71
|
t++;
|
|
72
72
|
}
|
|
73
|
-
const h = c ? "ol" : "ul",
|
|
74
|
-
o.push(`<${h}${
|
|
73
|
+
const h = c ? "ol" : "ul", $ = c && parseInt(n[1], 10) !== 1 ? ` start="${parseInt(n[1], 10)}"` : "";
|
|
74
|
+
o.push(`<${h}${$}>${d.map((a) => `<li>${k(a)}</li>`).join("")}</${h}>`);
|
|
75
75
|
continue;
|
|
76
76
|
}
|
|
77
|
-
const
|
|
77
|
+
const f = [];
|
|
78
78
|
for (; t < e.length && e[t].trim() && !P(e, t); )
|
|
79
|
-
|
|
80
|
-
o.push(`<p>${
|
|
79
|
+
f.push(e[t].trim()), t++;
|
|
80
|
+
o.push(`<p>${f.map(k).join("<br>")}</p>`);
|
|
81
81
|
}
|
|
82
82
|
return o.join(`
|
|
83
83
|
`);
|
|
84
84
|
}
|
|
85
|
-
function
|
|
86
|
-
return s.split(/(`+[^`]*`+)/).map((e, o) => o % 2 === 1 ? `<code>${
|
|
85
|
+
function k(s) {
|
|
86
|
+
return s.split(/(`+[^`]*`+)/).map((e, o) => o % 2 === 1 ? `<code>${v(e.replace(/^`+|`+$/g, ""))}</code>` : F(v(e))).join("");
|
|
87
87
|
}
|
|
88
88
|
function F(s) {
|
|
89
|
-
return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (e, o, t) =>
|
|
89
|
+
return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (e, o, t) => I(t) ? `<img src="${t}" alt="${o}">` : o).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (e, o, t) => I(t) ? `<a href="${t}" target="_blank" rel="noopener noreferrer">${o}</a>` : o).replace(new RegExp("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1", "g"), "<strong>$2</strong>").replace(new RegExp("(?<![\\w*])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![\\w*])", "g"), "<em>$1</em>").replace(new RegExp("(?<![\\w_])_(?=\\S)(.+?)(?<=\\S)_(?![\\w_])", "g"), "<em>$1</em>").replace(new RegExp("~~(?=\\S)(.+?)(?<=\\S)~~", "g"), "<del>$1</del>");
|
|
90
90
|
}
|
|
91
|
-
function
|
|
91
|
+
function I(s) {
|
|
92
92
|
const e = s.replace(/&/g, "&").replace(/&#(x?[0-9a-f]+);?/gi, "?");
|
|
93
93
|
return E.test(e.trim());
|
|
94
94
|
}
|
|
95
|
-
function
|
|
95
|
+
function S(s) {
|
|
96
96
|
return s.trim().replace(/^\||\|$/g, "").split("|").map((e) => e.trim());
|
|
97
97
|
}
|
|
98
|
-
function
|
|
98
|
+
function L(s, e) {
|
|
99
99
|
return s[e].includes("|") && e + 1 < s.length && /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(s[e + 1]);
|
|
100
100
|
}
|
|
101
101
|
function P(s, e) {
|
|
102
102
|
const o = s[e];
|
|
103
|
-
return /^\s*(`{3,}|~{3,})/.test(o) || /^#{1,6}\s/.test(o) || /^\s*>/.test(o) || /^\s*([-*+]|\d+[.)])\s+/.test(o) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(o) ||
|
|
103
|
+
return /^\s*(`{3,}|~{3,})/.test(o) || /^#{1,6}\s/.test(o) || /^\s*>/.test(o) || /^\s*([-*+]|\d+[.)])\s+/.test(o) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(o) || L(s, e);
|
|
104
104
|
}
|
|
105
105
|
const H = ["innerHTML"], D = {
|
|
106
106
|
key: 0,
|
|
107
107
|
class: "vue-llm-cursor",
|
|
108
108
|
"aria-hidden": "true"
|
|
109
|
-
}, U = /* @__PURE__ */
|
|
109
|
+
}, U = /* @__PURE__ */ j({
|
|
110
110
|
__name: "StreamMarkdown",
|
|
111
111
|
props: {
|
|
112
112
|
content: {},
|
|
@@ -114,36 +114,37 @@ const H = ["innerHTML"], D = {
|
|
|
114
114
|
render: { type: Function }
|
|
115
115
|
},
|
|
116
116
|
setup(s) {
|
|
117
|
-
const e = s, o =
|
|
118
|
-
return (t,
|
|
119
|
-
|
|
117
|
+
const e = s, o = B(() => (e.render ?? R)(e.content));
|
|
118
|
+
return (t, u) => (r(), i(g, null, [
|
|
119
|
+
x("div", {
|
|
120
120
|
class: "vue-llm-markdown",
|
|
121
121
|
innerHTML: o.value
|
|
122
122
|
}, null, 8, H),
|
|
123
|
-
s.streaming ? (
|
|
123
|
+
s.streaming ? (r(), i("span", D, "▊")) : M("", !0)
|
|
124
124
|
], 64));
|
|
125
125
|
}
|
|
126
|
-
}),
|
|
126
|
+
}), N = (s, e) => {
|
|
127
127
|
const o = s.__vccOpts || s;
|
|
128
|
-
for (const [t,
|
|
129
|
-
o[t] =
|
|
128
|
+
for (const [t, u] of e)
|
|
129
|
+
o[t] = u;
|
|
130
130
|
return o;
|
|
131
|
-
}, V = /* @__PURE__ */
|
|
131
|
+
}, V = /* @__PURE__ */ N(U, [["__scopeId", "data-v-f225ccf4"]]), A = ["data-role"], K = {
|
|
132
132
|
key: 0,
|
|
133
133
|
class: "vue-llm-text"
|
|
134
|
-
},
|
|
134
|
+
}, O = ["open"], z = ["src", "alt"], G = {
|
|
135
135
|
key: 1,
|
|
136
136
|
class: "vue-llm-file"
|
|
137
|
-
},
|
|
137
|
+
}, J = ["href"], Q = /* @__PURE__ */ j({
|
|
138
138
|
__name: "MessageParts",
|
|
139
139
|
props: {
|
|
140
140
|
message: {},
|
|
141
141
|
components: {},
|
|
142
|
+
dataComponents: {},
|
|
142
143
|
render: { type: Function }
|
|
143
144
|
},
|
|
144
145
|
emits: ["tool-result"],
|
|
145
146
|
setup(s, { emit: e }) {
|
|
146
|
-
const o = e, t = (l) => ({
|
|
147
|
+
const o = e, t = (l, m) => l.type === "tool-call" ? l.toolCallId : l.type === "data" && l.id !== void 0 ? `data:${l.name}:${l.id}` : m, u = (l) => ({
|
|
147
148
|
toolCallId: l.toolCallId,
|
|
148
149
|
toolName: l.toolName,
|
|
149
150
|
args: l.args,
|
|
@@ -152,57 +153,63 @@ const H = ["innerHTML"], D = {
|
|
|
152
153
|
error: l.error,
|
|
153
154
|
addResult: (m) => o("tool-result", { toolCallId: l.toolCallId, result: m })
|
|
154
155
|
});
|
|
155
|
-
return (l, m) => (
|
|
156
|
+
return (l, m) => (r(), i("div", {
|
|
156
157
|
class: "vue-llm-message",
|
|
157
158
|
"data-role": s.message.role
|
|
158
159
|
}, [
|
|
159
|
-
(
|
|
160
|
-
key: n
|
|
160
|
+
(r(!0), i(g, null, W(s.message.parts, (n, f) => (r(), i(g, {
|
|
161
|
+
key: t(n, f)
|
|
161
162
|
}, [
|
|
162
|
-
n.type === "text" ? (
|
|
163
|
-
s.message.role === "user" ? (
|
|
163
|
+
n.type === "text" ? (r(), i(g, { key: 0 }, [
|
|
164
|
+
s.message.role === "user" ? (r(), i("div", K, _(n.text), 1)) : (r(), w(V, {
|
|
164
165
|
key: 1,
|
|
165
166
|
content: n.text,
|
|
166
167
|
streaming: n.state === "streaming",
|
|
167
168
|
render: s.render
|
|
168
169
|
}, null, 8, ["content", "streaming", "render"]))
|
|
169
|
-
], 64)) : n.type === "reasoning" ? (
|
|
170
|
+
], 64)) : n.type === "reasoning" ? (r(), i("details", {
|
|
170
171
|
key: 1,
|
|
171
172
|
class: "vue-llm-reasoning",
|
|
172
173
|
open: n.state === "streaming"
|
|
173
174
|
}, [
|
|
174
|
-
m[0] || (m[0] =
|
|
175
|
-
|
|
176
|
-
], 8,
|
|
177
|
-
s.components?.[n.toolName] ? (
|
|
175
|
+
m[0] || (m[0] = x("summary", null, "Reasoning", -1)),
|
|
176
|
+
x("div", null, _(n.text), 1)
|
|
177
|
+
], 8, O)) : n.type === "tool-call" ? (r(), i(g, { key: 2 }, [
|
|
178
|
+
s.components?.[n.toolName] ? (r(), w(C(s.components[n.toolName]), q({
|
|
178
179
|
key: 0,
|
|
179
180
|
ref_for: !0
|
|
180
|
-
},
|
|
181
|
+
}, u(n)), null, 16)) : b(l.$slots, "tool", {
|
|
181
182
|
part: n,
|
|
182
|
-
addResult:
|
|
183
|
+
addResult: u(n).addResult
|
|
183
184
|
}, void 0, !0, 1)
|
|
184
|
-
], 64)) : n.type === "
|
|
185
|
-
n.
|
|
185
|
+
], 64)) : n.type === "data" ? (r(), i(g, { key: 3 }, [
|
|
186
|
+
s.dataComponents?.[n.name] ? (r(), w(C(s.dataComponents[n.name]), {
|
|
187
|
+
key: 0,
|
|
188
|
+
name: n.name,
|
|
189
|
+
data: n.data
|
|
190
|
+
}, null, 8, ["name", "data"])) : b(l.$slots, "data", { part: n }, void 0, !0, 1)
|
|
191
|
+
], 64)) : n.type === "file" ? (r(), i(g, { key: 4 }, [
|
|
192
|
+
n.mediaType.startsWith("image/") ? (r(), i("img", {
|
|
186
193
|
key: 0,
|
|
187
194
|
class: "vue-llm-file",
|
|
188
195
|
src: n.url,
|
|
189
196
|
alt: n.filename ?? ""
|
|
190
|
-
}, null, 8,
|
|
191
|
-
], 64)) : n.type === "source" && /^https?:/i.test(n.url) ? (
|
|
192
|
-
key:
|
|
197
|
+
}, null, 8, z)) : (r(), i("span", G, _(n.filename ?? n.mediaType), 1))
|
|
198
|
+
], 64)) : n.type === "source" && /^https?:/i.test(n.url) ? (r(), i("a", {
|
|
199
|
+
key: 5,
|
|
193
200
|
class: "vue-llm-source",
|
|
194
201
|
href: n.url,
|
|
195
202
|
target: "_blank",
|
|
196
203
|
rel: "noopener noreferrer"
|
|
197
|
-
}, _(n.title ?? n.url), 9,
|
|
204
|
+
}, _(n.title ?? n.url), 9, J)) : M("", !0)
|
|
198
205
|
], 64))), 128))
|
|
199
206
|
], 8, A));
|
|
200
207
|
}
|
|
201
|
-
}), Y = /* @__PURE__ */
|
|
208
|
+
}), Y = /* @__PURE__ */ N(Q, [["__scopeId", "data-v-3868ad67"]]);
|
|
202
209
|
export {
|
|
203
210
|
Y as MessageParts,
|
|
204
211
|
V as StreamMarkdown,
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
212
|
+
v as escapeHTML,
|
|
213
|
+
k as renderInline,
|
|
214
|
+
R as renderMarkdown
|
|
208
215
|
};
|
|
@@ -9,7 +9,11 @@ export type SendMessageInput = string | {
|
|
|
9
9
|
files?: FileInput;
|
|
10
10
|
};
|
|
11
11
|
export interface UseChatOptions {
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Chat id, also the `storage` key. Pass a ref or getter to switch chats: the running
|
|
14
|
+
* request stops and the history of the new id loads (or the chat starts empty).
|
|
15
|
+
*/
|
|
16
|
+
id?: MaybeRefOrGetter<string | undefined>;
|
|
13
17
|
provider: LLMProvider;
|
|
14
18
|
model: MaybeRefOrGetter<string>;
|
|
15
19
|
system?: MaybeRefOrGetter<string | undefined>;
|
|
@@ -38,7 +42,8 @@ export interface UseChatReturn {
|
|
|
38
42
|
messages: Ref<UIMessage[]>;
|
|
39
43
|
status: Ref<ChatStatus>;
|
|
40
44
|
error: Ref<Error | undefined>;
|
|
41
|
-
id
|
|
45
|
+
/** The current chat id */
|
|
46
|
+
readonly id: string;
|
|
42
47
|
input: Ref<string>;
|
|
43
48
|
sendMessage: (message?: SendMessageInput) => Promise<void>;
|
|
44
49
|
regenerate: () => Promise<void>;
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("vue"),B=require("./file-DusIs8wR.cjs"),J=require("./devtools-C4JE26vO.cjs"),$=require("./errors-CVDNhYqZ.cjs");function D(t){return typeof t=="function"?t():v.unref(t)}function W(t){const r=t.trim();if(!r)return;try{return JSON.parse(r)}catch{}const e=[],o=[];let a=!1,s=!1;for(let n=0;n<r.length;n++){const l=r[n];if(a){s?s=!1:l==="\\"?s=!0:l==='"'&&(a=!1,o.push({at:n+1,closers:e.join("")}));continue}l==='"'?a=!0:l==="{"||l==="["?(e.unshift(l==="{"?"}":"]"),o.push({at:n+1,closers:e.join("")})):l==="}"||l==="]"?(e.shift(),o.push({at:n+1,closers:e.join("")})):l===","&&o.push({at:n,closers:e.join("")})}if(a){const n=s?r.slice(0,-1):r,l=H(n.replace(/\\u[0-9a-fA-F]{0,3}$/,"")+'"'+e.join(""));if(l!==void 0)return l}else{const n=H(r.replace(/[\s,]+$/,"")+e.join(""));if(n!==void 0)return n}for(let n=o.length-1;n>=0;n--){const l=o[n],u=H(r.slice(0,l.at).replace(/[\s,]+$/,"")+l.closers);if(u!==void 0)return u}}function H(t){try{return JSON.parse(t)}catch{return}}class ee{constructor(r,e,o){this.messages=r,this.status=e,this.generateId=o}messages;status;generateId;async processStream(r,e,o){e.aborted||(this.status.value="streaming");const a=this.getOrCreateAssistantMessage(),s=new Map,n=[];let l="stop",u;const p=r.getReader();try{for(;!e.aborted;){const{done:d,value:i}=await p.read();if(d)break;if(this.applyChunk(a,i,s),i.type==="tool-call-end"){const C=s.get(i.toolCallId)??"{}";let b;try{b=JSON.parse(C)}catch{b=C}const E={toolCallId:i.toolCallId,toolName:this.getToolName(a,i.toolCallId),args:b};n.push(E);const m=this.findToolCallPart(a,i.toolCallId);if(m&&(m.args=b,m.state="pending"),o.onToolCall&&(o.canHandleTool?.(E.toolName)??!0)){m&&(m.state="running"),this.triggerReactivity();try{const S=await o.onToolCall(E,{signal:e});m&&(S===void 0?m.state="pending":(m.state="result",m.result=S),this.triggerReactivity())}catch(S){m&&(m.state="error",m.error=S instanceof Error?S.message:String(S),this.triggerReactivity())}}}if(i.type==="tool-result"){const C=this.findToolCallPart(a,i.toolCallId);C&&(C.state=i.error!==void 0?"error":"result",C.result=i.result,C.error=i.error);const b=n.findIndex(E=>E.toolCallId===i.toolCallId);b!==-1&&n.splice(b,1)}if(i.type==="finish"&&(l=i.finishReason,u=i.usage),i.type==="error")throw i.error;this.triggerReactivity()}}catch(d){if(!e.aborted){const i=d instanceof Error?d:new Error(String(d));throw o.onError?.(i),i}}finally{p.releaseLock()}return this.finalizeTextParts(a),this.triggerReactivity(),o.onFinish?.(a,{finishReason:l,usage:u}),{finishReason:l,usage:u,toolCalls:n}}getOrCreateAssistantMessage(){const r=this.messages.value,e=r[r.length-1];if(e?.role==="assistant")return e;const o={id:this.generateId(),role:"assistant",parts:[],createdAt:new Date};return r.push(o),r[r.length-1]}applyChunk(r,e,o){switch(e.type){case"text-delta":{const a=r.parts[r.parts.length-1];a?.type==="text"&&a.state==="streaming"?a.text+=e.text:r.parts.push({type:"text",text:e.text,state:"streaming"});break}case"reasoning-delta":{const a=r.parts[r.parts.length-1];a?.type==="reasoning"&&a.state==="streaming"?a.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:"streaming"}),o.set(e.toolCallId,"");break;case"tool-call-delta":{const a=(o.get(e.toolCallId)??"")+e.args;o.set(e.toolCallId,a);const s=this.findToolCallPart(r,e.toolCallId),n=W(a);s&&n!==void 0&&(s.args=n);break}case"data":{const a=e.id===void 0?void 0:r.parts.find(s=>s.type==="data"&&s.name===e.name&&s.id===e.id);if(a)a.data=e.data;else{const s={type:"data",name:e.name,data:e.data};e.id!==void 0&&(s.id=e.id),r.parts.push(s)}break}case"message-start":r.id=e.id;break;case"message-metadata":r.metadata={...r.metadata,...e.metadata};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(o=>o.type==="tool-call"&&o.toolCallId===e)}getToolName(r,e){return this.findToolCallPart(r,e)?.toolName??""}triggerReactivity(){this.messages.value=[...this.messages.value]}}const U="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function N(t=16){const r=crypto.getRandomValues(new Uint8Array(t));let e="";for(let o=0;o<t;o++)e+=U[r[o]%U.length];return e}function te(t){const r=N(),e=()=>D(t.id)??r,o=e(),a=v.ref(t.initialMessages??[]),s=v.ref("ready"),n=v.ref(void 0),l=v.ref("");let u=null;const p=v.ref(!t.storage),d=t.storage,i=c=>{t.onError?.(c instanceof Error?c:new Error(String(c)))};let C=0;const b=c=>{if(!d)return;const h=++C,y=a.value;p.value=!1;const w=x=>{h===C&&(x?.length&&a.value===y&&(a.value=x),p.value=!0)},M=x=>{h===C&&(i(x),p.value=!0)};try{const x=d.load(c);x instanceof Promise?x.then(w,M):w(x)}catch(x){M(x)}};d&&(b(e()),v.watch([a,s,p],()=>{if(!(!p.value||s.value==="submitted"||s.value==="streaming"))try{const c=a.value.length>0?d.save(e(),a.value):d.remove(e());c instanceof Promise&&c.catch(i)}catch(c){i(c)}},{deep:!0}));const E=new ee(a,s,N),m=()=>{const c=[],h=[D(t.system),...a.value.filter(y=>y.role==="system").map(y=>y.parts.filter(w=>w.type==="text").map(w=>w.text).join(""))].filter(Boolean);h.length>0&&c.push({role:"system",content:h.join(`
|
|
2
2
|
|
|
3
|
-
`)});for(const
|
|
3
|
+
`)});for(const y of a.value){if(y.role==="system")continue;const M=y.parts.filter(T=>T.type==="text").map(T=>T.text).join(""),x=y.parts.filter(T=>T.type==="tool-call").map(T=>({id:T.toolCallId,name:T.toolName,args:T.args}));if(y.role==="user"){const T=y.parts.filter(j=>j.type==="file");if(T.length===0){c.push({role:"user",content:M});continue}const L=T.map(j=>({type:"file",url:j.url,mediaType:j.mediaType,filename:j.filename}));M&&L.push({type:"text",text:M}),c.push({role:"user",content:L})}else if(y.role==="assistant"){c.push({role:"assistant",content:M,toolCalls:x.length>0?x:void 0});for(const T of y.parts)T.type==="tool-call"&&c.push({role:"tool",content:T.state==="result"?JSON.stringify(T.result??null):JSON.stringify({error:T.error??"The tool call was not answered"}),toolCallId:T.toolCallId})}}return c},S=t.tools?.map(({name:c,description:h,parameters:y})=>({name:c,description:h,parameters:y})),f=(c,{signal:h})=>{const y=t.tools?.find(w=>w.name===c.toolName);return y?.execute?y.execute(c.args,{toolCallId:c.toolCallId,signal:h}):t.onToolCall?.(c)},g=()=>{const c=a.value[a.value.length-1];return c?.role==="assistant"&&c.parts.some(h=>h.type==="tool-call"&&h.state!=="result"&&h.state!=="error")},P=async(c,h)=>{const y=t.maxToolRoundtrips??5;let w=0;for(;w<y;){const M=m();t.provider.validateConfig();const{stream:x}=await J.tracedChat(t.provider,{model:D(t.model),messages:M,tools:S,signal:c,providerOptions:{...t.providerOptions,...D(t.body)},...w===0?h:{trigger:"continue"}},o),T=await E.processStream(x,c,{onFinish:t.onFinish,onError:t.onError,onToolCall:f,canHandleTool:L=>!!t.onToolCall||!!t.tools?.find(j=>j.name===L)?.execute});if(T.finishReason!=="tool-calls"||T.toolCalls.length===0||g())break;w++}},I=async c=>{const h=typeof c=="string"?c:c?.text??l.value;let y;try{y=typeof c=="object"?await B.convertFilesToParts(c.files):[]}catch(x){n.value=x instanceof Error?x:new Error(String(x)),s.value="error";return}if(!h.trim()&&y.length===0)return;(typeof c!="object"||c===null||!("text"in c))&&(l.value="");const w=[...y];h.trim()&&w.push({type:"text",text:h,state:"done"});const M={id:N(),role:"user",parts:w,createdAt:new Date};a.value=[...a.value,M],await A({trigger:"submit",messageId:M.id})},A=async c=>{n.value=void 0,s.value="submitted",u?.abort();const h=new AbortController;u=h;const y=()=>u===h||u===null;try{await P(h.signal,c),y()&&(s.value="ready")}catch(w){if(h.signal.aborted){y()&&(s.value="ready");return}n.value=w instanceof Error?w:new Error(String(w)),s.value="error"}},F=async()=>{const c=a.value,h=c.reduce((w,M,x)=>M.role==="assistant"?x:w,-1);if(h===-1)return;const y=c[h].id;a.value=c.slice(0,h),await A({trigger:"regenerate",messageId:y})},R=()=>{u?.abort(),u=null,s.value="ready"},O=c=>{a.value=typeof c=="function"?c(a.value):c},z=c=>{c?.preventDefault?.(),l.value.trim()&&I()},q=v.computed(()=>s.value==="submitted"||s.value==="streaming"),G=async({toolCallId:c,result:h,error:y})=>{const w=a.value.flatMap(L=>L.parts).find(L=>L.type==="tool-call"&&L.toolCallId===c);if(!w)return;y!==void 0?(w.state="error",w.error=y):(w.state="result",w.result=h),a.value=[...a.value];const M=a.value[a.value.length-1],x=M?.role==="assistant"&&M.parts.includes(w),T=s.value==="submitted"||s.value==="streaming";(t.autoSendToolResults??!0)&&x&&!T&&!g()&&await A({trigger:"continue"})},Q=()=>{n.value=void 0,s.value==="error"&&(s.value="ready")};v.watch(e,(c,h)=>{c!==h&&(R(),n.value=void 0,a.value=[],b(c))});const X=J.registerDevtoolsSession({id:o,kind:"chat",providerId:t.provider.id,getModel:()=>D(t.model),status:s,error:n,messages:a,stop:R,clear:()=>O([])});return v.getCurrentScope()&&v.onScopeDispose(()=>{u?.abort(),X()}),{messages:a,status:v.computed(()=>s.value),error:n,get id(){return e()},input:l,sendMessage:I,regenerate:F,stop:R,setMessages:O,handleSubmit:z,isLoading:q,addToolResult:G,clearError:Q,isRestored:v.computed(()=>p.value)}}function re(t){const r=t.id??N(),e=v.ref(""),o=v.ref("ready"),a=v.ref(void 0),s=v.ref("");let n=null;const l=async b=>{const E=b??s.value;if(!E.trim())return e.value;b||(s.value=""),e.value="",a.value=void 0,o.value="submitted",n?.abort();const m=new AbortController;n=m;try{t.provider.validateConfig();const S=D(t.system),f=S?[{role:"system",content:S},{role:"user",content:E}]:[{role:"user",content:E}],{stream:g}=await J.tracedChat(t.provider,{model:D(t.model),messages:f,signal:m.signal},r);if(m.signal.aborted)return e.value;o.value="streaming";const P=g.getReader();let I="stop",A;for(;!m.signal.aborted;){const{done:F,value:R}=await P.read();if(m.signal.aborted||F)break;if(R.type==="text-delta")e.value+=R.text;else if(R.type==="finish")I=R.finishReason,A=R.usage;else if(R.type==="error")throw R.error}return P.releaseLock(),m.signal.aborted||(o.value="ready",t.onFinish?.(e.value,{finishReason:I,usage:A})),e.value}catch(S){if(m.signal.aborted)return e.value;const f=S instanceof Error?S:new Error(String(S));return a.value=f,o.value="error",t.onError?.(f),e.value}finally{n===m&&(n=null)}},u=()=>{n?.abort(),n=null,o.value="ready"},p=()=>{a.value=void 0,o.value==="error"&&(o.value="ready")},d=b=>{b?.preventDefault?.(),s.value.trim()&&l()},i=v.computed(()=>o.value==="submitted"||o.value==="streaming"),C=J.registerDevtoolsSession({id:r,kind:"completion",providerId:t.provider.id,getModel:()=>D(t.model),status:o,error:a,output:e,stop:u});return v.getCurrentScope()&&v.onScopeDispose(()=>{n?.abort(),C()}),{completion:e,status:v.computed(()=>o.value),error:a,isLoading:i,id:r,input:s,complete:l,stop:u,clearError:p,handleSubmit:d}}function ae(t){const r=t.id??N(),e=v.ref(void 0),o=v.ref(void 0),a=v.ref("ready"),s=v.ref(void 0),n=v.ref("");let l=null;const u=async b=>{const E=b??n.value;if(!E.trim())return e.value;b||(n.value=""),e.value=void 0,o.value=void 0,s.value=void 0,a.value="submitted",l?.abort();const m=new AbortController;l=m;try{t.provider.validateConfig();const S=[D(t.system)??"","Respond with valid JSON matching this schema:",JSON.stringify(t.schema,null,2),"Output ONLY the JSON object, no other text."].filter(Boolean).join(`
|
|
4
4
|
|
|
5
|
-
`),{stream:
|
|
5
|
+
`),{stream:f}=await J.tracedChat(t.provider,{model:D(t.model),messages:[{role:"system",content:S},{role:"user",content:E}],signal:m.signal,providerOptions:{response_format:{type:"json_object"}}},r);if(m.signal.aborted)return e.value;a.value="streaming";const g=f.getReader();let P="",I="stop",A;for(;!m.signal.aborted;){const{done:F,value:R}=await g.read();if(m.signal.aborted||F)break;if(R.type==="text-delta"){P+=R.text;const O=W(P);O!==null&&typeof O=="object"&&(o.value=O)}else if(R.type==="finish")I=R.finishReason,A=R.usage;else if(R.type==="error")throw R.error}if(g.releaseLock(),m.signal.aborted)return e.value;try{e.value=JSON.parse(P),o.value=e.value}catch{throw new Error(`Failed to parse JSON response: ${P.slice(0,200)}`)}return a.value="ready",t.onFinish?.(e.value,{finishReason:I,usage:A}),e.value}catch(S){if(m.signal.aborted)return e.value;const f=S instanceof Error?S:new Error(String(S));s.value=f,a.value="error",t.onError?.(f);return}finally{l===m&&(l=null)}},p=()=>{l?.abort(),l=null,a.value="ready"},d=()=>{s.value=void 0,a.value==="error"&&(a.value="ready")},i=v.computed(()=>a.value==="submitted"||a.value==="streaming"),C=J.registerDevtoolsSession({id:r,kind:"object",providerId:t.provider.id,getModel:()=>D(t.model),status:a,error:s,output:o,stop:p});return v.getCurrentScope()&&v.onScopeDispose(()=>{l?.abort(),C()}),{object:e,partialObject:o,status:v.computed(()=>a.value),error:s,isLoading:i,id:r,input:n,submit:u,stop:p,clearError:d}}const V=/(\\)?\{\{\s*([A-Za-z_][\w-]*)\s*\}\}/g;function _(t,r={}){return{template:t,variables:K(t),render(e){return k(t,{...r.defaults,...e})}}}function oe(t,r={}){const e=o=>{const a={...r.defaults,...o};return t.map(s=>({role:s.role,content:k(s.content,a)}))};return{messages:t,variables:[...new Set(t.flatMap(o=>K(o.content)))],render:e,toUIMessages(o){return e(o).map(a=>({id:N(),role:a.role,parts:[{type:"text",text:a.content,state:"done"}],createdAt:new Date}))}}}function k(t,r){return t.replace(V,(e,o,a)=>{if(o)return e.slice(1);const s=r[a];if(s==null)throw new Error(`[vue-llm] Missing prompt variable "${a}"`);return String(s)})}function K(t){const r=new Set;for(const[,e,o]of t.matchAll(V))e||r.add(o);return[...r]}function se(t,r){const e=typeof t=="string"?_(t):t;return v.computed(()=>e.render(D(r)))}function ne(t,r={}){const e=v.ref(null),o=v.ref([]),a=v.ref(!1);let s=0;const n=v.computed(()=>t.status.value==="submitted"||t.status.value==="streaming"),l=v.computed(()=>!n.value&&(t.input.value.trim()!==""||o.value.length>0)),u=f=>r.accept?r.accept.split(",").map(g=>g.trim().toLowerCase()).filter(Boolean).some(g=>g.startsWith(".")?f.name.toLowerCase().endsWith(g):g.endsWith("/*")?f.type.toLowerCase().startsWith(g.slice(0,-1)):f.type.toLowerCase()===g):!0,p=f=>{const g=Array.from(f??[]);if(!g.length)return;const P=g.filter(A=>!u(A));P.length&&r.onReject?.(P,"type");let I=g.filter(u);if(r.maxFiles!==void 0){const A=Math.max(0,r.maxFiles-o.value.length);I.length>A&&r.onReject?.(I.slice(A),"count"),I=I.slice(0,A)}I.length&&(o.value=[...o.value,...I])},d=f=>{o.value=o.value.filter(g=>g!==f)},i=()=>{const f=e.value;if(!f||typeof getComputedStyle>"u")return;const g=getComputedStyle(f),P=parseFloat(g.lineHeight)||parseFloat(g.fontSize)*1.5||20,I=(parseFloat(g.paddingTop)||0)+(parseFloat(g.paddingBottom)||0),A=(parseFloat(g.borderTopWidth)||0)+(parseFloat(g.borderBottomWidth)||0),F=g.boxSizing==="border-box",R=q=>F?q+A:q-I,O=P*(r.maxRows??8)+I;f.style.height="auto";const z=f.scrollHeight>O;f.style.height=`${R(Math.min(f.scrollHeight,O))}px`,f.style.overflowY=z?"auto":"hidden"};v.watch(t.input,()=>v.nextTick(i)),v.watch(e,()=>v.nextTick(i));const C=async()=>{if(!l.value)return;const f=t.input.value,g=o.value;t.input.value="",o.value=[],await t.sendMessage(g.length?{text:f,files:g}:f)},b=f=>{f.key!=="Enter"||f.shiftKey||r.submitOnEnter===!1||f.isComposing||f.keyCode===229||(f.preventDefault(),C())},E=f=>{const g=Array.from(f.clipboardData?.files??[]);g.length&&(f.preventDefault(),p(g))},m=f=>Array.from(f.dataTransfer?.types??[]).includes("Files");return{textarea:e,files:o,isDragging:a,canSubmit:l,submit:C,addFiles:p,removeFile:d,handlers:{onKeydown:b,onPaste:E},dropzone:{onDragenter(f){m(f)&&(f.preventDefault(),s++,a.value=!0)},onDragover(f){m(f)&&f.preventDefault()},onDragleave(f){m(f)&&(s=Math.max(0,s-1),s===0&&(a.value=!1))},onDrop(f){m(f)&&(f.preventDefault(),s=0,a.value=!1,p(f.dataTransfer?.files))}},resize:i}}function le(t={}){const r=v.ref(null),e=v.ref(!0),o=t.threshold??48;let a=!1;const s=d=>d.scrollHeight-d.scrollTop-d.clientHeight,n=(d="auto")=>{const i=r.value;i&&(a=!0,e.value=!0,typeof i.scrollTo=="function"?i.scrollTo({top:i.scrollHeight,behavior:d}):i.scrollTop=i.scrollHeight,ie(()=>{a=!1}))},l=()=>{const d=r.value;!d||a||(e.value=s(d)<=o)},u=()=>{e.value&&n()};let p=()=>{};return v.watch(r,d=>{if(p(),!d)return;d.addEventListener("scroll",l,{passive:!0});const i=typeof MutationObserver<"u"?new MutationObserver(u):void 0;i?.observe(d,{childList:!0,subtree:!0,characterData:!0});const C=typeof ResizeObserver<"u"?new ResizeObserver(u):void 0;C?.observe(d),d.firstElementChild&&C?.observe(d.firstElementChild),n(),p=()=>{d.removeEventListener("scroll",l),i?.disconnect(),C?.disconnect(),p=()=>{}}},{flush:"post"}),v.getCurrentScope()&&v.onScopeDispose(()=>p()),{container:r,isAtBottom:e,scrollToBottom:n}}function ie(t){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>requestAnimationFrame(t)):setTimeout(t,32)}function ce(t,r){return r.length?{id:t.id,supportsStreaming:t.supportsStreaming,validateConfig(){t.validateConfig()},async chat(e){let o=e;for(const u of r)u.beforeRequest&&(o=await u.beforeRequest(o,t));const a=r.reduceRight((u,p)=>p.wrapChat?d=>p.wrapChat(u,d):u,u=>t.chat(u));let s;try{s=await a(o)}catch(u){let p=u instanceof Error?u:new Error(String(u));for(const d of r)if(d.onError){const i=await d.onError(p,o);i instanceof Error&&(p=i)}throw p}const l=r.some(u=>u.afterStream)?s.stream.pipeThrough(new TransformStream({async transform(u,p){let d=u;for(const i of r){if(!d)break;i.afterStream&&(d=await i.afterStream(d,o))}d&&p.enqueue(d)}})):s.stream;for(const u of r)u.onFinish&&u.onFinish(o,s);return{stream:l,response:s.response}}}:t}function ue(t="vue-llm"){return{beforeRequest(r){return console.log(`[${t}] → ${r.model}`,r.messages.length,"messages"),r},afterStream(r){return r.type==="finish"&&console.log(`[${t}] ← finish:`,r.finishReason,r.usage??""),r},onError(r){console.error(`[${t}] error:`,r.message)}}}function de(t={},r){const e=typeof t=="number"?{maxRetries:t,initialDelay:r}:t,o=e.maxRetries??3,a=e.initialDelay??1e3,s=e.maxDelay??3e4,n=e.factor??2,l=e.jitter??!0,u=e.shouldRetry??Y;return{async wrapChat(p,d){for(let i=1;;i++)try{return await p(d)}catch(C){const b=C instanceof Error?C:new Error(String(C));if(i>o||d.signal?.aborted||!u(b,i))throw b;const E=a*n**(i-1),m=b instanceof $.LLMAPIError?b.retryAfter:void 0,S=Math.min(s,m??(l?E*(.5+Math.random()*.5):E));e.onRetry?.({error:b,attempt:i,delay:S}),await pe(S,d.signal)}}}}function Y(t){return t.name==="AbortError"?!1:t instanceof $.LLMAPIError?t.isRetryable:t instanceof TypeError}function fe(t){const r=t.interval??6e4,e=[];let o=0;const a=new Set,s=()=>{o--;for(const l of[...a])l()},n=async l=>{for(;;){l?.throwIfAborted();const u=Date.now();for(;e.length>0&&e[0]<=u-r;)e.shift();const p=t.maxRequests!==void 0&&e.length>=t.maxRequests,d=t.maxConcurrent!==void 0&&o>=t.maxConcurrent;if(!p&&!d){e.push(u),o++;return}await new Promise((i,C)=>{const b=()=>{clearTimeout(m),a.delete(b),l?.removeEventListener("abort",E),i()},E=()=>{b(),C(l.reason)},m=p?setTimeout(b,e[0]+r-u):void 0;a.add(b),l?.addEventListener("abort",E,{once:!0})})}};return{async wrapChat(l,u){await n(u.signal);let p;try{p=await l(u)}catch(d){throw s(),d}return{...p,stream:ve(p.stream,s)}}}}function ve(t,r){const e=t.getReader();let o=!1;const a=()=>{o||(o=!0,r())};return new ReadableStream({async pull(s){try{const{done:n,value:l}=await e.read();n?(a(),s.close()):s.enqueue(l)}catch(n){a(),s.error(n)}},cancel(s){return a(),e.cancel(s)}})}function pe(t,r){return new Promise((e,o)=>{if(r?.aborted)return o(r.reason);const a=setTimeout(()=>{r?.removeEventListener("abort",s),e()},t),s=()=>{clearTimeout(a),o(r.reason)};r?.addEventListener("abort",s,{once:!0})})}function me(t){return{beforeRequest(r){return{...r,providerOptions:{...r.providerOptions,headers:{...r.providerOptions?.headers,...t}}}}}}function ge(t){return t}function he(t={}){const r=t.prefix??"vue-llm:chat:",e=()=>t.storage?t.storage:typeof localStorage<"u"?localStorage:void 0;return{load(o){const a=e()?.getItem(r+o);if(!a)return null;try{return Z(a)}catch{return null}},save(o,a){e()?.setItem(r+o,JSON.stringify(a))},remove(o){e()?.removeItem(r+o)}}}function ye(){const t=new Map;return{load(r){const e=t.get(r);return e?Z(e):null},save(r,e){t.set(r,JSON.stringify(e))},remove(r){t.delete(r)}}}function Z(t){const r=JSON.parse(t);return Array.isArray(r)?r.map(e=>({...e,createdAt:e.createdAt?new Date(e.createdAt):void 0})):[]}exports.convertFilesToParts=B.convertFilesToParts;exports.fileToDataURL=B.fileToDataURL;exports.LLMAPIError=$.LLMAPIError;exports.createChatPrompt=oe;exports.createMemoryStorage=ye;exports.createPrompt=_;exports.createWebStorage=he;exports.defineTool=ge;exports.headerMiddleware=me;exports.isRetryableError=Y;exports.loggingMiddleware=ue;exports.parsePartialJSON=W;exports.rateLimitMiddleware=fe;exports.renderTemplate=k;exports.retryMiddleware=de;exports.useAutoScroll=le;exports.useChat=te;exports.useCompletion=re;exports.useObject=ae;exports.usePrompt=se;exports.usePromptInput=ne;exports.wrapProvider=ce;
|
package/dist/index.d.ts
CHANGED
|
@@ -20,5 +20,5 @@ export { fileToDataURL, convertFilesToParts } from './utils/file.js';
|
|
|
20
20
|
export type { FileInput } from './utils/file.js';
|
|
21
21
|
export { createWebStorage, createMemoryStorage } from './core/storage.js';
|
|
22
22
|
export type { ChatStorage, WebStorageOptions } from './core/storage.js';
|
|
23
|
-
export type { UIMessage, UIMessagePart, TextPart, ReasoningPart, ToolCallPart, FilePart, SourcePart, ToolDefinition, ChatTool, ToolCallState, ToolExecutionContext, ToolComponentProps, DeepPartial, ChatStatus, FinishReason, Usage, } from './types.js';
|
|
24
|
-
export type { LLMProvider, ChatRequest, ChatMessage, ContentPart, ChatStreamResult, ChatStreamChunk, ChatResponse, } from './providers/types.js';
|
|
23
|
+
export type { UIMessage, UIMessagePart, TextPart, ReasoningPart, ToolCallPart, FilePart, SourcePart, ToolDefinition, ChatTool, ToolCallState, ToolExecutionContext, ToolComponentProps, DataComponentProps, DataPart, DeepPartial, ChatStatus, FinishReason, Usage, } from './types.js';
|
|
24
|
+
export type { LLMProvider, ChatRequest, ChatTrigger, ChatMessage, ContentPart, ChatStreamResult, ChatStreamChunk, ChatResponse, } from './providers/types.js';
|