vue-llm 1.3.0 → 1.4.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.es.md +401 -0
- package/README.ja.md +401 -0
- package/README.md +18 -12
- package/README.pt-BR.md +401 -0
- package/README.ru.md +401 -0
- package/README.zh-CN.md +401 -0
- package/dist/devtools.cjs +1 -1
- package/dist/devtools.js +16 -16
- package/dist/nuxt.cjs +1 -1
- package/dist/nuxt.js +4 -3
- package/dist/providers/webllm.d.ts +14 -1
- package/dist/providers.cjs +5 -5
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +387 -352
- package/dist/server.d.ts +4 -0
- package/dist/utils/browser.d.ts +1 -0
- package/package.json +4 -2
package/README.es.md
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
# vue-llm
|
|
2
|
+
|
|
3
|
+
[English](./README.md) · [Русский](./README.ru.md) · [简体中文](./README.zh-CN.md) · [Português](./README.pt-BR.md) · **Español** · [日本語](./README.ja.md)
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/vue-llm)
|
|
6
|
+
[](https://www.npmjs.com/package/vue-llm)
|
|
7
|
+
[](https://github.com/dadashi44/vue-llm/actions/workflows/ci.yml)
|
|
8
|
+
[](./LICENSE)
|
|
9
|
+
|
|
10
|
+
**vue-llm** es el AI SDK para Vue y Nuxt: `useChat` con streaming, llamadas a herramientas, Generative UI y modelos en el navegador para OpenAI, Anthropic, Gemini, Ollama y WebGPU.
|
|
11
|
+
|
|
12
|
+
`useChat()` con streaming, llamadas a herramientas y varios proveedores, en 10 líneas de código.
|
|
13
|
+
|
|
14
|
+
**Documentación:** https://vue-llm.js.org/es/ · **[Pruébalo en el navegador](https://vue-llm.js.org/es/playground)**, sin API key
|
|
15
|
+
|
|
16
|
+
## Funciones
|
|
17
|
+
|
|
18
|
+
- **`useChat()`**: composable reactivo con streaming, cancelación y regeneración
|
|
19
|
+
- **Varios proveedores**: OpenAI, Anthropic, Gemini y Ollama listos para usar
|
|
20
|
+
- **Modelos en el navegador**: ejecuta Llama, Qwen o SmolLM sobre WebGPU con `createWebLLM`, sin servidor ni API key
|
|
21
|
+
- **Generative UI**: renderiza las llamadas a herramientas como tus componentes Vue con `<MessageParts>`, con argumentos en streaming e intervención humana
|
|
22
|
+
- **Llamadas a herramientas**: `defineTool` con `execute`, `onToolCall`, `addToolResult`
|
|
23
|
+
- **Adjuntos**: imágenes, PDF, audio y archivos de texto, adaptados a cada proveedor
|
|
24
|
+
- **Persistencia**: restaura el historial del chat desde localStorage o cualquier backend propio
|
|
25
|
+
- **Resiliencia**: reintentos con backoff exponencial y límites de peticiones en cliente y servidor
|
|
26
|
+
- **Plantillas de prompts**: `{{variables}}` con inferencia de tipos, plantillas de chat y `usePrompt` reactivo
|
|
27
|
+
- **Cualquier backend**: herramientas de servidor en `createLLMHandler` y `createSSEProvider` para tu propia API SSE
|
|
28
|
+
- **Streaming**: parser de SSE y deltas de texto, razonamiento y llamadas a herramientas
|
|
29
|
+
- **Seguridad**: la protección `dangerouslyAllowBrowser` mantiene a salvo las API keys
|
|
30
|
+
- **Chat UI**: un chat completo que es tuyo: `npx shadcn-vue add https://vue-llm.js.org/r/chat.json`, además de los headless `usePromptInput` y `useAutoScroll`
|
|
31
|
+
- **Vue DevTools**: una pestaña LLM con cada chat, línea de tiempo de peticiones, tiempo hasta el primer token, llamadas a herramientas y consumo de tokens (`vue-llm/devtools`)
|
|
32
|
+
- **Módulo de Nuxt**: auto-imports, componentes, DevTools en desarrollo y runtime config en el servidor
|
|
33
|
+
- **Cero dependencias en tiempo de ejecución**: solo `vue` como peer dependency (Vue 3.3+; los composables también en Vue 2.7)
|
|
34
|
+
- **TypeScript**: tipado completo y tipos exportados
|
|
35
|
+
|
|
36
|
+
## Inicio rápido
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm install vue-llm
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```vue
|
|
43
|
+
<script setup>
|
|
44
|
+
import { useChat } from 'vue-llm'
|
|
45
|
+
import { createOpenAI } from 'vue-llm/providers'
|
|
46
|
+
|
|
47
|
+
const ai = createOpenAI({
|
|
48
|
+
apiKey: 'sk-...',
|
|
49
|
+
dangerouslyAllowBrowser: true, // only for prototyping
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
const { messages, input, handleSubmit, isLoading } = useChat({
|
|
53
|
+
provider: ai,
|
|
54
|
+
model: 'gpt-4o',
|
|
55
|
+
})
|
|
56
|
+
</script>
|
|
57
|
+
|
|
58
|
+
<template>
|
|
59
|
+
<div v-for="msg in messages" :key="msg.id">
|
|
60
|
+
<strong>{{ msg.role }}:</strong>
|
|
61
|
+
<span v-for="(part, i) in msg.parts" :key="i">
|
|
62
|
+
<template v-if="part.type === 'text'">{{ part.text }}</template>
|
|
63
|
+
</span>
|
|
64
|
+
</div>
|
|
65
|
+
|
|
66
|
+
<form @submit.prevent="handleSubmit">
|
|
67
|
+
<input v-model="input" placeholder="Ask something..." />
|
|
68
|
+
<button :disabled="isLoading">Send</button>
|
|
69
|
+
</form>
|
|
70
|
+
</template>
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Proveedores
|
|
74
|
+
|
|
75
|
+
### OpenAI
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { createOpenAI } from 'vue-llm/providers'
|
|
79
|
+
|
|
80
|
+
const ai = createOpenAI({
|
|
81
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
82
|
+
})
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Anthropic
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { createAnthropic } from 'vue-llm/providers'
|
|
89
|
+
|
|
90
|
+
const ai = createAnthropic({
|
|
91
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
const { messages, sendMessage } = useChat({
|
|
95
|
+
provider: ai,
|
|
96
|
+
model: 'claude-sonnet-4-5',
|
|
97
|
+
})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Ollama (local)
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { createOllama } from 'vue-llm/providers'
|
|
104
|
+
|
|
105
|
+
const ai = createOllama() // localhost:11434 by default
|
|
106
|
+
|
|
107
|
+
const { messages, sendMessage } = useChat({
|
|
108
|
+
provider: ai,
|
|
109
|
+
model: 'llama3',
|
|
110
|
+
})
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### En el navegador (WebGPU)
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { CreateMLCEngine } from '@mlc-ai/web-llm' // npm i @mlc-ai/web-llm
|
|
117
|
+
import { createWebLLM } from 'vue-llm/providers'
|
|
118
|
+
|
|
119
|
+
const ai = createWebLLM({
|
|
120
|
+
createEngine: CreateMLCEngine,
|
|
121
|
+
onProgress: ({ progress }) => console.log(`${Math.round(progress * 100)}%`),
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
const { messages, sendMessage } = useChat({
|
|
125
|
+
provider: ai,
|
|
126
|
+
model: 'Llama-3.2-1B-Instruct-q4f16_1-MLC',
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
El modelo se ejecuta en la GPU del usuario y nada sale del dispositivo. Consulta [Modelos en el navegador](https://vue-llm.js.org/es/guide/in-browser).
|
|
131
|
+
|
|
132
|
+
## Llamadas a herramientas
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
const { messages, sendMessage } = useChat({
|
|
136
|
+
provider: ai,
|
|
137
|
+
model: 'gpt-4o',
|
|
138
|
+
tools: [
|
|
139
|
+
{
|
|
140
|
+
name: 'get_weather',
|
|
141
|
+
description: 'Get weather for a city',
|
|
142
|
+
parameters: {
|
|
143
|
+
type: 'object',
|
|
144
|
+
properties: {
|
|
145
|
+
city: { type: 'string', description: 'City name' },
|
|
146
|
+
},
|
|
147
|
+
required: ['city'],
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
],
|
|
151
|
+
onToolCall: async ({ toolName, args }) => {
|
|
152
|
+
if (toolName === 'get_weather') {
|
|
153
|
+
return { temperature: 22, condition: 'sunny' }
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
maxToolRoundtrips: 3,
|
|
157
|
+
})
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Adjuntos
|
|
161
|
+
|
|
162
|
+
Pasa objetos `File`, `FileList` o `FilePart` a `sendMessage`. Los archivos se leen como data URLs y se guardan como partes `file` en el mensaje del usuario.
|
|
163
|
+
|
|
164
|
+
```vue
|
|
165
|
+
<script setup lang="ts">
|
|
166
|
+
const { messages, input, sendMessage } = useChat({ provider: ai, model: 'gpt-4o' })
|
|
167
|
+
const files = ref<FileList>()
|
|
168
|
+
|
|
169
|
+
async function submit() {
|
|
170
|
+
await sendMessage({ text: input.value, files: files.value })
|
|
171
|
+
input.value = ''
|
|
172
|
+
files.value = undefined
|
|
173
|
+
}
|
|
174
|
+
</script>
|
|
175
|
+
|
|
176
|
+
<template>
|
|
177
|
+
<input type="file" multiple @change="files = ($event.target as HTMLInputElement).files ?? undefined">
|
|
178
|
+
<input v-model="input" @keydown.enter="submit">
|
|
179
|
+
</template>
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Las URLs remotas también funcionan: `sendMessage({ files: { type: 'file', mediaType: 'image/png', url: 'https://…' } })`.
|
|
183
|
+
|
|
184
|
+
| Proveedor | Imágenes | PDF | Audio | Texto | URLs remotas |
|
|
185
|
+
|----------|--------|-----|-------|------|-------------|
|
|
186
|
+
| OpenAI | ✓ | ✓ | wav, mp3 | insertado como texto | solo imágenes |
|
|
187
|
+
| Anthropic | ✓ | ✓ | — | ✓ (document) | imágenes, PDF |
|
|
188
|
+
| Google | ✓ | ✓ | ✓ | ✓ | URIs `fileData` |
|
|
189
|
+
| Ollama | ✓ | — | — | insertado como texto | — |
|
|
190
|
+
|
|
191
|
+
Las combinaciones no compatibles lanzan un error descriptivo antes de enviar la petición.
|
|
192
|
+
|
|
193
|
+
## Persistencia
|
|
194
|
+
|
|
195
|
+
Pasa un adaptador `storage` y un `id` estable: el historial se restaura al iniciar y se guarda cada vez que termina una respuesta.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { useChat, createWebStorage } from 'vue-llm'
|
|
199
|
+
|
|
200
|
+
const { messages, setMessages, isRestored } = useChat({
|
|
201
|
+
id: 'support-chat',
|
|
202
|
+
provider: ai,
|
|
203
|
+
model: 'gpt-4o',
|
|
204
|
+
storage: createWebStorage(), // localStorage, key `vue-llm:chat:support-chat`
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
setMessages([]) // clears history and removes the stored entry
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
`createWebStorage({ prefix, storage: sessionStorage })` personaliza la clave y el backend; `createMemoryStorage()` es útil para tests. Sirve cualquier objeto que implemente `ChatStorage`, síncrono o asíncrono:
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
const storage: ChatStorage = {
|
|
214
|
+
load: id => fetch(`/api/chats/${id}`).then(r => r.json()),
|
|
215
|
+
save: (id, messages) => fetch(`/api/chats/${id}`, { method: 'PUT', body: JSON.stringify(messages) }).then(() => {}),
|
|
216
|
+
remove: id => fetch(`/api/chats/${id}`, { method: 'DELETE' }).then(() => {}),
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Con almacenamiento asíncrono, `isRestored` es `false` hasta que `load` se resuelve. Los mensajes enviados antes se conservan: el historial guardado no los sobrescribe. Los errores de almacenamiento van a `onError`. Los adjuntos se guardan como data URLs, así que los archivos grandes pueden superar la cuota de ~5 MB de localStorage.
|
|
221
|
+
|
|
222
|
+
## Reintentos y límites de peticiones
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
import { wrapProvider, retryMiddleware, rateLimitMiddleware } from 'vue-llm'
|
|
226
|
+
|
|
227
|
+
const ai = wrapProvider(createOpenAI({ apiKey }), [
|
|
228
|
+
retryMiddleware({ maxRetries: 3, initialDelay: 1000, maxDelay: 30_000 }),
|
|
229
|
+
rateLimitMiddleware({ maxRequests: 20, interval: 60_000, maxConcurrent: 2 }),
|
|
230
|
+
])
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
`retryMiddleware` reenvía la petición ante errores 408, 409, 429, 5xx y de red con backoff exponencial (`initialDelay * factor^n`, con jitter), respetando `Retry-After` / `retry-after-ms`. Pasa `shouldRetry(error, attempt)` para personalizarlo y `onRetry` para observarlo. Solo se reintenta la petición inicial; los errores que llegan después de empezar el stream no.
|
|
234
|
+
|
|
235
|
+
`rateLimitMiddleware` encola las peticiones en el cliente: como máximo `maxRequests` por `interval` y `maxConcurrent` streams abiertos (un hueco se libera cuando el stream termina o se cancela). Cancelar una petición en cola la rechaza de inmediato.
|
|
236
|
+
|
|
237
|
+
Los proveedores lanzan `LLMAPIError` con `status`, `provider`, `body`, `retryAfter` e `isRetryable`:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { LLMAPIError } from 'vue-llm'
|
|
241
|
+
|
|
242
|
+
onError(error) {
|
|
243
|
+
if (error instanceof LLMAPIError && error.status === 429) showToast('Slow down')
|
|
244
|
+
}
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
En el servidor, `createLLMHandler` puede limitar las peticiones por cliente (identificado por defecto por `x-forwarded-for` / `x-real-ip`) y responde con `429` + `Retry-After`:
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
createLLMHandler({
|
|
251
|
+
provider,
|
|
252
|
+
rateLimit: { maxRequests: 10, interval: 60_000, key: req => req.headers.get('x-user-id') ?? 'anon' },
|
|
253
|
+
})
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
El limitador del servidor vive en memoria por instancia: en despliegues con varias instancias, pon delante del manejador un limitador compartido (p. ej., basado en Redis).
|
|
257
|
+
|
|
258
|
+
## Prompt de sistema
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
const { messages, sendMessage } = useChat({
|
|
262
|
+
provider: ai,
|
|
263
|
+
model: 'gpt-4o',
|
|
264
|
+
system: 'You are a helpful assistant that speaks like a pirate.',
|
|
265
|
+
})
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`system` también acepta un ref o un getter (en `useChat`, `useCompletion` y `useObject`) y se vuelve a leer en cada petición.
|
|
269
|
+
|
|
270
|
+
## Plantillas de prompts
|
|
271
|
+
|
|
272
|
+
Los nombres de las variables se infieren a partir del string de la plantilla, así que las variables que faltan o están mal escritas son errores de tipos:
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import { createPrompt, createChatPrompt, usePrompt } from 'vue-llm'
|
|
276
|
+
|
|
277
|
+
const translate = createPrompt('Translate {{ text }} to {{lang}}.', { defaults: { lang: 'English' } })
|
|
278
|
+
|
|
279
|
+
translate.render({ text: 'Hola' }) // 'Translate Hola to English.'
|
|
280
|
+
translate.render({ txt: 'Hola' }) // ✗ type error
|
|
281
|
+
translate.variables // ['text', 'lang']
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Los valores que faltan también lanzan un error en tiempo de ejecución. Escapa un placeholder con una barra invertida: `\{{literal}}`.
|
|
285
|
+
|
|
286
|
+
Prompts reactivos con `usePrompt`:
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
const lang = ref('French')
|
|
290
|
+
const system = usePrompt('Always reply in {{lang}}.', () => ({ lang: lang.value }))
|
|
291
|
+
|
|
292
|
+
const chat = useChat({ provider: ai, model: 'gpt-4o', system })
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
Plantillas de varios mensajes:
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
const tutor = createChatPrompt([
|
|
299
|
+
{ role: 'system', content: 'You are a {{level}} tutor.' },
|
|
300
|
+
{ role: 'user', content: 'Explain {{topic}}.' },
|
|
301
|
+
])
|
|
302
|
+
|
|
303
|
+
tutor.render({ level: 'patient', topic: 'recursion' }) // ChatMessage[] for provider.chat()
|
|
304
|
+
useChat({ provider: ai, model: 'gpt-4o', initialMessages: tutor.toUIMessages({ level: 'patient', topic: 'recursion' }) })
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## Referencia de la API
|
|
308
|
+
|
|
309
|
+
### `useChat(options)`
|
|
310
|
+
|
|
311
|
+
Devuelve una interfaz de chat reactiva.
|
|
312
|
+
|
|
313
|
+
**Opciones:**
|
|
314
|
+
|
|
315
|
+
| Opción | Tipo | Descripción |
|
|
316
|
+
|--------|------|-------------|
|
|
317
|
+
| `provider` | `LLMProvider` | Instancia del proveedor (obligatoria) |
|
|
318
|
+
| `model` | `string` | ID del modelo (obligatorio) |
|
|
319
|
+
| `system` | `MaybeRefOrGetter<string>` | Prompt de sistema |
|
|
320
|
+
| `tools` | `ToolDefinition[]` | Herramientas disponibles |
|
|
321
|
+
| `onToolCall` | `(call) => unknown` | Manejador de llamadas a herramientas |
|
|
322
|
+
| `onFinish` | `(msg, ctx) => void` | Se llama cuando termina la respuesta |
|
|
323
|
+
| `onError` | `(error) => void` | Manejador de errores |
|
|
324
|
+
| `maxToolRoundtrips` | `number` | Máximo de rondas de llamadas a herramientas (por defecto: 5) |
|
|
325
|
+
| `storage` | `ChatStorage` | Guarda y restaura los mensajes por `id` |
|
|
326
|
+
|
|
327
|
+
**Valores devueltos:**
|
|
328
|
+
|
|
329
|
+
| Propiedad | Tipo | Descripción |
|
|
330
|
+
|----------|------|-------------|
|
|
331
|
+
| `messages` | `Ref<UIMessage[]>` | Mensajes del chat |
|
|
332
|
+
| `status` | `Ref<ChatStatus>` | `'ready' \| 'submitted' \| 'streaming' \| 'error'` |
|
|
333
|
+
| `error` | `Ref<Error \| undefined>` | Último error |
|
|
334
|
+
| `input` | `Ref<string>` | Texto de entrada (v-model) |
|
|
335
|
+
| `isLoading` | `Ref<boolean>` | Si hay una petición activa |
|
|
336
|
+
| `sendMessage` | `(text? \| { text?, files? }) => Promise` | Envía un mensaje, opcionalmente con adjuntos |
|
|
337
|
+
| `stop` | `() => void` | Cancela el stream actual |
|
|
338
|
+
| `regenerate` | `() => Promise` | Elimina el último mensaje del asistente y lo genera de nuevo |
|
|
339
|
+
| `setMessages` | `(msgs) => void` | Reemplaza el historial de mensajes |
|
|
340
|
+
| `handleSubmit` | `(event?: Event) => void` | Manejador de envío del formulario (envía `input.value`) |
|
|
341
|
+
| `clearError` | `() => void` | Limpia el estado de error |
|
|
342
|
+
| `isRestored` | `Ref<boolean>` | `false` mientras carga el almacenamiento asíncrono |
|
|
343
|
+
|
|
344
|
+
## Módulo de Nuxt
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
// nuxt.config.ts
|
|
348
|
+
export default defineNuxtConfig({
|
|
349
|
+
modules: ['vue-llm/nuxt'],
|
|
350
|
+
runtimeConfig: {
|
|
351
|
+
vueLlm: {
|
|
352
|
+
openaiApiKey: '',
|
|
353
|
+
anthropicApiKey: '',
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
})
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
Los composables y las factorías de proveedores se importan automáticamente.
|
|
360
|
+
|
|
361
|
+
## Seguridad
|
|
362
|
+
|
|
363
|
+
Los proveedores lanzan un error si se usan en el navegador sin activarlo explícitamente:
|
|
364
|
+
|
|
365
|
+
```ts
|
|
366
|
+
// This will throw in browser:
|
|
367
|
+
const ai = createOpenAI({ apiKey: 'sk-...' })
|
|
368
|
+
|
|
369
|
+
// Opt-in for prototyping only:
|
|
370
|
+
const ai = createOpenAI({
|
|
371
|
+
apiKey: 'sk-...',
|
|
372
|
+
dangerouslyAllowBrowser: true,
|
|
373
|
+
})
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
En producción, haz de proxy de las llamadas a la API a través de tu servidor o usa el módulo de Nuxt con `runtimeConfig`.
|
|
377
|
+
|
|
378
|
+
## Formato de los mensajes
|
|
379
|
+
|
|
380
|
+
Los mensajes usan un formato basado en partes para contenido enriquecido:
|
|
381
|
+
|
|
382
|
+
```ts
|
|
383
|
+
interface UIMessage {
|
|
384
|
+
id: string
|
|
385
|
+
role: 'system' | 'user' | 'assistant'
|
|
386
|
+
parts: UIMessagePart[]
|
|
387
|
+
metadata?: Record<string, unknown>
|
|
388
|
+
createdAt?: Date
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
type UIMessagePart =
|
|
392
|
+
| { type: 'text'; text: string; state?: 'streaming' | 'done' }
|
|
393
|
+
| { type: 'reasoning'; text: string; state?: 'streaming' | 'done' }
|
|
394
|
+
| { type: 'tool-call'; toolCallId: string; toolName: string; args: unknown; state: 'streaming' | 'pending' | 'running' | 'result' | 'error'; result?: unknown; error?: string }
|
|
395
|
+
| { type: 'file'; mediaType: string; url: string; filename?: string }
|
|
396
|
+
| { type: 'source'; url: string; title?: string }
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
## Licencia
|
|
400
|
+
|
|
401
|
+
MIT
|