vue-llm 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,23 @@
1
1
  # vue-llm
2
2
 
3
- AI/LLM composables for Vue. The missing AI SDK for the Vue ecosystem.
3
+ [![npm version](https://img.shields.io/npm/v/vue-llm.svg)](https://www.npmjs.com/package/vue-llm)
4
+ [![npm downloads](https://img.shields.io/npm/dm/vue-llm.svg)](https://www.npmjs.com/package/vue-llm)
5
+ [![CI](https://github.com/dadashi44/vue-llm/actions/workflows/ci.yml/badge.svg)](https://github.com/dadashi44/vue-llm/actions/workflows/ci.yml)
6
+ [![license](https://img.shields.io/npm/l/vue-llm.svg)](./LICENSE)
7
+
8
+ **vue-llm** is the AI SDK for Vue and Nuxt: streaming `useChat`, tool calling, Generative UI and in-browser models for OpenAI, Anthropic, Gemini, Ollama and WebGPU.
4
9
 
5
10
  `useChat()` with streaming, tool calling, multi-provider support — in 10 lines of code.
6
11
 
7
- **Documentation:** https://dadashi44.github.io/vue-llm/
12
+ **Documentation:** https://dadashi44.github.io/vue-llm/ · **[Try it in your browser](https://dadashi44.github.io/vue-llm/playground)** — no API key needed
8
13
 
9
14
  ## Features
10
15
 
11
16
  - **`useChat()`** — reactive composable with streaming, abort, regenerate
12
- - **Multi-provider** — OpenAI, Anthropic, Ollama out of the box
13
- - **Tool calling** — automatic roundtrips with `onToolCall` handler
17
+ - **Multi-provider** — OpenAI, Anthropic, Gemini, Ollama out of the box
18
+ - **In-browser models** — run Llama, Qwen or SmolLM on WebGPU with `createWebLLM`, no server or API key
19
+ - **Generative UI** — render tool calls as your Vue components with `<MessageParts>`, streamed arguments and human-in-the-loop
20
+ - **Tool calling** — `defineTool` with `execute`, `onToolCall`, `addToolResult`
14
21
  - **Attachments** — images, PDFs, audio and text files, mapped per provider
15
22
  - **Persistence** — restore chat history from localStorage or any custom backend
16
23
  - **Resilience** — retries with exponential backoff, client and server rate limiting
@@ -18,7 +25,9 @@ AI/LLM composables for Vue. The missing AI SDK for the Vue ecosystem.
18
25
  - **Any backend** — server-side tools in `createLLMHandler`, `createSSEProvider` for your own SSE API
19
26
  - **Streaming** — SSE parser, text/reasoning/tool-call deltas
20
27
  - **Security** — `dangerouslyAllowBrowser` guard protects API keys
21
- - **Nuxt module** — auto-imports, server-side runtime config
28
+ - **Chat UI** — a complete chat you own: `npx shadcn-vue add https://dadashi44.github.io/vue-llm/r/chat.json`, plus headless `usePromptInput` and `useAutoScroll`
29
+ - **Vue DevTools** — an LLM tab with every chat, request timeline, time to first token, tool calls and token usage (`vue-llm/devtools`)
30
+ - **Nuxt module** — auto-imports, components, DevTools in development, server-side runtime config
22
31
  - **Zero runtime deps** — only `vue` as peer dependency (Vue 3.3+, composables also on Vue 2.7)
23
32
  - **TypeScript** — full type safety, exported types
24
33
 
@@ -99,6 +108,25 @@ const { messages, sendMessage } = useChat({
99
108
  })
100
109
  ```
101
110
 
111
+ ### In the browser (WebGPU)
112
+
113
+ ```ts
114
+ import { CreateMLCEngine } from '@mlc-ai/web-llm' // npm i @mlc-ai/web-llm
115
+ import { createWebLLM } from 'vue-llm/providers'
116
+
117
+ const ai = createWebLLM({
118
+ createEngine: CreateMLCEngine,
119
+ onProgress: ({ progress }) => console.log(`${Math.round(progress * 100)}%`),
120
+ })
121
+
122
+ const { messages, sendMessage } = useChat({
123
+ provider: ai,
124
+ model: 'Llama-3.2-1B-Instruct-q4f16_1-MLC',
125
+ })
126
+ ```
127
+
128
+ The model runs on the user's GPU, and nothing leaves the device. See [In-Browser Models](https://dadashi44.github.io/vue-llm/guide/in-browser).
129
+
102
130
  ## Tool Calling
103
131
 
104
132
  ```ts
@@ -0,0 +1,33 @@
1
+ import type { Component } from 'vue';
2
+ import type { ToolCallPart, UIMessage } from '../types';
3
+ type __VLS_Props = {
4
+ message: UIMessage;
5
+ /** Components that render tool calls, keyed by tool name (Generative UI) */
6
+ components?: Record<string, Component>;
7
+ /** Markdown renderer for text parts, see StreamMarkdown */
8
+ render?: (markdown: string) => string;
9
+ };
10
+ type __VLS_Slots = {
11
+ tool?: (props: {
12
+ part: ToolCallPart;
13
+ addResult: (result: unknown) => void;
14
+ }) => unknown;
15
+ };
16
+ declare const __VLS_component: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
17
+ "tool-result": (payload: {
18
+ toolCallId: string;
19
+ result: unknown;
20
+ }) => any;
21
+ }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
22
+ "onTool-result"?: ((payload: {
23
+ toolCallId: string;
24
+ result: unknown;
25
+ }) => any) | undefined;
26
+ }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
27
+ declare const _default: __VLS_WithSlots<typeof __VLS_component, __VLS_Slots>;
28
+ export default _default;
29
+ type __VLS_WithSlots<T, S> = T & {
30
+ new (): {
31
+ $slots: S;
32
+ };
33
+ };
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("vue"),j=/^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;function h(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function w(s){const e=s.replace(/\r\n?/g,`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),b=/^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;function h(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function y(o){const t=o.replace(/\r\n?/g,`
2
2
  `).split(`
3
- `),n=[];let t=0;for(;t<e.length;){const a=e[t],d=/^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(a);if(d){const o=[];for(t++;t<e.length&&!e[t].trimStart().startsWith(d[1]);)o.push(e[t]),t++;t++;const c=d[2]?` class="language-${h(d[2])}"`:"";n.push(`<pre><code${c}>${h(o.join(`
4
- `))}</code></pre>`);continue}if(!a.trim()){t++;continue}const f=/^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(a);if(f){const o=f[1].length;n.push(`<h${o}>${u(f[2])}</h${o}>`),t++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(a)){n.push("<hr>"),t++;continue}if(/^\s*>/.test(a)){const o=[];for(;t<e.length&&/^\s*>/.test(e[t]);)o.push(e[t].replace(/^\s*>\s?/,"")),t++;n.push(`<blockquote>${w(o.join(`
5
- `))}</blockquote>`);continue}if(b(e,t)){const o=_(e[t]),c=_(e[t+1]).map(r=>r.endsWith(":")?r.startsWith(":")?"center":"right":r.startsWith(":")?"left":"");t+=2;const l=[];for(;t<e.length&&e[t].includes("|")&&e[t].trim();)l.push(_(e[t])),t++;const g=(r,$,p)=>{const M=c[p]?` style="text-align:${c[p]}"`:"";return`<${r}${M}>${u($)}</${r}>`};n.push("<table><thead><tr>"+o.map((r,$)=>g("th",r,$)).join("")+"</tr></thead><tbody>"+l.map(r=>"<tr>"+o.map(($,p)=>g("td",r[p]??"",p)).join("")+"</tr>").join("")+"</tbody></table>");continue}const m=/^\s*([-*+]|\d+[.)])\s+/.exec(a);if(m){const o=/\d/.test(m[1]),c=[];for(;t<e.length;){const r=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(e[t]);if(r&&/\d/.test(r[1])===o)c.push(r[2]);else if(e[t].trim()&&/^\s{2,}/.test(e[t])&&c.length>0)c[c.length-1]+=" "+e[t].trim();else break;t++}const l=o?"ol":"ul",g=o&&parseInt(m[1],10)!==1?` start="${parseInt(m[1],10)}"`:"";n.push(`<${l}${g}>${c.map(r=>`<li>${u(r)}</li>`).join("")}</${l}>`);continue}const k=[];for(;t<e.length&&e[t].trim()&&!y(e,t);)k.push(e[t].trim()),t++;n.push(`<p>${k.map(u).join("<br>")}</p>`)}return n.join(`
6
- `)}function u(s){return s.split(/(`+[^`]*`+)/).map((e,n)=>n%2===1?`<code>${h(e.replace(/^`+|`+$/g,""))}</code>`:v(h(e))).join("")}function v(s){return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(e,n,t)=>S(t)?`<img src="${t}" alt="${n}">`:n).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(e,n,t)=>S(t)?`<a href="${t}" target="_blank" rel="noopener noreferrer">${n}</a>`:n).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(s){const e=s.replace(/&amp;/g,"&").replace(/&#(x?[0-9a-f]+);?/gi,"?");return j.test(e.trim())}function _(s){return s.trim().replace(/^\||\|$/g,"").split("|").map(e=>e.trim())}function b(s,e){return s[e].includes("|")&&e+1<s.length&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(s[e+1])}function y(s,e){const n=s[e];return/^\s*(`{3,}|~{3,})/.test(n)||/^#{1,6}\s/.test(n)||/^\s*>/.test(n)||/^\s*([-*+]|\d+[.)])\s+/.test(n)||/^\s*([-*_])(\s*\1){2,}\s*$/.test(n)||b(s,e)}const x=["innerHTML"],B={key:0,class:"vue-llm-cursor","aria-hidden":"true"},L=i.defineComponent({__name:"StreamMarkdown",props:{content:{},streaming:{type:Boolean},render:{type:Function}},setup(s){const e=s,n=i.computed(()=>(e.render??w)(e.content));return(t,a)=>(i.openBlock(),i.createElementBlock(i.Fragment,null,[i.createElementVNode("div",{class:"vue-llm-markdown",innerHTML:n.value},null,8,x),s.streaming?(i.openBlock(),i.createElementBlock("span",B,"▊")):i.createCommentVNode("",!0)],64))}}),T=(s,e)=>{const n=s.__vccOpts||s;for(const[t,a]of e)n[t]=a;return n},q=T(L,[["__scopeId","data-v-52dbf793"]]);exports.StreamMarkdown=q;exports.escapeHTML=h;exports.renderInline=u;exports.renderMarkdown=w;
3
+ `),l=[];let n=0;for(;n<t.length;){const r=t[n],m=/^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(r);if(m){const a=[];for(n++;n<t.length&&!t[n].trimStart().startsWith(m[1]);)a.push(t[n]),n++;n++;const i=m[2]?` class="language-${h(m[2])}"`:"";l.push(`<pre><code${i}>${h(a.join(`
4
+ `))}</code></pre>`);continue}if(!r.trim()){n++;continue}const s=/^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(r);if(s){const a=s[1].length;l.push(`<h${a}>${p(s[2])}</h${a}>`),n++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(r)){l.push("<hr>"),n++;continue}if(/^\s*>/.test(r)){const a=[];for(;n<t.length&&/^\s*>/.test(t[n]);)a.push(t[n].replace(/^\s*>\s?/,"")),n++;l.push(`<blockquote>${y(a.join(`
5
+ `))}</blockquote>`);continue}if(v(t,n)){const a=$(t[n]),i=$(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($(t[n])),n++;const k=(c,f,g)=>{const E=i[g]?` style="text-align:${i[g]}"`:"";return`<${c}${E}>${p(f)}</${c}>`};l.push("<table><thead><tr>"+a.map((c,f)=>k("th",c,f)).join("")+"</tr></thead><tbody>"+d.map(c=>"<tr>"+a.map((f,g)=>k("td",c[g]??"",g)).join("")+"</tr>").join("")+"</tbody></table>");continue}const u=/^\s*([-*+]|\d+[.)])\s+/.exec(r);if(u){const a=/\d/.test(u[1]),i=[];for(;n<t.length;){const c=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(t[n]);if(c&&/\d/.test(c[1])===a)i.push(c[2]);else if(t[n].trim()&&/^\s{2,}/.test(t[n])&&i.length>0)i[i.length-1]+=" "+t[n].trim();else break;n++}const d=a?"ol":"ul",k=a&&parseInt(u[1],10)!==1?` start="${parseInt(u[1],10)}"`:"";l.push(`<${d}${k}>${i.map(c=>`<li>${p(c)}</li>`).join("")}</${d}>`);continue}const _=[];for(;n<t.length&&t[n].trim()&&!x(t,n);)_.push(t[n].trim()),n++;l.push(`<p>${_.map(p).join("<br>")}</p>`)}return l.join(`
6
+ `)}function p(o){return o.split(/(`+[^`]*`+)/).map((t,l)=>l%2===1?`<code>${h(t.replace(/^`+|`+$/g,""))}</code>`:M(h(t))).join("")}function M(o){return o.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(t,l,n)=>B(n)?`<img src="${n}" alt="${l}">`:l).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(t,l,n)=>B(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 B(o){const t=o.replace(/&amp;/g,"&").replace(/&#(x?[0-9a-f]+);?/gi,"?");return b.test(t.trim())}function $(o){return o.trim().replace(/^\||\|$/g,"").split("|").map(t=>t.trim())}function v(o,t){return o[t].includes("|")&&t+1<o.length&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(o[t+1])}function x(o,t){const l=o[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(o,t)}const I=["innerHTML"],j={key:0,class:"vue-llm-cursor","aria-hidden":"true"},C=e.defineComponent({__name:"StreamMarkdown",props:{content:{},streaming:{type:Boolean},render:{type:Function}},setup(o){const t=o,l=e.computed(()=>(t.render??y)(t.content));return(n,r)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createElementVNode("div",{class:"vue-llm-markdown",innerHTML:l.value},null,8,I),o.streaming?(e.openBlock(),e.createElementBlock("span",j,"▊")):e.createCommentVNode("",!0)],64))}}),S=(o,t)=>{const l=o.__vccOpts||o;for(const[n,r]of t)l[n]=r;return l},w=S(C,[["__scopeId","data-v-52dbf793"]]),F=["data-role"],N={key:0,class:"vue-llm-text"},T=["open"],L=["src","alt"],R={key:1,class:"vue-llm-file"},P=["href"],q=e.defineComponent({__name:"MessageParts",props:{message:{},components:{},render:{type:Function}},emits:["tool-result"],setup(o,{emit:t}){const l=t,n=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":o.message.role},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(o.message.parts,(s,u)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:s.type==="tool-call"?s.toolCallId:u},[s.type==="text"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[o.message.role==="user"?(e.openBlock(),e.createElementBlock("div",N,e.toDisplayString(s.text),1)):(e.openBlock(),e.createBlock(w,{key:1,content:s.text,streaming:s.state==="streaming",render:o.render},null,8,["content","streaming","render"]))],64)):s.type==="reasoning"?(e.openBlock(),e.createElementBlock("details",{key:1,class:"vue-llm-reasoning",open:s.state==="streaming"},[m[0]||(m[0]=e.createElementVNode("summary",null,"Reasoning",-1)),e.createElementVNode("div",null,e.toDisplayString(s.text),1)],8,T)):s.type==="tool-call"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[o.components?.[s.toolName]?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(o.components[s.toolName]),e.mergeProps({key:0,ref_for:!0},n(s)),null,16)):e.renderSlot(r.$slots,"tool",{part:s,addResult:n(s).addResult},void 0,!0,1)],64)):s.type==="file"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[s.mediaType.startsWith("image/")?(e.openBlock(),e.createElementBlock("img",{key:0,class:"vue-llm-file",src:s.url,alt:s.filename??""},null,8,L)):(e.openBlock(),e.createElementBlock("span",R,e.toDisplayString(s.filename??s.mediaType),1))],64)):s.type==="source"&&/^https?:/i.test(s.url)?(e.openBlock(),e.createElementBlock("a",{key:4,class:"vue-llm-source",href:s.url,target:"_blank",rel:"noopener noreferrer"},e.toDisplayString(s.title??s.url),9,P)):e.createCommentVNode("",!0)],64))),128))],8,F))}}),D=S(q,[["__scopeId","data-v-3f30944b"]]);exports.MessageParts=D;exports.StreamMarkdown=w;exports.escapeHTML=h;exports.renderInline=p;exports.renderMarkdown=y;
@@ -1,2 +1,3 @@
1
1
  export { default as StreamMarkdown } from './components/StreamMarkdown.vue';
2
+ export { default as MessageParts } from './components/MessageParts.vue';
2
3
  export { renderMarkdown, renderInline, escapeHTML } from './core/markdown';
@@ -1,112 +1,112 @@
1
- import { defineComponent as v, computed as y, openBlock as w, createElementBlock as S, Fragment as M, createElementVNode as L, createCommentVNode as q } from "vue";
2
- const B = /^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;
3
- function g(s) {
1
+ import { defineComponent as I, computed as N, openBlock as a, createElementBlock as i, Fragment as g, createElementVNode as w, createCommentVNode as j, renderList as T, toDisplayString as _, createBlock as x, resolveDynamicComponent as B, mergeProps as W, renderSlot as q } from "vue";
2
+ const E = /^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;
3
+ function k(s) {
4
4
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
5
5
  }
6
- function b(s) {
6
+ function M(s) {
7
7
  const e = s.replace(/\r\n?/g, `
8
8
  `).split(`
9
- `), n = [];
9
+ `), o = [];
10
10
  let t = 0;
11
11
  for (; t < e.length; ) {
12
- const a = e[t], p = /^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(a);
13
- if (p) {
14
- const o = [];
15
- for (t++; t < e.length && !e[t].trimStart().startsWith(p[1]); )
16
- o.push(e[t]), t++;
12
+ const l = e[t], m = /^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(l);
13
+ if (m) {
14
+ const c = [];
15
+ for (t++; t < e.length && !e[t].trimStart().startsWith(m[1]); )
16
+ c.push(e[t]), t++;
17
17
  t++;
18
- const c = p[2] ? ` class="language-${g(p[2])}"` : "";
19
- n.push(`<pre><code${c}>${g(o.join(`
18
+ const u = m[2] ? ` class="language-${k(m[2])}"` : "";
19
+ o.push(`<pre><code${u}>${k(c.join(`
20
20
  `))}</code></pre>`);
21
21
  continue;
22
22
  }
23
- if (!a.trim()) {
23
+ if (!l.trim()) {
24
24
  t++;
25
25
  continue;
26
26
  }
27
- const $ = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(a);
28
- if ($) {
29
- const o = $[1].length;
30
- n.push(`<h${o}>${d($[2])}</h${o}>`), t++;
27
+ const n = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(l);
28
+ if (n) {
29
+ const c = n[1].length;
30
+ o.push(`<h${c}>${y(n[2])}</h${c}>`), t++;
31
31
  continue;
32
32
  }
33
- if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(a)) {
34
- n.push("<hr>"), t++;
33
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) {
34
+ o.push("<hr>"), t++;
35
35
  continue;
36
36
  }
37
- if (/^\s*>/.test(a)) {
38
- const o = [];
37
+ if (/^\s*>/.test(l)) {
38
+ const c = [];
39
39
  for (; t < e.length && /^\s*>/.test(e[t]); )
40
- o.push(e[t].replace(/^\s*>\s?/, "")), t++;
41
- n.push(`<blockquote>${b(o.join(`
40
+ c.push(e[t].replace(/^\s*>\s?/, "")), t++;
41
+ o.push(`<blockquote>${M(c.join(`
42
42
  `))}</blockquote>`);
43
43
  continue;
44
44
  }
45
- if (j(e, t)) {
46
- const o = f(e[t]), c = f(e[t + 1]).map((r) => r.endsWith(":") ? r.startsWith(":") ? "center" : "right" : r.startsWith(":") ? "left" : "");
45
+ if (C(e, t)) {
46
+ const c = v(e[t]), u = v(e[t + 1]).map((r) => r.endsWith(":") ? r.startsWith(":") ? "center" : "right" : r.startsWith(":") ? "left" : "");
47
47
  t += 2;
48
- const i = [];
48
+ const h = [];
49
49
  for (; t < e.length && e[t].includes("|") && e[t].trim(); )
50
- i.push(f(e[t])), t++;
51
- const h = (r, m, l) => {
52
- const x = c[l] ? ` style="text-align:${c[l]}"` : "";
53
- return `<${r}${x}>${d(m)}</${r}>`;
50
+ h.push(v(e[t])), t++;
51
+ const f = (r, $, p) => {
52
+ const L = u[p] ? ` style="text-align:${u[p]}"` : "";
53
+ return `<${r}${L}>${y($)}</${r}>`;
54
54
  };
55
- n.push(
56
- "<table><thead><tr>" + o.map((r, m) => h("th", r, m)).join("") + "</tr></thead><tbody>" + i.map((r) => "<tr>" + o.map((m, l) => h("td", r[l] ?? "", l)).join("") + "</tr>").join("") + "</tbody></table>"
55
+ o.push(
56
+ "<table><thead><tr>" + c.map((r, $) => f("th", r, $)).join("") + "</tr></thead><tbody>" + h.map((r) => "<tr>" + c.map(($, p) => f("td", r[p] ?? "", p)).join("") + "</tr>").join("") + "</tbody></table>"
57
57
  );
58
58
  continue;
59
59
  }
60
- const u = /^\s*([-*+]|\d+[.)])\s+/.exec(a);
61
- if (u) {
62
- const o = /\d/.test(u[1]), c = [];
60
+ const d = /^\s*([-*+]|\d+[.)])\s+/.exec(l);
61
+ if (d) {
62
+ const c = /\d/.test(d[1]), u = [];
63
63
  for (; t < e.length; ) {
64
64
  const r = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(e[t]);
65
- if (r && /\d/.test(r[1]) === o)
66
- c.push(r[2]);
67
- else if (e[t].trim() && /^\s{2,}/.test(e[t]) && c.length > 0)
68
- c[c.length - 1] += " " + e[t].trim();
65
+ if (r && /\d/.test(r[1]) === c)
66
+ u.push(r[2]);
67
+ else if (e[t].trim() && /^\s{2,}/.test(e[t]) && u.length > 0)
68
+ u[u.length - 1] += " " + e[t].trim();
69
69
  else
70
70
  break;
71
71
  t++;
72
72
  }
73
- const i = o ? "ol" : "ul", h = o && parseInt(u[1], 10) !== 1 ? ` start="${parseInt(u[1], 10)}"` : "";
74
- n.push(`<${i}${h}>${c.map((r) => `<li>${d(r)}</li>`).join("")}</${i}>`);
73
+ const h = c ? "ol" : "ul", f = c && parseInt(d[1], 10) !== 1 ? ` start="${parseInt(d[1], 10)}"` : "";
74
+ o.push(`<${h}${f}>${u.map((r) => `<li>${y(r)}</li>`).join("")}</${h}>`);
75
75
  continue;
76
76
  }
77
- const _ = [];
78
- for (; t < e.length && e[t].trim() && !I(e, t); )
79
- _.push(e[t].trim()), t++;
80
- n.push(`<p>${_.map(d).join("<br>")}</p>`);
77
+ const S = [];
78
+ for (; t < e.length && e[t].trim() && !P(e, t); )
79
+ S.push(e[t].trim()), t++;
80
+ o.push(`<p>${S.map(y).join("<br>")}</p>`);
81
81
  }
82
- return n.join(`
82
+ return o.join(`
83
83
  `);
84
84
  }
85
- function d(s) {
86
- return s.split(/(`+[^`]*`+)/).map((e, n) => n % 2 === 1 ? `<code>${g(e.replace(/^`+|`+$/g, ""))}</code>` : E(g(e))).join("");
85
+ function y(s) {
86
+ return s.split(/(`+[^`]*`+)/).map((e, o) => o % 2 === 1 ? `<code>${k(e.replace(/^`+|`+$/g, ""))}</code>` : F(k(e))).join("");
87
87
  }
88
- function E(s) {
89
- return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (e, n, t) => k(t) ? `<img src="${t}" alt="${n}">` : n).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (e, n, t) => k(t) ? `<a href="${t}" target="_blank" rel="noopener noreferrer">${n}</a>` : n).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>");
88
+ function F(s) {
89
+ return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (e, o, t) => b(t) ? `<img src="${t}" alt="${o}">` : o).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (e, o, t) => b(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 k(s) {
91
+ function b(s) {
92
92
  const e = s.replace(/&amp;/g, "&").replace(/&#(x?[0-9a-f]+);?/gi, "?");
93
- return B.test(e.trim());
93
+ return E.test(e.trim());
94
94
  }
95
- function f(s) {
95
+ function v(s) {
96
96
  return s.trim().replace(/^\||\|$/g, "").split("|").map((e) => e.trim());
97
97
  }
98
- function j(s, e) {
98
+ function C(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
- function I(s, e) {
102
- const n = s[e];
103
- return /^\s*(`{3,}|~{3,})/.test(n) || /^#{1,6}\s/.test(n) || /^\s*>/.test(n) || /^\s*([-*+]|\d+[.)])\s+/.test(n) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(n) || j(s, e);
101
+ function P(s, e) {
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) || C(s, e);
104
104
  }
105
- const T = ["innerHTML"], W = {
105
+ const H = ["innerHTML"], D = {
106
106
  key: 0,
107
107
  class: "vue-llm-cursor",
108
108
  "aria-hidden": "true"
109
- }, F = /* @__PURE__ */ v({
109
+ }, U = /* @__PURE__ */ I({
110
110
  __name: "StreamMarkdown",
111
111
  props: {
112
112
  content: {},
@@ -114,24 +114,95 @@ const T = ["innerHTML"], W = {
114
114
  render: { type: Function }
115
115
  },
116
116
  setup(s) {
117
- const e = s, n = y(() => (e.render ?? b)(e.content));
118
- return (t, a) => (w(), S(M, null, [
119
- L("div", {
117
+ const e = s, o = N(() => (e.render ?? M)(e.content));
118
+ return (t, l) => (a(), i(g, null, [
119
+ w("div", {
120
120
  class: "vue-llm-markdown",
121
- innerHTML: n.value
122
- }, null, 8, T),
123
- s.streaming ? (w(), S("span", W, "▊")) : q("", !0)
121
+ innerHTML: o.value
122
+ }, null, 8, H),
123
+ s.streaming ? (a(), i("span", D, "▊")) : j("", !0)
124
124
  ], 64));
125
125
  }
126
- }), H = (s, e) => {
127
- const n = s.__vccOpts || s;
128
- for (const [t, a] of e)
129
- n[t] = a;
130
- return n;
131
- }, C = /* @__PURE__ */ H(F, [["__scopeId", "data-v-52dbf793"]]);
126
+ }), R = (s, e) => {
127
+ const o = s.__vccOpts || s;
128
+ for (const [t, l] of e)
129
+ o[t] = l;
130
+ return o;
131
+ }, V = /* @__PURE__ */ R(U, [["__scopeId", "data-v-52dbf793"]]), A = ["data-role"], O = {
132
+ key: 0,
133
+ class: "vue-llm-text"
134
+ }, z = ["open"], G = ["src", "alt"], J = {
135
+ key: 1,
136
+ class: "vue-llm-file"
137
+ }, K = ["href"], Q = /* @__PURE__ */ I({
138
+ __name: "MessageParts",
139
+ props: {
140
+ message: {},
141
+ components: {},
142
+ render: { type: Function }
143
+ },
144
+ emits: ["tool-result"],
145
+ setup(s, { emit: e }) {
146
+ const o = e, t = (l) => ({
147
+ toolCallId: l.toolCallId,
148
+ toolName: l.toolName,
149
+ args: l.args,
150
+ state: l.state,
151
+ result: l.result,
152
+ error: l.error,
153
+ addResult: (m) => o("tool-result", { toolCallId: l.toolCallId, result: m })
154
+ });
155
+ return (l, m) => (a(), i("div", {
156
+ class: "vue-llm-message",
157
+ "data-role": s.message.role
158
+ }, [
159
+ (a(!0), i(g, null, T(s.message.parts, (n, d) => (a(), i(g, {
160
+ key: n.type === "tool-call" ? n.toolCallId : d
161
+ }, [
162
+ n.type === "text" ? (a(), i(g, { key: 0 }, [
163
+ s.message.role === "user" ? (a(), i("div", O, _(n.text), 1)) : (a(), x(V, {
164
+ key: 1,
165
+ content: n.text,
166
+ streaming: n.state === "streaming",
167
+ render: s.render
168
+ }, null, 8, ["content", "streaming", "render"]))
169
+ ], 64)) : n.type === "reasoning" ? (a(), i("details", {
170
+ key: 1,
171
+ class: "vue-llm-reasoning",
172
+ open: n.state === "streaming"
173
+ }, [
174
+ m[0] || (m[0] = w("summary", null, "Reasoning", -1)),
175
+ w("div", null, _(n.text), 1)
176
+ ], 8, z)) : n.type === "tool-call" ? (a(), i(g, { key: 2 }, [
177
+ s.components?.[n.toolName] ? (a(), x(B(s.components[n.toolName]), W({
178
+ key: 0,
179
+ ref_for: !0
180
+ }, t(n)), null, 16)) : q(l.$slots, "tool", {
181
+ part: n,
182
+ addResult: t(n).addResult
183
+ }, void 0, !0, 1)
184
+ ], 64)) : n.type === "file" ? (a(), i(g, { key: 3 }, [
185
+ n.mediaType.startsWith("image/") ? (a(), i("img", {
186
+ key: 0,
187
+ class: "vue-llm-file",
188
+ src: n.url,
189
+ alt: n.filename ?? ""
190
+ }, null, 8, G)) : (a(), i("span", J, _(n.filename ?? n.mediaType), 1))
191
+ ], 64)) : n.type === "source" && /^https?:/i.test(n.url) ? (a(), i("a", {
192
+ key: 4,
193
+ class: "vue-llm-source",
194
+ href: n.url,
195
+ target: "_blank",
196
+ rel: "noopener noreferrer"
197
+ }, _(n.title ?? n.url), 9, K)) : j("", !0)
198
+ ], 64))), 128))
199
+ ], 8, A));
200
+ }
201
+ }), Y = /* @__PURE__ */ R(Q, [["__scopeId", "data-v-3f30944b"]]);
132
202
  export {
133
- C as StreamMarkdown,
134
- g as escapeHTML,
135
- d as renderInline,
136
- b as renderMarkdown
203
+ Y as MessageParts,
204
+ V as StreamMarkdown,
205
+ k as escapeHTML,
206
+ y as renderInline,
207
+ M as renderMarkdown
137
208
  };
@@ -0,0 +1,17 @@
1
+ import { type Ref } from 'vue';
2
+ export interface UseAutoScrollOptions {
3
+ /** Distance from the bottom, in px, that still counts as "at the bottom". Default `48`. */
4
+ threshold?: number;
5
+ }
6
+ export interface UseAutoScrollReturn {
7
+ /** Bind to the scrollable element with `ref="container"` */
8
+ container: Ref<HTMLElement | null>;
9
+ /** False once the user scrolls up; use it to show a "scroll to bottom" button */
10
+ isAtBottom: Ref<boolean>;
11
+ scrollToBottom: (behavior?: ScrollBehavior) => void;
12
+ }
13
+ /**
14
+ * Keeps a message list pinned to the bottom while content streams in,
15
+ * and lets the user scroll up to read without being pulled back down.
16
+ */
17
+ export declare function useAutoScroll(options?: UseAutoScrollOptions): UseAutoScrollReturn;
@@ -1,6 +1,6 @@
1
1
  import { type Ref } from 'vue';
2
2
  import { type MaybeRef, type MaybeRefOrGetter } from '../utils/vue';
3
- import type { ChatStatus, FinishReason, ToolDefinition, UIMessage, Usage } from '../types';
3
+ import type { ChatStatus, ChatTool, FinishReason, UIMessage, Usage } from '../types';
4
4
  import type { LLMProvider } from '../providers/types';
5
5
  import type { ChatStorage } from '../core/storage';
6
6
  import { type FileInput } from '../utils/file';
@@ -11,12 +11,14 @@ export type SendMessageInput = string | {
11
11
  export interface UseChatOptions {
12
12
  id?: string;
13
13
  provider: LLMProvider;
14
- model: string;
14
+ model: MaybeRefOrGetter<string>;
15
15
  system?: MaybeRefOrGetter<string | undefined>;
16
16
  initialMessages?: UIMessage[];
17
17
  body?: MaybeRef<Record<string, unknown>>;
18
18
  providerOptions?: Record<string, unknown>;
19
- tools?: ToolDefinition[];
19
+ /** Tools with `execute` run automatically; others go to `onToolCall` or wait for `addToolResult` */
20
+ tools?: ChatTool[];
21
+ /** Return a result to resolve the call, or `undefined` to resolve it later with `addToolResult` */
20
22
  onToolCall?: (toolCall: {
21
23
  toolCallId: string;
22
24
  toolName: string;
@@ -28,6 +30,8 @@ export interface UseChatOptions {
28
30
  }) => void;
29
31
  onError?: (error: Error) => void;
30
32
  maxToolRoundtrips?: number;
33
+ /** Continue the conversation once `addToolResult` has resolved every pending call. Default `true`. */
34
+ autoSendToolResults?: boolean;
31
35
  storage?: ChatStorage;
32
36
  }
33
37
  export interface UseChatReturn {
@@ -42,10 +46,12 @@ export interface UseChatReturn {
42
46
  setMessages: (messages: UIMessage[] | ((prev: UIMessage[]) => UIMessage[])) => void;
43
47
  handleSubmit: (event?: Event) => void;
44
48
  isLoading: Ref<boolean>;
49
+ /** Resolve a tool call from the UI. Continues the chat when no other call is pending. */
45
50
  addToolResult: (options: {
46
51
  toolCallId: string;
47
- result: unknown;
48
- }) => void;
52
+ result?: unknown;
53
+ error?: string;
54
+ }) => Promise<void>;
49
55
  clearError: () => void;
50
56
  isRestored: Ref<boolean>;
51
57
  }
@@ -5,7 +5,7 @@ import type { LLMProvider } from '../providers/types';
5
5
  export interface UseCompletionOptions {
6
6
  id?: string;
7
7
  provider: LLMProvider;
8
- model: string;
8
+ model: MaybeRefOrGetter<string>;
9
9
  system?: MaybeRefOrGetter<string | undefined>;
10
10
  onFinish?: (completion: string, context: {
11
11
  finishReason: FinishReason;
@@ -5,7 +5,7 @@ import type { LLMProvider } from '../providers/types';
5
5
  export interface UseObjectOptions<T> {
6
6
  id?: string;
7
7
  provider: LLMProvider;
8
- model: string;
8
+ model: MaybeRefOrGetter<string>;
9
9
  system?: MaybeRefOrGetter<string | undefined>;
10
10
  schema: Record<string, unknown>;
11
11
  onFinish?: (object: T, context: {
@@ -0,0 +1,51 @@
1
+ import { type Ref } from 'vue';
2
+ import type { ChatStatus } from '../types';
3
+ import type { SendMessageInput } from './use-chat';
4
+ export interface UsePromptInputOptions {
5
+ /** Submit on Enter; Shift+Enter inserts a newline. Default `true`. */
6
+ submitOnEnter?: boolean;
7
+ /** Grow the textarea with its content up to this many rows. Default `8`. */
8
+ maxRows?: number;
9
+ /** Accepted file types, as in `<input accept>` (e.g. `'image/*,.pdf'`). Default: any. */
10
+ accept?: string;
11
+ /** Maximum number of attached files. Default: unlimited. */
12
+ maxFiles?: number;
13
+ /** Called when files are rejected by `accept` or `maxFiles` */
14
+ onReject?: (files: File[], reason: 'type' | 'count') => void;
15
+ }
16
+ /** The parts of `useChat` the prompt input needs */
17
+ export interface PromptInputChat {
18
+ input: Ref<string>;
19
+ status: Ref<ChatStatus>;
20
+ sendMessage: (message?: SendMessageInput) => Promise<void>;
21
+ }
22
+ export interface UsePromptInputReturn {
23
+ /** Bind with `ref="textarea"` */
24
+ textarea: Ref<HTMLTextAreaElement | null>;
25
+ files: Ref<File[]>;
26
+ /** True while files are dragged over the drop zone */
27
+ isDragging: Ref<boolean>;
28
+ canSubmit: Ref<boolean>;
29
+ submit: () => Promise<void>;
30
+ addFiles: (files: FileList | File[] | null | undefined) => void;
31
+ removeFile: (file: File) => void;
32
+ /** Spread on the textarea: `v-bind="handlers"` (keydown, paste) */
33
+ handlers: {
34
+ onKeydown: (event: KeyboardEvent) => void;
35
+ onPaste: (event: ClipboardEvent) => void;
36
+ };
37
+ /** Spread on the drop zone: `v-bind="dropzone"` */
38
+ dropzone: {
39
+ onDragenter: (event: DragEvent) => void;
40
+ onDragover: (event: DragEvent) => void;
41
+ onDragleave: (event: DragEvent) => void;
42
+ onDrop: (event: DragEvent) => void;
43
+ };
44
+ /** Recalculate the textarea height */
45
+ resize: () => void;
46
+ }
47
+ /**
48
+ * Headless logic for a chat input: Enter to send, IME-safe, auto-growing textarea,
49
+ * attachments from the file picker, clipboard and drag-and-drop.
50
+ */
51
+ export declare function usePromptInput(chat: PromptInputChat, options?: UsePromptInputOptions): UsePromptInputReturn;