vue-llm 0.5.0 → 1.0.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 +146 -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 +553 -312
- package/dist/middleware.d.ts +23 -1
- package/dist/nuxt.cjs +1 -1
- package/dist/nuxt.js +11 -7
- package/dist/providers/types.d.ts +5 -0
- package/dist/providers.cjs +9 -7
- package/dist/providers.js +384 -286
- package/dist/server.cjs +4 -4
- package/dist/server.d.ts +6 -0
- package/dist/server.js +92 -65
- 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,17 @@ 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`
|
|
12
18
|
- **Streaming** — SSE parser, text/reasoning/tool-call deltas
|
|
13
19
|
- **Security** — `dangerouslyAllowBrowser` guard protects API keys
|
|
14
20
|
- **Nuxt module** — auto-imports, server-side runtime config
|
|
@@ -61,7 +67,6 @@ import { createOpenAI } from 'vue-llm/providers'
|
|
|
61
67
|
|
|
62
68
|
const ai = createOpenAI({
|
|
63
69
|
apiKey: process.env.OPENAI_API_KEY,
|
|
64
|
-
model: 'gpt-4o', // default model
|
|
65
70
|
})
|
|
66
71
|
```
|
|
67
72
|
|
|
@@ -121,6 +126,104 @@ const { messages, sendMessage } = useChat({
|
|
|
121
126
|
})
|
|
122
127
|
```
|
|
123
128
|
|
|
129
|
+
## Attachments
|
|
130
|
+
|
|
131
|
+
Pass `File`, `FileList` or `FilePart` objects to `sendMessage`. Files are read as data URLs and stored as `file` parts on the user message.
|
|
132
|
+
|
|
133
|
+
```vue
|
|
134
|
+
<script setup lang="ts">
|
|
135
|
+
const { messages, input, sendMessage } = useChat({ provider: ai, model: 'gpt-4o' })
|
|
136
|
+
const files = ref<FileList>()
|
|
137
|
+
|
|
138
|
+
async function submit() {
|
|
139
|
+
await sendMessage({ text: input.value, files: files.value })
|
|
140
|
+
input.value = ''
|
|
141
|
+
files.value = undefined
|
|
142
|
+
}
|
|
143
|
+
</script>
|
|
144
|
+
|
|
145
|
+
<template>
|
|
146
|
+
<input type="file" multiple @change="files = ($event.target as HTMLInputElement).files ?? undefined">
|
|
147
|
+
<input v-model="input" @keydown.enter="submit">
|
|
148
|
+
</template>
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Remote URLs work too: `sendMessage({ files: { type: 'file', mediaType: 'image/png', url: 'https://…' } })`.
|
|
152
|
+
|
|
153
|
+
| Provider | Images | PDF | Audio | Text | Remote URLs |
|
|
154
|
+
|----------|--------|-----|-------|------|-------------|
|
|
155
|
+
| OpenAI | ✓ | ✓ | wav, mp3 | inlined as text | images only |
|
|
156
|
+
| Anthropic | ✓ | ✓ | — | ✓ (document) | images, PDF |
|
|
157
|
+
| Google | ✓ | ✓ | ✓ | ✓ | `fileData` URIs |
|
|
158
|
+
| Ollama | ✓ | — | — | inlined as text | — |
|
|
159
|
+
|
|
160
|
+
Unsupported combinations throw a descriptive error before the request is sent.
|
|
161
|
+
|
|
162
|
+
## Persistence
|
|
163
|
+
|
|
164
|
+
Pass a `storage` adapter and a stable `id` — history is restored on init and saved whenever a response finishes.
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import { useChat, createWebStorage } from 'vue-llm'
|
|
168
|
+
|
|
169
|
+
const { messages, setMessages, isRestored } = useChat({
|
|
170
|
+
id: 'support-chat',
|
|
171
|
+
provider: ai,
|
|
172
|
+
model: 'gpt-4o',
|
|
173
|
+
storage: createWebStorage(), // localStorage, key `vue-llm:chat:support-chat`
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
setMessages([]) // clears history and removes the stored entry
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`createWebStorage({ prefix, storage: sessionStorage })` customizes the key and backend; `createMemoryStorage()` is handy for tests. Any object implementing `ChatStorage` works, sync or async:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
const storage: ChatStorage = {
|
|
183
|
+
load: id => fetch(`/api/chats/${id}`).then(r => r.json()),
|
|
184
|
+
save: (id, messages) => fetch(`/api/chats/${id}`, { method: 'PUT', body: JSON.stringify(messages) }).then(() => {}),
|
|
185
|
+
remove: id => fetch(`/api/chats/${id}`, { method: 'DELETE' }).then(() => {}),
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
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.
|
|
190
|
+
|
|
191
|
+
## Retries & Rate Limiting
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { wrapProvider, retryMiddleware, rateLimitMiddleware } from 'vue-llm'
|
|
195
|
+
|
|
196
|
+
const ai = wrapProvider(createOpenAI({ apiKey }), [
|
|
197
|
+
retryMiddleware({ maxRetries: 3, initialDelay: 1000, maxDelay: 30_000 }),
|
|
198
|
+
rateLimitMiddleware({ maxRequests: 20, interval: 60_000, maxConcurrent: 2 }),
|
|
199
|
+
])
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`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.
|
|
203
|
+
|
|
204
|
+
`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.
|
|
205
|
+
|
|
206
|
+
Providers throw `LLMAPIError` with `status`, `provider`, `body`, `retryAfter` and `isRetryable`:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
import { LLMAPIError } from 'vue-llm'
|
|
210
|
+
|
|
211
|
+
onError(error) {
|
|
212
|
+
if (error instanceof LLMAPIError && error.status === 429) showToast('Slow down')
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
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`:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
createLLMHandler({
|
|
220
|
+
provider,
|
|
221
|
+
rateLimit: { maxRequests: 10, interval: 60_000, key: req => req.headers.get('x-user-id') ?? 'anon' },
|
|
222
|
+
})
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
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.
|
|
226
|
+
|
|
124
227
|
## System Prompt
|
|
125
228
|
|
|
126
229
|
```ts
|
|
@@ -131,6 +234,45 @@ const { messages, sendMessage } = useChat({
|
|
|
131
234
|
})
|
|
132
235
|
```
|
|
133
236
|
|
|
237
|
+
`system` also accepts a ref or getter (in `useChat`, `useCompletion` and `useObject`) and is re-read on every request.
|
|
238
|
+
|
|
239
|
+
## Prompt Templates
|
|
240
|
+
|
|
241
|
+
Variable names are inferred from the template string, so missing or misspelled variables are type errors:
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
import { createPrompt, createChatPrompt, usePrompt } from 'vue-llm'
|
|
245
|
+
|
|
246
|
+
const translate = createPrompt('Translate {{ text }} to {{lang}}.', { defaults: { lang: 'English' } })
|
|
247
|
+
|
|
248
|
+
translate.render({ text: 'Hola' }) // 'Translate Hola to English.'
|
|
249
|
+
translate.render({ txt: 'Hola' }) // ✗ type error
|
|
250
|
+
translate.variables // ['text', 'lang']
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Missing values throw at runtime too. Escape a placeholder with a backslash: `\{{literal}}`.
|
|
254
|
+
|
|
255
|
+
Reactive prompts with `usePrompt`:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
const lang = ref('French')
|
|
259
|
+
const system = usePrompt('Always reply in {{lang}}.', () => ({ lang: lang.value }))
|
|
260
|
+
|
|
261
|
+
const chat = useChat({ provider: ai, model: 'gpt-4o', system })
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Multi-message templates:
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
const tutor = createChatPrompt([
|
|
268
|
+
{ role: 'system', content: 'You are a {{level}} tutor.' },
|
|
269
|
+
{ role: 'user', content: 'Explain {{topic}}.' },
|
|
270
|
+
])
|
|
271
|
+
|
|
272
|
+
tutor.render({ level: 'patient', topic: 'recursion' }) // ChatMessage[] for provider.chat()
|
|
273
|
+
useChat({ provider: ai, model: 'gpt-4o', initialMessages: tutor.toUIMessages({ level: 'patient', topic: 'recursion' }) })
|
|
274
|
+
```
|
|
275
|
+
|
|
134
276
|
## API Reference
|
|
135
277
|
|
|
136
278
|
### `useChat(options)`
|
|
@@ -149,6 +291,7 @@ Returns a reactive chat interface.
|
|
|
149
291
|
| `onFinish` | `(msg, ctx) => void` | Called when response completes |
|
|
150
292
|
| `onError` | `(error) => void` | Error handler |
|
|
151
293
|
| `maxToolRoundtrips` | `number` | Max tool call rounds (default: 5) |
|
|
294
|
+
| `storage` | `ChatStorage` | Persist and restore messages by `id` |
|
|
152
295
|
|
|
153
296
|
**Returns:**
|
|
154
297
|
|
|
@@ -159,12 +302,13 @@ Returns a reactive chat interface.
|
|
|
159
302
|
| `error` | `Ref<Error \| undefined>` | Last error |
|
|
160
303
|
| `input` | `Ref<string>` | Input text (v-model) |
|
|
161
304
|
| `isLoading` | `ComputedRef<boolean>` | Whether a request is active |
|
|
162
|
-
| `sendMessage` | `(text?) => Promise` | Send a message |
|
|
305
|
+
| `sendMessage` | `(text? \| { text?, files? }) => Promise` | Send a message, optionally with attachments |
|
|
163
306
|
| `stop` | `() => void` | Abort current stream |
|
|
164
307
|
| `regenerate` | `() => Promise` | Re-send last user message |
|
|
165
308
|
| `setMessages` | `(msgs) => void` | Replace message history |
|
|
166
309
|
| `handleSubmit` | `() => Promise` | Form submit handler (sends `input.value`) |
|
|
167
310
|
| `clearError` | `() => void` | Clear error state |
|
|
311
|
+
| `isRestored` | `Ref<boolean>` | `false` while async storage is loading |
|
|
168
312
|
|
|
169
313
|
## Nuxt Module
|
|
170
314
|
|
|
@@ -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
|
+
};
|