vue-llm 0.5.0 → 1.1.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 +147 -2
- package/dist/components/StreamMarkdown.vue.d.ts +1 -0
- package/dist/components.cjs +6 -1
- package/dist/components.d.ts +1 -0
- package/dist/components.js +125 -17
- package/dist/composables/use-chat.d.ts +11 -6
- package/dist/composables/use-completion.d.ts +2 -2
- package/dist/composables/use-object.d.ts +2 -2
- package/dist/composables/use-prompt.d.ts +3 -0
- package/dist/core/errors.d.ts +16 -0
- package/dist/core/markdown.d.ts +3 -0
- package/dist/core/prompt.d.ts +32 -0
- package/dist/core/storage.d.ts +15 -0
- package/dist/errors-B3A_zmVE.js +37 -0
- package/dist/errors-CVDNhYqZ.cjs +1 -0
- package/dist/file-DusIs8wR.cjs +1 -0
- package/dist/file-x_kW7BHa.js +49 -0
- package/dist/index.cjs +4 -2
- package/dist/index.d.ts +12 -4
- package/dist/index.js +556 -308
- package/dist/middleware.d.ts +23 -1
- package/dist/nuxt.cjs +1 -1
- package/dist/nuxt.js +11 -7
- package/dist/providers/sse.d.ts +18 -0
- package/dist/providers/types.d.ts +10 -0
- package/dist/providers.cjs +5 -7
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +350 -316
- package/dist/server.cjs +3 -4
- package/dist/server.d.ts +14 -1
- package/dist/server.js +134 -98
- package/dist/sse-DU5m1n6r.js +104 -0
- package/dist/sse-PZGBuYKy.cjs +2 -0
- package/dist/utils/file.d.ts +21 -0
- package/dist/vue-llm.css +1 -1
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -4,11 +4,18 @@ AI/LLM composables for Vue. The missing AI SDK for the Vue ecosystem.
|
|
|
4
4
|
|
|
5
5
|
`useChat()` with streaming, tool calling, multi-provider support — in 10 lines of code.
|
|
6
6
|
|
|
7
|
+
**Documentation:** https://dadashi44.github.io/vue-llm/
|
|
8
|
+
|
|
7
9
|
## Features
|
|
8
10
|
|
|
9
11
|
- **`useChat()`** — reactive composable with streaming, abort, regenerate
|
|
10
12
|
- **Multi-provider** — OpenAI, Anthropic, Ollama out of the box
|
|
11
13
|
- **Tool calling** — automatic roundtrips with `onToolCall` handler
|
|
14
|
+
- **Attachments** — images, PDFs, audio and text files, mapped per provider
|
|
15
|
+
- **Persistence** — restore chat history from localStorage or any custom backend
|
|
16
|
+
- **Resilience** — retries with exponential backoff, client and server rate limiting
|
|
17
|
+
- **Prompt templates** — `{{variables}}` with type inference, chat templates, reactive `usePrompt`
|
|
18
|
+
- **Any backend** — server-side tools in `createLLMHandler`, `createSSEProvider` for your own SSE API
|
|
12
19
|
- **Streaming** — SSE parser, text/reasoning/tool-call deltas
|
|
13
20
|
- **Security** — `dangerouslyAllowBrowser` guard protects API keys
|
|
14
21
|
- **Nuxt module** — auto-imports, server-side runtime config
|
|
@@ -61,7 +68,6 @@ import { createOpenAI } from 'vue-llm/providers'
|
|
|
61
68
|
|
|
62
69
|
const ai = createOpenAI({
|
|
63
70
|
apiKey: process.env.OPENAI_API_KEY,
|
|
64
|
-
model: 'gpt-4o', // default model
|
|
65
71
|
})
|
|
66
72
|
```
|
|
67
73
|
|
|
@@ -121,6 +127,104 @@ const { messages, sendMessage } = useChat({
|
|
|
121
127
|
})
|
|
122
128
|
```
|
|
123
129
|
|
|
130
|
+
## Attachments
|
|
131
|
+
|
|
132
|
+
Pass `File`, `FileList` or `FilePart` objects to `sendMessage`. Files are read as data URLs and stored as `file` parts on the user message.
|
|
133
|
+
|
|
134
|
+
```vue
|
|
135
|
+
<script setup lang="ts">
|
|
136
|
+
const { messages, input, sendMessage } = useChat({ provider: ai, model: 'gpt-4o' })
|
|
137
|
+
const files = ref<FileList>()
|
|
138
|
+
|
|
139
|
+
async function submit() {
|
|
140
|
+
await sendMessage({ text: input.value, files: files.value })
|
|
141
|
+
input.value = ''
|
|
142
|
+
files.value = undefined
|
|
143
|
+
}
|
|
144
|
+
</script>
|
|
145
|
+
|
|
146
|
+
<template>
|
|
147
|
+
<input type="file" multiple @change="files = ($event.target as HTMLInputElement).files ?? undefined">
|
|
148
|
+
<input v-model="input" @keydown.enter="submit">
|
|
149
|
+
</template>
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Remote URLs work too: `sendMessage({ files: { type: 'file', mediaType: 'image/png', url: 'https://…' } })`.
|
|
153
|
+
|
|
154
|
+
| Provider | Images | PDF | Audio | Text | Remote URLs |
|
|
155
|
+
|----------|--------|-----|-------|------|-------------|
|
|
156
|
+
| OpenAI | ✓ | ✓ | wav, mp3 | inlined as text | images only |
|
|
157
|
+
| Anthropic | ✓ | ✓ | — | ✓ (document) | images, PDF |
|
|
158
|
+
| Google | ✓ | ✓ | ✓ | ✓ | `fileData` URIs |
|
|
159
|
+
| Ollama | ✓ | — | — | inlined as text | — |
|
|
160
|
+
|
|
161
|
+
Unsupported combinations throw a descriptive error before the request is sent.
|
|
162
|
+
|
|
163
|
+
## Persistence
|
|
164
|
+
|
|
165
|
+
Pass a `storage` adapter and a stable `id` — history is restored on init and saved whenever a response finishes.
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { useChat, createWebStorage } from 'vue-llm'
|
|
169
|
+
|
|
170
|
+
const { messages, setMessages, isRestored } = useChat({
|
|
171
|
+
id: 'support-chat',
|
|
172
|
+
provider: ai,
|
|
173
|
+
model: 'gpt-4o',
|
|
174
|
+
storage: createWebStorage(), // localStorage, key `vue-llm:chat:support-chat`
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
setMessages([]) // clears history and removes the stored entry
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`createWebStorage({ prefix, storage: sessionStorage })` customizes the key and backend; `createMemoryStorage()` is handy for tests. Any object implementing `ChatStorage` works, sync or async:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
const storage: ChatStorage = {
|
|
184
|
+
load: id => fetch(`/api/chats/${id}`).then(r => r.json()),
|
|
185
|
+
save: (id, messages) => fetch(`/api/chats/${id}`, { method: 'PUT', body: JSON.stringify(messages) }).then(() => {}),
|
|
186
|
+
remove: id => fetch(`/api/chats/${id}`, { method: 'DELETE' }).then(() => {}),
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
With async storage, `isRestored` is `false` until `load` resolves. Messages sent before that are kept — stored history won't overwrite them. Storage errors go to `onError`. Attachments are stored as data URLs, so large files can exceed the ~5 MB localStorage quota.
|
|
191
|
+
|
|
192
|
+
## Retries & Rate Limiting
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
import { wrapProvider, retryMiddleware, rateLimitMiddleware } from 'vue-llm'
|
|
196
|
+
|
|
197
|
+
const ai = wrapProvider(createOpenAI({ apiKey }), [
|
|
198
|
+
retryMiddleware({ maxRetries: 3, initialDelay: 1000, maxDelay: 30_000 }),
|
|
199
|
+
rateLimitMiddleware({ maxRequests: 20, interval: 60_000, maxConcurrent: 2 }),
|
|
200
|
+
])
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
`retryMiddleware` re-sends the request on 408, 409, 429, 5xx and network errors with exponential backoff (`initialDelay * factor^n`, jittered), honoring `Retry-After` / `retry-after-ms`. Pass `shouldRetry(error, attempt)` to customize and `onRetry` to observe. Only the initial request is retried — errors after the stream has started are not.
|
|
204
|
+
|
|
205
|
+
`rateLimitMiddleware` queues requests client-side: at most `maxRequests` per `interval` and `maxConcurrent` open streams (a slot is freed when the stream ends or is cancelled). Aborting a queued request rejects it immediately.
|
|
206
|
+
|
|
207
|
+
Providers throw `LLMAPIError` with `status`, `provider`, `body`, `retryAfter` and `isRetryable`:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import { LLMAPIError } from 'vue-llm'
|
|
211
|
+
|
|
212
|
+
onError(error) {
|
|
213
|
+
if (error instanceof LLMAPIError && error.status === 429) showToast('Slow down')
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
On the server, `createLLMHandler` can limit requests per client (keyed by `x-forwarded-for` / `x-real-ip` by default) and responds with `429` + `Retry-After`:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
createLLMHandler({
|
|
221
|
+
provider,
|
|
222
|
+
rateLimit: { maxRequests: 10, interval: 60_000, key: req => req.headers.get('x-user-id') ?? 'anon' },
|
|
223
|
+
})
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
The server limiter is in-memory per instance — for multi-instance deployments put a shared limiter (e.g. Redis-backed) in front of the handler.
|
|
227
|
+
|
|
124
228
|
## System Prompt
|
|
125
229
|
|
|
126
230
|
```ts
|
|
@@ -131,6 +235,45 @@ const { messages, sendMessage } = useChat({
|
|
|
131
235
|
})
|
|
132
236
|
```
|
|
133
237
|
|
|
238
|
+
`system` also accepts a ref or getter (in `useChat`, `useCompletion` and `useObject`) and is re-read on every request.
|
|
239
|
+
|
|
240
|
+
## Prompt Templates
|
|
241
|
+
|
|
242
|
+
Variable names are inferred from the template string, so missing or misspelled variables are type errors:
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
import { createPrompt, createChatPrompt, usePrompt } from 'vue-llm'
|
|
246
|
+
|
|
247
|
+
const translate = createPrompt('Translate {{ text }} to {{lang}}.', { defaults: { lang: 'English' } })
|
|
248
|
+
|
|
249
|
+
translate.render({ text: 'Hola' }) // 'Translate Hola to English.'
|
|
250
|
+
translate.render({ txt: 'Hola' }) // ✗ type error
|
|
251
|
+
translate.variables // ['text', 'lang']
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Missing values throw at runtime too. Escape a placeholder with a backslash: `\{{literal}}`.
|
|
255
|
+
|
|
256
|
+
Reactive prompts with `usePrompt`:
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
const lang = ref('French')
|
|
260
|
+
const system = usePrompt('Always reply in {{lang}}.', () => ({ lang: lang.value }))
|
|
261
|
+
|
|
262
|
+
const chat = useChat({ provider: ai, model: 'gpt-4o', system })
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Multi-message templates:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
const tutor = createChatPrompt([
|
|
269
|
+
{ role: 'system', content: 'You are a {{level}} tutor.' },
|
|
270
|
+
{ role: 'user', content: 'Explain {{topic}}.' },
|
|
271
|
+
])
|
|
272
|
+
|
|
273
|
+
tutor.render({ level: 'patient', topic: 'recursion' }) // ChatMessage[] for provider.chat()
|
|
274
|
+
useChat({ provider: ai, model: 'gpt-4o', initialMessages: tutor.toUIMessages({ level: 'patient', topic: 'recursion' }) })
|
|
275
|
+
```
|
|
276
|
+
|
|
134
277
|
## API Reference
|
|
135
278
|
|
|
136
279
|
### `useChat(options)`
|
|
@@ -149,6 +292,7 @@ Returns a reactive chat interface.
|
|
|
149
292
|
| `onFinish` | `(msg, ctx) => void` | Called when response completes |
|
|
150
293
|
| `onError` | `(error) => void` | Error handler |
|
|
151
294
|
| `maxToolRoundtrips` | `number` | Max tool call rounds (default: 5) |
|
|
295
|
+
| `storage` | `ChatStorage` | Persist and restore messages by `id` |
|
|
152
296
|
|
|
153
297
|
**Returns:**
|
|
154
298
|
|
|
@@ -159,12 +303,13 @@ Returns a reactive chat interface.
|
|
|
159
303
|
| `error` | `Ref<Error \| undefined>` | Last error |
|
|
160
304
|
| `input` | `Ref<string>` | Input text (v-model) |
|
|
161
305
|
| `isLoading` | `ComputedRef<boolean>` | Whether a request is active |
|
|
162
|
-
| `sendMessage` | `(text?) => Promise` | Send a message |
|
|
306
|
+
| `sendMessage` | `(text? \| { text?, files? }) => Promise` | Send a message, optionally with attachments |
|
|
163
307
|
| `stop` | `() => void` | Abort current stream |
|
|
164
308
|
| `regenerate` | `() => Promise` | Re-send last user message |
|
|
165
309
|
| `setMessages` | `(msgs) => void` | Replace message history |
|
|
166
310
|
| `handleSubmit` | `() => Promise` | Form submit handler (sends `input.value`) |
|
|
167
311
|
| `clearError` | `() => void` | Clear error state |
|
|
312
|
+
| `isRestored` | `Ref<boolean>` | `false` while async storage is loading |
|
|
168
313
|
|
|
169
314
|
## Nuxt Module
|
|
170
315
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
type __VLS_Props = {
|
|
2
2
|
content: string;
|
|
3
3
|
streaming?: boolean;
|
|
4
|
+
render?: (markdown: string) => string;
|
|
4
5
|
};
|
|
5
6
|
declare const _default: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
|
|
6
7
|
export default _default;
|
package/dist/components.cjs
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function w(s){const e=s.replace(/\r\n?/g,`
|
|
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(/&/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;
|
package/dist/components.d.ts
CHANGED
package/dist/components.js
CHANGED
|
@@ -1,29 +1,137 @@
|
|
|
1
|
-
import { defineComponent as
|
|
2
|
-
const
|
|
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) {
|
|
4
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
5
|
+
}
|
|
6
|
+
function b(s) {
|
|
7
|
+
const e = s.replace(/\r\n?/g, `
|
|
8
|
+
`).split(`
|
|
9
|
+
`), n = [];
|
|
10
|
+
let t = 0;
|
|
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++;
|
|
17
|
+
t++;
|
|
18
|
+
const c = p[2] ? ` class="language-${g(p[2])}"` : "";
|
|
19
|
+
n.push(`<pre><code${c}>${g(o.join(`
|
|
20
|
+
`))}</code></pre>`);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (!a.trim()) {
|
|
24
|
+
t++;
|
|
25
|
+
continue;
|
|
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++;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(a)) {
|
|
34
|
+
n.push("<hr>"), t++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (/^\s*>/.test(a)) {
|
|
38
|
+
const o = [];
|
|
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(`
|
|
42
|
+
`))}</blockquote>`);
|
|
43
|
+
continue;
|
|
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" : "");
|
|
47
|
+
t += 2;
|
|
48
|
+
const i = [];
|
|
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}>`;
|
|
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>"
|
|
57
|
+
);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const u = /^\s*([-*+]|\d+[.)])\s+/.exec(a);
|
|
61
|
+
if (u) {
|
|
62
|
+
const o = /\d/.test(u[1]), c = [];
|
|
63
|
+
for (; t < e.length; ) {
|
|
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();
|
|
69
|
+
else
|
|
70
|
+
break;
|
|
71
|
+
t++;
|
|
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}>`);
|
|
75
|
+
continue;
|
|
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>`);
|
|
81
|
+
}
|
|
82
|
+
return n.join(`
|
|
83
|
+
`);
|
|
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("");
|
|
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>");
|
|
90
|
+
}
|
|
91
|
+
function k(s) {
|
|
92
|
+
const e = s.replace(/&/g, "&").replace(/&#(x?[0-9a-f]+);?/gi, "?");
|
|
93
|
+
return B.test(e.trim());
|
|
94
|
+
}
|
|
95
|
+
function f(s) {
|
|
96
|
+
return s.trim().replace(/^\||\|$/g, "").split("|").map((e) => e.trim());
|
|
97
|
+
}
|
|
98
|
+
function j(s, e) {
|
|
99
|
+
return s[e].includes("|") && e + 1 < s.length && /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(s[e + 1]);
|
|
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);
|
|
104
|
+
}
|
|
105
|
+
const T = ["innerHTML"], W = {
|
|
3
106
|
key: 0,
|
|
4
107
|
class: "vue-llm-cursor",
|
|
5
108
|
"aria-hidden": "true"
|
|
6
|
-
},
|
|
109
|
+
}, F = /* @__PURE__ */ v({
|
|
7
110
|
__name: "StreamMarkdown",
|
|
8
111
|
props: {
|
|
9
112
|
content: {},
|
|
10
|
-
streaming: { type: Boolean }
|
|
113
|
+
streaming: { type: Boolean },
|
|
114
|
+
render: { type: Function }
|
|
11
115
|
},
|
|
12
|
-
setup(
|
|
13
|
-
|
|
14
|
-
|
|
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", {
|
|
15
120
|
class: "vue-llm-markdown",
|
|
16
|
-
innerHTML:
|
|
17
|
-
}, null, 8,
|
|
18
|
-
|
|
121
|
+
innerHTML: n.value
|
|
122
|
+
}, null, 8, T),
|
|
123
|
+
s.streaming ? (w(), S("span", W, "▊")) : q("", !0)
|
|
19
124
|
], 64));
|
|
20
125
|
}
|
|
21
|
-
}),
|
|
22
|
-
const
|
|
23
|
-
for (const [
|
|
24
|
-
t
|
|
25
|
-
return
|
|
26
|
-
},
|
|
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"]]);
|
|
27
132
|
export {
|
|
28
|
-
|
|
133
|
+
C as StreamMarkdown,
|
|
134
|
+
g as escapeHTML,
|
|
135
|
+
d as renderInline,
|
|
136
|
+
b as renderMarkdown
|
|
29
137
|
};
|
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
import { type MaybeRef, type Ref } from 'vue';
|
|
1
|
+
import { type MaybeRef, type MaybeRefOrGetter, type Ref } from 'vue';
|
|
2
2
|
import type { ChatStatus, FinishReason, ToolDefinition, UIMessage, Usage } from '../types';
|
|
3
3
|
import type { LLMProvider } from '../providers/types';
|
|
4
|
+
import type { ChatStorage } from '../core/storage';
|
|
5
|
+
import { type FileInput } from '../utils/file';
|
|
6
|
+
export type SendMessageInput = string | {
|
|
7
|
+
text?: string;
|
|
8
|
+
files?: FileInput;
|
|
9
|
+
};
|
|
4
10
|
export interface UseChatOptions {
|
|
5
11
|
id?: string;
|
|
6
12
|
provider: LLMProvider;
|
|
7
13
|
model: string;
|
|
8
|
-
system?: string
|
|
14
|
+
system?: MaybeRefOrGetter<string | undefined>;
|
|
9
15
|
initialMessages?: UIMessage[];
|
|
10
16
|
body?: MaybeRef<Record<string, unknown>>;
|
|
11
17
|
providerOptions?: Record<string, unknown>;
|
|
@@ -21,6 +27,7 @@ export interface UseChatOptions {
|
|
|
21
27
|
}) => void;
|
|
22
28
|
onError?: (error: Error) => void;
|
|
23
29
|
maxToolRoundtrips?: number;
|
|
30
|
+
storage?: ChatStorage;
|
|
24
31
|
}
|
|
25
32
|
export interface UseChatReturn {
|
|
26
33
|
messages: Ref<UIMessage[]>;
|
|
@@ -28,10 +35,7 @@ export interface UseChatReturn {
|
|
|
28
35
|
error: Ref<Error | undefined>;
|
|
29
36
|
id: string;
|
|
30
37
|
input: Ref<string>;
|
|
31
|
-
sendMessage: (message?:
|
|
32
|
-
text?: string;
|
|
33
|
-
files?: File[];
|
|
34
|
-
}) => Promise<void>;
|
|
38
|
+
sendMessage: (message?: SendMessageInput) => Promise<void>;
|
|
35
39
|
regenerate: () => Promise<void>;
|
|
36
40
|
stop: () => void;
|
|
37
41
|
setMessages: (messages: UIMessage[] | ((prev: UIMessage[]) => UIMessage[])) => void;
|
|
@@ -42,5 +46,6 @@ export interface UseChatReturn {
|
|
|
42
46
|
result: unknown;
|
|
43
47
|
}) => void;
|
|
44
48
|
clearError: () => void;
|
|
49
|
+
isRestored: Ref<boolean>;
|
|
45
50
|
}
|
|
46
51
|
export declare function useChat(options: UseChatOptions): UseChatReturn;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type Ref } from 'vue';
|
|
1
|
+
import { type MaybeRefOrGetter, type Ref } from 'vue';
|
|
2
2
|
import type { ChatStatus, FinishReason, Usage } from '../types';
|
|
3
3
|
import type { LLMProvider } from '../providers/types';
|
|
4
4
|
export interface UseCompletionOptions {
|
|
5
5
|
id?: string;
|
|
6
6
|
provider: LLMProvider;
|
|
7
7
|
model: string;
|
|
8
|
-
system?: string
|
|
8
|
+
system?: MaybeRefOrGetter<string | undefined>;
|
|
9
9
|
onFinish?: (completion: string, context: {
|
|
10
10
|
finishReason: FinishReason;
|
|
11
11
|
usage?: Usage;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type Ref } from 'vue';
|
|
1
|
+
import { type MaybeRefOrGetter, type Ref } from 'vue';
|
|
2
2
|
import type { ChatStatus, FinishReason, Usage } from '../types';
|
|
3
3
|
import type { LLMProvider } from '../providers/types';
|
|
4
4
|
export interface UseObjectOptions<T> {
|
|
5
5
|
id?: string;
|
|
6
6
|
provider: LLMProvider;
|
|
7
7
|
model: string;
|
|
8
|
-
system?: string
|
|
8
|
+
system?: MaybeRefOrGetter<string | undefined>;
|
|
9
9
|
schema: Record<string, unknown>;
|
|
10
10
|
onFinish?: (object: T, context: {
|
|
11
11
|
finishReason: FinishReason;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type ComputedRef, type MaybeRefOrGetter } from 'vue';
|
|
2
|
+
import { type PromptInput, type PromptTemplate, type PromptVariables } from '../core/prompt';
|
|
3
|
+
export declare function usePrompt<const T extends string, D = object>(template: T | PromptTemplate<T, D>, variables: MaybeRefOrGetter<PromptInput<PromptVariables<T>, D>>): ComputedRef<string>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare class LLMAPIError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
readonly provider: string;
|
|
4
|
+
readonly body: string;
|
|
5
|
+
readonly retryAfter?: number;
|
|
6
|
+
constructor(options: {
|
|
7
|
+
message: string;
|
|
8
|
+
status: number;
|
|
9
|
+
provider: string;
|
|
10
|
+
body: string;
|
|
11
|
+
retryAfter?: number;
|
|
12
|
+
});
|
|
13
|
+
get isRetryable(): boolean;
|
|
14
|
+
}
|
|
15
|
+
export declare function createAPIError(provider: string, label: string, response: Response): Promise<LLMAPIError>;
|
|
16
|
+
export declare function parseRetryAfter(headers: Headers | undefined): number | undefined;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ChatMessage } from '../providers/types';
|
|
2
|
+
import type { UIMessage } from '../types';
|
|
3
|
+
export type PromptValue = string | number | boolean;
|
|
4
|
+
type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S;
|
|
5
|
+
export type PromptVariableNames<T extends string> = T extends `${string}{{${infer V}}}${infer Rest}` ? Trim<V> | PromptVariableNames<Rest> : never;
|
|
6
|
+
export type PromptVariables<T extends string> = string extends T ? Record<string, PromptValue> : [PromptVariableNames<T>] extends [never] ? Record<string, never> : {
|
|
7
|
+
[K in PromptVariableNames<T>]: PromptValue;
|
|
8
|
+
};
|
|
9
|
+
export interface PromptOptions<D> {
|
|
10
|
+
defaults?: D;
|
|
11
|
+
}
|
|
12
|
+
export type PromptInput<V, D> = Omit<V, keyof D> & Partial<V>;
|
|
13
|
+
export interface PromptTemplate<T extends string, D = object> {
|
|
14
|
+
readonly template: T;
|
|
15
|
+
readonly variables: string[];
|
|
16
|
+
render(variables: PromptInput<PromptVariables<T>, D>): string;
|
|
17
|
+
}
|
|
18
|
+
export declare function createPrompt<const T extends string, const D extends Partial<PromptVariables<T>> = object>(template: T, options?: PromptOptions<D>): PromptTemplate<T, D>;
|
|
19
|
+
export interface ChatPromptMessage {
|
|
20
|
+
role: 'system' | 'user' | 'assistant';
|
|
21
|
+
content: string;
|
|
22
|
+
}
|
|
23
|
+
type ChatPromptVariables<T extends readonly ChatPromptMessage[]> = PromptVariables<T[number]['content']>;
|
|
24
|
+
export interface ChatPromptTemplate<T extends readonly ChatPromptMessage[], D = object> {
|
|
25
|
+
readonly messages: T;
|
|
26
|
+
readonly variables: string[];
|
|
27
|
+
render(variables: PromptInput<ChatPromptVariables<T>, D>): ChatMessage[];
|
|
28
|
+
toUIMessages(variables: PromptInput<ChatPromptVariables<T>, D>): UIMessage[];
|
|
29
|
+
}
|
|
30
|
+
export declare function createChatPrompt<const T extends readonly ChatPromptMessage[], const D extends Partial<ChatPromptVariables<T>> = object>(messages: T, options?: PromptOptions<D>): ChatPromptTemplate<T, D>;
|
|
31
|
+
export declare function renderTemplate(template: string, variables: Record<string, PromptValue | undefined>): string;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { UIMessage } from '../types';
|
|
2
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
3
|
+
export interface ChatStorage {
|
|
4
|
+
load(id: string): MaybePromise<UIMessage[] | null | undefined>;
|
|
5
|
+
save(id: string, messages: UIMessage[]): MaybePromise<void>;
|
|
6
|
+
remove(id: string): MaybePromise<void>;
|
|
7
|
+
}
|
|
8
|
+
export interface WebStorageOptions {
|
|
9
|
+
prefix?: string;
|
|
10
|
+
storage?: Storage;
|
|
11
|
+
}
|
|
12
|
+
export declare function createWebStorage(options?: WebStorageOptions): ChatStorage;
|
|
13
|
+
export declare function createMemoryStorage(): ChatStorage;
|
|
14
|
+
export declare function deserializeMessages(raw: string): UIMessage[];
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
class u extends Error {
|
|
2
|
+
status;
|
|
3
|
+
provider;
|
|
4
|
+
body;
|
|
5
|
+
retryAfter;
|
|
6
|
+
constructor(t) {
|
|
7
|
+
super(t.message), this.name = "LLMAPIError", this.status = t.status, this.provider = t.provider, this.body = t.body, this.retryAfter = t.retryAfter;
|
|
8
|
+
}
|
|
9
|
+
get isRetryable() {
|
|
10
|
+
return this.status === 408 || this.status === 409 || this.status === 429 || this.status >= 500;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
async function n(e, t, r) {
|
|
14
|
+
const s = await r.text();
|
|
15
|
+
return new u({
|
|
16
|
+
message: `[vue-llm] ${t} error ${r.status}: ${s}`,
|
|
17
|
+
status: r.status,
|
|
18
|
+
provider: e,
|
|
19
|
+
body: s,
|
|
20
|
+
retryAfter: i(r.headers)
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function i(e) {
|
|
24
|
+
if (!e) return;
|
|
25
|
+
const t = e.get("retry-after-ms");
|
|
26
|
+
if (t && !Number.isNaN(Number(t))) return Number(t);
|
|
27
|
+
const r = e.get("retry-after");
|
|
28
|
+
if (!r) return;
|
|
29
|
+
const s = Number(r);
|
|
30
|
+
if (!Number.isNaN(s)) return s * 1e3;
|
|
31
|
+
const a = Date.parse(r);
|
|
32
|
+
return Number.isNaN(a) ? void 0 : Math.max(0, a - Date.now());
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
u as L,
|
|
36
|
+
n as c
|
|
37
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";class u extends Error{status;provider;body;retryAfter;constructor(r){super(r.message),this.name="LLMAPIError",this.status=r.status,this.provider=r.provider,this.body=r.body,this.retryAfter=r.retryAfter}get isRetryable(){return this.status===408||this.status===409||this.status===429||this.status>=500}}async function i(e,r,t){const s=await t.text();return new u({message:`[vue-llm] ${r} error ${t.status}: ${s}`,status:t.status,provider:e,body:s,retryAfter:o(t.headers)})}function o(e){if(!e)return;const r=e.get("retry-after-ms");if(r&&!Number.isNaN(Number(r)))return Number(r);const t=e.get("retry-after");if(!t)return;const s=Number(t);if(!Number.isNaN(s))return s*1e3;const a=Date.parse(t);return Number.isNaN(a)?void 0:Math.max(0,a-Date.now())}exports.LLMAPIError=u;exports.createAPIError=i;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";function n(e){return new Promise((r,t)=>{const a=new FileReader;a.onload=()=>r(a.result),a.onerror=()=>t(a.error??new Error("[vue-llm] Failed to read file")),a.readAsDataURL(e)})}async function i(e){if(!e)return[];const r=d(e)?Array.from(e):Array.isArray(e)?e:[e];return Promise.all(r.map(async t=>f(t)?t:{type:"file",mediaType:t.type||"application/octet-stream",url:await n(t),filename:t.name}))}function o(e){const r=l(e.url);return{url:e.url,mediaType:e.mediaType??r?.mediaType??"image/png",filename:e.filename,base64:r?.data}}function s(e){return e.startsWith("text/")||e==="application/json"}function l(e){const r=/^data:([^;,]*)(?:;[^,]*)?;base64,(.*)$/s.exec(e);return r?{mediaType:r[1]||"application/octet-stream",data:r[2]}:null}function c(e){const r=atob(e),t=Uint8Array.from(r,a=>a.charCodeAt(0));return new TextDecoder().decode(t)}function d(e){return typeof FileList<"u"&&e instanceof FileList}function f(e){return e.type==="file"&&typeof e.url=="string"}exports.convertFilesToParts=i;exports.decodeBase64Text=c;exports.fileToDataURL=n;exports.isTextMediaType=s;exports.resolveFilePart=o;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function n(e) {
|
|
2
|
+
return new Promise((r, a) => {
|
|
3
|
+
const t = new FileReader();
|
|
4
|
+
t.onload = () => r(t.result), t.onerror = () => a(t.error ?? new Error("[vue-llm] Failed to read file")), t.readAsDataURL(e);
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
async function l(e) {
|
|
8
|
+
if (!e) return [];
|
|
9
|
+
const r = o(e) ? Array.from(e) : Array.isArray(e) ? e : [e];
|
|
10
|
+
return Promise.all(r.map(async (a) => s(a) ? a : {
|
|
11
|
+
type: "file",
|
|
12
|
+
mediaType: a.type || "application/octet-stream",
|
|
13
|
+
url: await n(a),
|
|
14
|
+
filename: a.name
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
17
|
+
function c(e) {
|
|
18
|
+
const r = i(e.url);
|
|
19
|
+
return {
|
|
20
|
+
url: e.url,
|
|
21
|
+
mediaType: e.mediaType ?? r?.mediaType ?? "image/png",
|
|
22
|
+
filename: e.filename,
|
|
23
|
+
base64: r?.data
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function f(e) {
|
|
27
|
+
return e.startsWith("text/") || e === "application/json";
|
|
28
|
+
}
|
|
29
|
+
function i(e) {
|
|
30
|
+
const r = /^data:([^;,]*)(?:;[^,]*)?;base64,(.*)$/s.exec(e);
|
|
31
|
+
return r ? { mediaType: r[1] || "application/octet-stream", data: r[2] } : null;
|
|
32
|
+
}
|
|
33
|
+
function d(e) {
|
|
34
|
+
const r = atob(e), a = Uint8Array.from(r, (t) => t.charCodeAt(0));
|
|
35
|
+
return new TextDecoder().decode(a);
|
|
36
|
+
}
|
|
37
|
+
function o(e) {
|
|
38
|
+
return typeof FileList < "u" && e instanceof FileList;
|
|
39
|
+
}
|
|
40
|
+
function s(e) {
|
|
41
|
+
return e.type === "file" && typeof e.url == "string";
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
l as c,
|
|
45
|
+
d,
|
|
46
|
+
n as f,
|
|
47
|
+
f as i,
|
|
48
|
+
c as r
|
|
49
|
+
};
|