vue-llm 1.7.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/index.cjs +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +76 -66
- package/dist/providers/types.d.ts +7 -0
- 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
|
};
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("vue"),
|
|
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 y of
|
|
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';
|
|
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
24
|
export type { LLMProvider, ChatRequest, ChatTrigger, ChatMessage, ContentPart, ChatStreamResult, ChatStreamChunk, ChatResponse, } from './providers/types.js';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { unref as ae, ref as E, watch as z, computed as F, getCurrentScope as
|
|
1
|
+
import { unref as ae, ref as E, watch as z, computed as F, getCurrentScope as B, onScopeDispose as q, nextTick as V } from "vue";
|
|
2
2
|
import { c as oe } from "./file-x_kW7BHa.js";
|
|
3
3
|
import { f as Fe } from "./file-x_kW7BHa.js";
|
|
4
|
-
import { r as
|
|
4
|
+
import { r as k, t as U } from "./devtools-DnDvylCG.js";
|
|
5
5
|
import { L as K } from "./errors-B3A_zmVE.js";
|
|
6
6
|
function P(t) {
|
|
7
7
|
return typeof t == "function" ? t() : ae(t);
|
|
@@ -24,18 +24,18 @@ function Y(t) {
|
|
|
24
24
|
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("") });
|
|
25
25
|
}
|
|
26
26
|
if (a) {
|
|
27
|
-
const n = s ? r.slice(0, -1) : r, l =
|
|
27
|
+
const n = s ? r.slice(0, -1) : r, l = W(n.replace(/\\u[0-9a-fA-F]{0,3}$/, "") + '"' + e.join(""));
|
|
28
28
|
if (l !== void 0) return l;
|
|
29
29
|
} else {
|
|
30
|
-
const n =
|
|
30
|
+
const n = W(r.replace(/[\s,]+$/, "") + e.join(""));
|
|
31
31
|
if (n !== void 0) return n;
|
|
32
32
|
}
|
|
33
33
|
for (let n = o.length - 1; n >= 0; n--) {
|
|
34
|
-
const l = o[n], c =
|
|
34
|
+
const l = o[n], c = W(r.slice(0, l.at).replace(/[\s,]+$/, "") + l.closers);
|
|
35
35
|
if (c !== void 0) return c;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
function
|
|
38
|
+
function W(t) {
|
|
39
39
|
try {
|
|
40
40
|
return JSON.parse(t);
|
|
41
41
|
} catch {
|
|
@@ -138,6 +138,16 @@ class se {
|
|
|
138
138
|
s && n !== void 0 && (s.args = n);
|
|
139
139
|
break;
|
|
140
140
|
}
|
|
141
|
+
case "data": {
|
|
142
|
+
const a = e.id === void 0 ? void 0 : r.parts.find((s) => s.type === "data" && s.name === e.name && s.id === e.id);
|
|
143
|
+
if (a)
|
|
144
|
+
a.data = e.data;
|
|
145
|
+
else {
|
|
146
|
+
const s = { type: "data", name: e.name, data: e.data };
|
|
147
|
+
e.id !== void 0 && (s.id = e.id), r.parts.push(s);
|
|
148
|
+
}
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
141
151
|
case "message-start":
|
|
142
152
|
r.id = e.id;
|
|
143
153
|
break;
|
|
@@ -168,7 +178,7 @@ function J(t = 16) {
|
|
|
168
178
|
e += _[r[o] % _.length];
|
|
169
179
|
return e;
|
|
170
180
|
}
|
|
171
|
-
function
|
|
181
|
+
function pe(t) {
|
|
172
182
|
const r = J(), e = () => P(t.id) ?? r, o = e(), a = E(t.initialMessages ?? []), s = E("ready"), n = E(void 0), l = E("");
|
|
173
183
|
let c = null;
|
|
174
184
|
const v = E(!t.storage), f = t.storage, i = (u) => {
|
|
@@ -177,12 +187,12 @@ function ge(t) {
|
|
|
177
187
|
let w = 0;
|
|
178
188
|
const y = (u) => {
|
|
179
189
|
if (!f) return;
|
|
180
|
-
const
|
|
190
|
+
const g = ++w, h = a.value;
|
|
181
191
|
v.value = !1;
|
|
182
192
|
const b = (x) => {
|
|
183
|
-
|
|
193
|
+
g === w && (x?.length && a.value === h && (a.value = x), v.value = !0);
|
|
184
194
|
}, M = (x) => {
|
|
185
|
-
|
|
195
|
+
g === w && (i(x), v.value = !0);
|
|
186
196
|
};
|
|
187
197
|
try {
|
|
188
198
|
const x = f.load(u);
|
|
@@ -201,11 +211,11 @@ function ge(t) {
|
|
|
201
211
|
}
|
|
202
212
|
}, { deep: !0 }));
|
|
203
213
|
const T = new se(a, s, J), m = () => {
|
|
204
|
-
const u = [],
|
|
214
|
+
const u = [], g = [
|
|
205
215
|
P(t.system),
|
|
206
216
|
...a.value.filter((h) => h.role === "system").map((h) => h.parts.filter((b) => b.type === "text").map((b) => b.text).join(""))
|
|
207
217
|
].filter(Boolean);
|
|
208
|
-
|
|
218
|
+
g.length > 0 && u.push({ role: "system", content: g.join(`
|
|
209
219
|
|
|
210
220
|
`) });
|
|
211
221
|
for (const h of a.value) {
|
|
@@ -239,15 +249,15 @@ function ge(t) {
|
|
|
239
249
|
}
|
|
240
250
|
}
|
|
241
251
|
return u;
|
|
242
|
-
}, C = t.tools?.map(({ name: u, description:
|
|
252
|
+
}, C = t.tools?.map(({ name: u, description: g, parameters: h }) => ({ name: u, description: g, parameters: h })), d = (u, { signal: g }) => {
|
|
243
253
|
const h = t.tools?.find((b) => b.name === u.toolName);
|
|
244
|
-
return h?.execute ? h.execute(u.args, { toolCallId: u.toolCallId, signal:
|
|
245
|
-
},
|
|
254
|
+
return h?.execute ? h.execute(u.args, { toolCallId: u.toolCallId, signal: g }) : t.onToolCall?.(u);
|
|
255
|
+
}, p = () => {
|
|
246
256
|
const u = a.value[a.value.length - 1];
|
|
247
257
|
return u?.role === "assistant" && u.parts.some(
|
|
248
|
-
(
|
|
258
|
+
(g) => g.type === "tool-call" && g.state !== "result" && g.state !== "error"
|
|
249
259
|
);
|
|
250
|
-
}, O = async (u,
|
|
260
|
+
}, O = async (u, g) => {
|
|
251
261
|
const h = t.maxToolRoundtrips ?? 5;
|
|
252
262
|
let b = 0;
|
|
253
263
|
for (; b < h; ) {
|
|
@@ -263,19 +273,19 @@ function ge(t) {
|
|
|
263
273
|
...P(t.body)
|
|
264
274
|
},
|
|
265
275
|
// Later roundtrips of the same run send tool results back
|
|
266
|
-
...b === 0 ?
|
|
276
|
+
...b === 0 ? g : { trigger: "continue" }
|
|
267
277
|
}, o), S = await T.processStream(x, u, {
|
|
268
278
|
onFinish: t.onFinish,
|
|
269
279
|
onError: t.onError,
|
|
270
280
|
onToolCall: d,
|
|
271
281
|
canHandleTool: (L) => !!t.onToolCall || !!t.tools?.find((j) => j.name === L)?.execute
|
|
272
282
|
});
|
|
273
|
-
if (S.finishReason !== "tool-calls" || S.toolCalls.length === 0 ||
|
|
283
|
+
if (S.finishReason !== "tool-calls" || S.toolCalls.length === 0 || p())
|
|
274
284
|
break;
|
|
275
285
|
b++;
|
|
276
286
|
}
|
|
277
287
|
}, I = async (u) => {
|
|
278
|
-
const
|
|
288
|
+
const g = typeof u == "string" ? u : u?.text ?? l.value;
|
|
279
289
|
let h;
|
|
280
290
|
try {
|
|
281
291
|
h = typeof u == "object" ? await oe(u.files) : [];
|
|
@@ -283,10 +293,10 @@ function ge(t) {
|
|
|
283
293
|
n.value = x instanceof Error ? x : new Error(String(x)), s.value = "error";
|
|
284
294
|
return;
|
|
285
295
|
}
|
|
286
|
-
if (!
|
|
296
|
+
if (!g.trim() && h.length === 0) return;
|
|
287
297
|
(typeof u != "object" || u === null || !("text" in u)) && (l.value = "");
|
|
288
298
|
const b = [...h];
|
|
289
|
-
|
|
299
|
+
g.trim() && b.push({ type: "text", text: g, state: "done" });
|
|
290
300
|
const M = {
|
|
291
301
|
id: J(),
|
|
292
302
|
role: "user",
|
|
@@ -296,42 +306,42 @@ function ge(t) {
|
|
|
296
306
|
a.value = [...a.value, M], await A({ trigger: "submit", messageId: M.id });
|
|
297
307
|
}, A = async (u) => {
|
|
298
308
|
n.value = void 0, s.value = "submitted", c?.abort();
|
|
299
|
-
const
|
|
300
|
-
c =
|
|
301
|
-
const h = () => c ===
|
|
309
|
+
const g = new AbortController();
|
|
310
|
+
c = g;
|
|
311
|
+
const h = () => c === g || c === null;
|
|
302
312
|
try {
|
|
303
|
-
await O(
|
|
313
|
+
await O(g.signal, u), h() && (s.value = "ready");
|
|
304
314
|
} catch (b) {
|
|
305
|
-
if (
|
|
315
|
+
if (g.signal.aborted) {
|
|
306
316
|
h() && (s.value = "ready");
|
|
307
317
|
return;
|
|
308
318
|
}
|
|
309
319
|
n.value = b instanceof Error ? b : new Error(String(b)), s.value = "error";
|
|
310
320
|
}
|
|
311
321
|
}, N = async () => {
|
|
312
|
-
const u = a.value,
|
|
313
|
-
if (
|
|
314
|
-
const h = u[
|
|
315
|
-
a.value = u.slice(0,
|
|
322
|
+
const u = a.value, g = u.reduce((b, M, x) => M.role === "assistant" ? x : b, -1);
|
|
323
|
+
if (g === -1) return;
|
|
324
|
+
const h = u[g].id;
|
|
325
|
+
a.value = u.slice(0, g), await A({ trigger: "regenerate", messageId: h });
|
|
316
326
|
}, R = () => {
|
|
317
327
|
c?.abort(), c = null, s.value = "ready";
|
|
318
328
|
}, D = (u) => {
|
|
319
329
|
a.value = typeof u == "function" ? u(a.value) : u;
|
|
320
|
-
},
|
|
330
|
+
}, $ = (u) => {
|
|
321
331
|
u?.preventDefault?.(), l.value.trim() && I();
|
|
322
|
-
}, H = F(() => s.value === "submitted" || s.value === "streaming"), ee = async ({ toolCallId: u, result:
|
|
332
|
+
}, H = F(() => s.value === "submitted" || s.value === "streaming"), ee = async ({ toolCallId: u, result: g, error: h }) => {
|
|
323
333
|
const b = a.value.flatMap((L) => L.parts).find((L) => L.type === "tool-call" && L.toolCallId === u);
|
|
324
334
|
if (!b) return;
|
|
325
|
-
h !== void 0 ? (b.state = "error", b.error = h) : (b.state = "result", b.result =
|
|
335
|
+
h !== void 0 ? (b.state = "error", b.error = h) : (b.state = "result", b.result = g), a.value = [...a.value];
|
|
326
336
|
const M = a.value[a.value.length - 1], x = M?.role === "assistant" && M.parts.includes(b), S = s.value === "submitted" || s.value === "streaming";
|
|
327
|
-
(t.autoSendToolResults ?? !0) && x && !S && !
|
|
337
|
+
(t.autoSendToolResults ?? !0) && x && !S && !p() && await A({ trigger: "continue" });
|
|
328
338
|
}, te = () => {
|
|
329
339
|
n.value = void 0, s.value === "error" && (s.value = "ready");
|
|
330
340
|
};
|
|
331
|
-
z(e, (u,
|
|
332
|
-
u !==
|
|
341
|
+
z(e, (u, g) => {
|
|
342
|
+
u !== g && (R(), n.value = void 0, a.value = [], y(u));
|
|
333
343
|
});
|
|
334
|
-
const re =
|
|
344
|
+
const re = k({
|
|
335
345
|
id: o,
|
|
336
346
|
kind: "chat",
|
|
337
347
|
providerId: t.provider.id,
|
|
@@ -342,7 +352,7 @@ function ge(t) {
|
|
|
342
352
|
stop: R,
|
|
343
353
|
clear: () => D([])
|
|
344
354
|
});
|
|
345
|
-
return
|
|
355
|
+
return B() && q(() => {
|
|
346
356
|
c?.abort(), re();
|
|
347
357
|
}), {
|
|
348
358
|
messages: a,
|
|
@@ -356,14 +366,14 @@ function ge(t) {
|
|
|
356
366
|
regenerate: N,
|
|
357
367
|
stop: R,
|
|
358
368
|
setMessages: D,
|
|
359
|
-
handleSubmit:
|
|
369
|
+
handleSubmit: $,
|
|
360
370
|
isLoading: H,
|
|
361
371
|
addToolResult: ee,
|
|
362
372
|
clearError: te,
|
|
363
373
|
isRestored: F(() => v.value)
|
|
364
374
|
};
|
|
365
375
|
}
|
|
366
|
-
function
|
|
376
|
+
function ge(t) {
|
|
367
377
|
const r = t.id ?? J(), e = E(""), o = E("ready"), a = E(void 0), s = E("");
|
|
368
378
|
let n = null;
|
|
369
379
|
const l = async (y) => {
|
|
@@ -377,14 +387,14 @@ function pe(t) {
|
|
|
377
387
|
const C = P(t.system), d = C ? [
|
|
378
388
|
{ role: "system", content: C },
|
|
379
389
|
{ role: "user", content: T }
|
|
380
|
-
] : [{ role: "user", content: T }], { stream:
|
|
390
|
+
] : [{ role: "user", content: T }], { stream: p } = await U(t.provider, {
|
|
381
391
|
model: P(t.model),
|
|
382
392
|
messages: d,
|
|
383
393
|
signal: m.signal
|
|
384
394
|
}, r);
|
|
385
395
|
if (m.signal.aborted) return e.value;
|
|
386
396
|
o.value = "streaming";
|
|
387
|
-
const O =
|
|
397
|
+
const O = p.getReader();
|
|
388
398
|
let I = "stop", A;
|
|
389
399
|
for (; !m.signal.aborted; ) {
|
|
390
400
|
const { done: N, value: R } = await O.read();
|
|
@@ -410,7 +420,7 @@ function pe(t) {
|
|
|
410
420
|
a.value = void 0, o.value === "error" && (o.value = "ready");
|
|
411
421
|
}, f = (y) => {
|
|
412
422
|
y?.preventDefault?.(), s.value.trim() && l();
|
|
413
|
-
}, i = F(() => o.value === "submitted" || o.value === "streaming"), w =
|
|
423
|
+
}, i = F(() => o.value === "submitted" || o.value === "streaming"), w = k({
|
|
414
424
|
id: r,
|
|
415
425
|
kind: "completion",
|
|
416
426
|
providerId: t.provider.id,
|
|
@@ -420,7 +430,7 @@ function pe(t) {
|
|
|
420
430
|
output: e,
|
|
421
431
|
stop: c
|
|
422
432
|
});
|
|
423
|
-
return
|
|
433
|
+
return B() && q(() => {
|
|
424
434
|
n?.abort(), w();
|
|
425
435
|
}), {
|
|
426
436
|
completion: e,
|
|
@@ -466,10 +476,10 @@ function he(t) {
|
|
|
466
476
|
}, r);
|
|
467
477
|
if (m.signal.aborted) return e.value;
|
|
468
478
|
a.value = "streaming";
|
|
469
|
-
const
|
|
479
|
+
const p = d.getReader();
|
|
470
480
|
let O = "", I = "stop", A;
|
|
471
481
|
for (; !m.signal.aborted; ) {
|
|
472
|
-
const { done: N, value: R } = await
|
|
482
|
+
const { done: N, value: R } = await p.read();
|
|
473
483
|
if (m.signal.aborted || N) break;
|
|
474
484
|
if (R.type === "text-delta") {
|
|
475
485
|
O += R.text;
|
|
@@ -480,7 +490,7 @@ function he(t) {
|
|
|
480
490
|
else if (R.type === "error")
|
|
481
491
|
throw R.error;
|
|
482
492
|
}
|
|
483
|
-
if (
|
|
493
|
+
if (p.releaseLock(), m.signal.aborted) return e.value;
|
|
484
494
|
try {
|
|
485
495
|
e.value = JSON.parse(O), o.value = e.value;
|
|
486
496
|
} catch {
|
|
@@ -499,7 +509,7 @@ function he(t) {
|
|
|
499
509
|
l?.abort(), l = null, a.value = "ready";
|
|
500
510
|
}, f = () => {
|
|
501
511
|
s.value = void 0, a.value === "error" && (a.value = "ready");
|
|
502
|
-
}, i = F(() => a.value === "submitted" || a.value === "streaming"), w =
|
|
512
|
+
}, i = F(() => a.value === "submitted" || a.value === "streaming"), w = k({
|
|
503
513
|
id: r,
|
|
504
514
|
kind: "object",
|
|
505
515
|
providerId: t.provider.id,
|
|
@@ -509,7 +519,7 @@ function he(t) {
|
|
|
509
519
|
output: o,
|
|
510
520
|
stop: v
|
|
511
521
|
});
|
|
512
|
-
return
|
|
522
|
+
return B() && q(() => {
|
|
513
523
|
l?.abort(), w();
|
|
514
524
|
}), {
|
|
515
525
|
object: e,
|
|
@@ -575,37 +585,37 @@ function be(t, r) {
|
|
|
575
585
|
function we(t, r = {}) {
|
|
576
586
|
const e = E(null), o = E([]), a = E(!1);
|
|
577
587
|
let s = 0;
|
|
578
|
-
const n = F(() => t.status.value === "submitted" || t.status.value === "streaming"), l = F(() => !n.value && (t.input.value.trim() !== "" || o.value.length > 0)), c = (d) => r.accept ? r.accept.split(",").map((
|
|
579
|
-
const
|
|
580
|
-
if (!
|
|
581
|
-
const O =
|
|
588
|
+
const n = F(() => t.status.value === "submitted" || t.status.value === "streaming"), l = F(() => !n.value && (t.input.value.trim() !== "" || o.value.length > 0)), c = (d) => r.accept ? r.accept.split(",").map((p) => p.trim().toLowerCase()).filter(Boolean).some((p) => p.startsWith(".") ? d.name.toLowerCase().endsWith(p) : p.endsWith("/*") ? d.type.toLowerCase().startsWith(p.slice(0, -1)) : d.type.toLowerCase() === p) : !0, v = (d) => {
|
|
589
|
+
const p = Array.from(d ?? []);
|
|
590
|
+
if (!p.length) return;
|
|
591
|
+
const O = p.filter((A) => !c(A));
|
|
582
592
|
O.length && r.onReject?.(O, "type");
|
|
583
|
-
let I =
|
|
593
|
+
let I = p.filter(c);
|
|
584
594
|
if (r.maxFiles !== void 0) {
|
|
585
595
|
const A = Math.max(0, r.maxFiles - o.value.length);
|
|
586
596
|
I.length > A && r.onReject?.(I.slice(A), "count"), I = I.slice(0, A);
|
|
587
597
|
}
|
|
588
598
|
I.length && (o.value = [...o.value, ...I]);
|
|
589
599
|
}, f = (d) => {
|
|
590
|
-
o.value = o.value.filter((
|
|
600
|
+
o.value = o.value.filter((p) => p !== d);
|
|
591
601
|
}, i = () => {
|
|
592
602
|
const d = e.value;
|
|
593
603
|
if (!d || typeof getComputedStyle > "u") return;
|
|
594
|
-
const
|
|
604
|
+
const p = getComputedStyle(d), O = parseFloat(p.lineHeight) || parseFloat(p.fontSize) * 1.5 || 20, I = (parseFloat(p.paddingTop) || 0) + (parseFloat(p.paddingBottom) || 0), A = (parseFloat(p.borderTopWidth) || 0) + (parseFloat(p.borderBottomWidth) || 0), N = p.boxSizing === "border-box", R = (H) => N ? H + A : H - I, D = O * (r.maxRows ?? 8) + I;
|
|
595
605
|
d.style.height = "auto";
|
|
596
|
-
const
|
|
597
|
-
d.style.height = `${R(Math.min(d.scrollHeight, D))}px`, d.style.overflowY =
|
|
606
|
+
const $ = d.scrollHeight > D;
|
|
607
|
+
d.style.height = `${R(Math.min(d.scrollHeight, D))}px`, d.style.overflowY = $ ? "auto" : "hidden";
|
|
598
608
|
};
|
|
599
609
|
z(t.input, () => V(i)), z(e, () => V(i));
|
|
600
610
|
const w = async () => {
|
|
601
611
|
if (!l.value) return;
|
|
602
|
-
const d = t.input.value,
|
|
603
|
-
t.input.value = "", o.value = [], await t.sendMessage(
|
|
612
|
+
const d = t.input.value, p = o.value;
|
|
613
|
+
t.input.value = "", o.value = [], await t.sendMessage(p.length ? { text: d, files: p } : d);
|
|
604
614
|
}, y = (d) => {
|
|
605
615
|
d.key !== "Enter" || d.shiftKey || r.submitOnEnter === !1 || d.isComposing || d.keyCode === 229 || (d.preventDefault(), w());
|
|
606
616
|
}, T = (d) => {
|
|
607
|
-
const
|
|
608
|
-
|
|
617
|
+
const p = Array.from(d.clipboardData?.files ?? []);
|
|
618
|
+
p.length && (d.preventDefault(), v(p));
|
|
609
619
|
}, m = (d) => Array.from(d.dataTransfer?.types ?? []).includes("Files");
|
|
610
620
|
return {
|
|
611
621
|
textarea: e,
|
|
@@ -659,7 +669,7 @@ function Ce(t = {}) {
|
|
|
659
669
|
f.removeEventListener("scroll", l), i?.disconnect(), w?.disconnect(), v = () => {
|
|
660
670
|
};
|
|
661
671
|
};
|
|
662
|
-
}, { flush: "post" }),
|
|
672
|
+
}, { flush: "post" }), B() && q(() => v()), { container: r, isAtBottom: e, scrollToBottom: n };
|
|
663
673
|
}
|
|
664
674
|
function le(t) {
|
|
665
675
|
typeof requestAnimationFrame == "function" ? requestAnimationFrame(() => requestAnimationFrame(t)) : setTimeout(t, 32);
|
|
@@ -888,8 +898,8 @@ export {
|
|
|
888
898
|
G as renderTemplate,
|
|
889
899
|
Te as retryMiddleware,
|
|
890
900
|
Ce as useAutoScroll,
|
|
891
|
-
|
|
892
|
-
|
|
901
|
+
pe as useChat,
|
|
902
|
+
ge as useCompletion,
|
|
893
903
|
he as useObject,
|
|
894
904
|
be as usePrompt,
|
|
895
905
|
we as usePromptInput,
|
|
@@ -80,6 +80,13 @@ export type ChatStreamChunk =
|
|
|
80
80
|
result?: unknown;
|
|
81
81
|
error?: string;
|
|
82
82
|
}
|
|
83
|
+
/** Adds a data part to the answer, or replaces the data of the part with the same `name` and `id` */
|
|
84
|
+
| {
|
|
85
|
+
type: 'data';
|
|
86
|
+
name: string;
|
|
87
|
+
data: unknown;
|
|
88
|
+
id?: string;
|
|
89
|
+
}
|
|
83
90
|
/** Merged into `metadata` of the assistant message; later keys replace earlier ones */
|
|
84
91
|
| {
|
|
85
92
|
type: 'message-metadata';
|
package/dist/types.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export interface UIMessage {
|
|
|
5
5
|
metadata?: Record<string, unknown>;
|
|
6
6
|
createdAt?: Date;
|
|
7
7
|
}
|
|
8
|
-
export type UIMessagePart = TextPart | ReasoningPart | ToolCallPart | FilePart | SourcePart;
|
|
8
|
+
export type UIMessagePart = TextPart | ReasoningPart | ToolCallPart | FilePart | SourcePart | DataPart;
|
|
9
9
|
export interface TextPart {
|
|
10
10
|
type: 'text';
|
|
11
11
|
text: string;
|
|
@@ -44,6 +44,16 @@ export interface SourcePart {
|
|
|
44
44
|
url: string;
|
|
45
45
|
title?: string;
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Custom data shown in the answer, such as a chart, a table or progress. Not sent to the model.
|
|
49
|
+
* A later `data` chunk with the same `name` and `id` replaces `data` in place.
|
|
50
|
+
*/
|
|
51
|
+
export interface DataPart<Data = unknown> {
|
|
52
|
+
type: 'data';
|
|
53
|
+
name: string;
|
|
54
|
+
data: Data;
|
|
55
|
+
id?: string;
|
|
56
|
+
}
|
|
47
57
|
export interface ToolDefinition {
|
|
48
58
|
name: string;
|
|
49
59
|
description: string;
|
|
@@ -76,6 +86,11 @@ export interface ToolComponentProps<Args = AnyArgs, Result = AnyArgs> {
|
|
|
76
86
|
/** Resolve the call from the UI (human-in-the-loop) */
|
|
77
87
|
addResult: (result: Result) => void;
|
|
78
88
|
}
|
|
89
|
+
/** Props passed to a component rendering a data part, see `dataComponents` */
|
|
90
|
+
export interface DataComponentProps<Data = AnyArgs> {
|
|
91
|
+
name: string;
|
|
92
|
+
data: Data;
|
|
93
|
+
}
|
|
79
94
|
export type ChatStatus = 'ready' | 'submitted' | 'streaming' | 'error';
|
|
80
95
|
export type FinishReason = 'stop' | 'length' | 'tool-calls' | 'error';
|
|
81
96
|
export interface Usage {
|
package/dist/vue-llm.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
.vue-llm-cursor[data-v-f225ccf4]{animation:vue-llm-blink-f225ccf4 .7s step-end infinite}@keyframes vue-llm-blink-f225ccf4{50%{opacity:0}}.vue-llm-text[data-v-
|
|
1
|
+
.vue-llm-cursor[data-v-f225ccf4]{animation:vue-llm-blink-f225ccf4 .7s step-end infinite}@keyframes vue-llm-blink-f225ccf4{50%{opacity:0}}.vue-llm-text[data-v-3868ad67]{white-space:pre-wrap}.vue-llm-file[data-v-3868ad67]{max-width:100%}
|
package/package.json
CHANGED