vue-llm 1.2.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 +48 -14
- package/README.pt-BR.md +401 -0
- package/README.ru.md +401 -0
- package/README.zh-CN.md +401 -0
- package/dist/components/MessageParts.vue.d.ts +33 -0
- package/dist/components.cjs +5 -5
- package/dist/components.d.ts +1 -0
- package/dist/components.js +146 -75
- package/dist/composables/use-auto-scroll.d.ts +17 -0
- package/dist/composables/use-chat.d.ts +11 -5
- package/dist/composables/use-completion.d.ts +1 -1
- package/dist/composables/use-object.d.ts +1 -1
- package/dist/composables/use-prompt-input.d.ts +51 -0
- package/dist/core/devtools.d.ts +86 -0
- package/dist/core/partial-json.d.ts +6 -0
- package/dist/core/stream-processor.d.ts +4 -0
- package/dist/devtools-C4JE26vO.cjs +1 -0
- package/dist/devtools-DnDvylCG.js +87 -0
- package/dist/devtools.cjs +1 -0
- package/dist/devtools.d.ts +15 -0
- package/dist/devtools.js +210 -0
- package/dist/index.cjs +3 -3
- package/dist/index.d.ts +7 -1
- package/dist/index.js +576 -441
- package/dist/nuxt.cjs +2 -1
- package/dist/nuxt.d.ts +4 -0
- package/dist/nuxt.js +34 -11
- package/dist/providers/webllm.d.ts +87 -0
- package/dist/providers.cjs +5 -4
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +529 -275
- package/dist/server.d.ts +4 -0
- package/dist/types.d.ts +37 -1
- package/dist/utils/browser.d.ts +1 -0
- package/dist/vue-llm.css +1 -1
- package/package.json +44 -5
package/README.pt-BR.md
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
# vue-llm
|
|
2
|
+
|
|
3
|
+
[English](./README.md) · [Русский](./README.ru.md) · [简体中文](./README.zh-CN.md) · **Português** · [Español](./README.es.md) · [日本語](./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** é o AI SDK para Vue e Nuxt: `useChat` com streaming, chamada de ferramentas, Generative UI e modelos no navegador para OpenAI, Anthropic, Gemini, Ollama e WebGPU.
|
|
11
|
+
|
|
12
|
+
`useChat()` com streaming, chamada de ferramentas e suporte a vários provedores — em 10 linhas de código.
|
|
13
|
+
|
|
14
|
+
**Documentação:** https://vue-llm.js.org/pt/ · **[Experimente no navegador](https://vue-llm.js.org/pt/playground)** — sem precisar de API key
|
|
15
|
+
|
|
16
|
+
## Recursos
|
|
17
|
+
|
|
18
|
+
- **`useChat()`** — composable reativo com streaming, abort e regenerate
|
|
19
|
+
- **Vários provedores** — OpenAI, Anthropic, Gemini e Ollama prontos para usar
|
|
20
|
+
- **Modelos no navegador** — rode Llama, Qwen ou SmolLM em WebGPU com `createWebLLM`, sem servidor nem API key
|
|
21
|
+
- **Generative UI** — renderize chamadas de ferramentas como seus componentes Vue com `<MessageParts>`, argumentos via streaming e human-in-the-loop
|
|
22
|
+
- **Chamada de ferramentas** — `defineTool` com `execute`, `onToolCall`, `addToolResult`
|
|
23
|
+
- **Anexos** — imagens, PDFs, áudio e arquivos de texto, convertidos para cada provedor
|
|
24
|
+
- **Persistência** — restaure o histórico do chat do localStorage ou de qualquer backend customizado
|
|
25
|
+
- **Resiliência** — retentativas com backoff exponencial, rate limiting no cliente e no servidor
|
|
26
|
+
- **Templates de prompt** — `{{variables}}` com inferência de tipos, templates de chat, `usePrompt` reativo
|
|
27
|
+
- **Qualquer backend** — ferramentas no servidor com `createLLMHandler`, `createSSEProvider` para a sua própria API SSE
|
|
28
|
+
- **Streaming** — parser de SSE, deltas de texto/raciocínio/chamadas de ferramentas
|
|
29
|
+
- **Segurança** — a proteção `dangerouslyAllowBrowser` protege as API keys
|
|
30
|
+
- **Chat UI** — um chat completo que é seu: `npx shadcn-vue add https://vue-llm.js.org/r/chat.json`, além dos headless `usePromptInput` e `useAutoScroll`
|
|
31
|
+
- **Vue DevTools** — uma aba LLM com todos os chats, linha do tempo das requisições, tempo até o primeiro token, chamadas de ferramentas e uso de tokens (`vue-llm/devtools`)
|
|
32
|
+
- **Módulo Nuxt** — auto-imports, componentes, DevTools em desenvolvimento, runtime config no servidor
|
|
33
|
+
- **Zero dependências de runtime** — só `vue` como peer dependency (Vue 3.3+, composables também no Vue 2.7)
|
|
34
|
+
- **TypeScript** — type safety completo, tipos exportados
|
|
35
|
+
|
|
36
|
+
## Início 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
|
+
## Provedores
|
|
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
|
+
### No 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
|
+
O modelo roda na GPU do usuário, e nada sai do dispositivo. Veja [Modelos no navegador](https://vue-llm.js.org/pt/guide/in-browser).
|
|
131
|
+
|
|
132
|
+
## Chamada de ferramentas
|
|
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
|
+
## Anexos
|
|
161
|
+
|
|
162
|
+
Passe objetos `File`, `FileList` ou `FilePart` para `sendMessage`. Os arquivos são lidos como data URLs e guardados como partes `file` na mensagem do usuário.
|
|
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
|
+
URLs remotas também funcionam: `sendMessage({ files: { type: 'file', mediaType: 'image/png', url: 'https://…' } })`.
|
|
183
|
+
|
|
184
|
+
| Provedor | Imagens | PDF | Áudio | Texto | URLs remotas |
|
|
185
|
+
|----------|--------|-----|-------|------|-------------|
|
|
186
|
+
| OpenAI | ✓ | ✓ | wav, mp3 | inline como texto | só imagens |
|
|
187
|
+
| Anthropic | ✓ | ✓ | — | ✓ (document) | imagens, PDF |
|
|
188
|
+
| Google | ✓ | ✓ | ✓ | ✓ | URIs `fileData` |
|
|
189
|
+
| Ollama | ✓ | — | — | inline como texto | — |
|
|
190
|
+
|
|
191
|
+
Combinações não suportadas lançam um erro descritivo antes de a requisição ser enviada.
|
|
192
|
+
|
|
193
|
+
## Persistência
|
|
194
|
+
|
|
195
|
+
Passe um adapter de `storage` e um `id` estável — o histórico é restaurado na inicialização e salvo sempre que uma resposta termina.
|
|
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 a chave e o backend; `createMemoryStorage()` é útil para testes. Qualquer objeto que implemente `ChatStorage` funciona, síncrono ou assí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
|
+
Com storage assíncrono, `isRestored` fica `false` até o `load` resolver. Mensagens enviadas antes disso são mantidas — o histórico salvo não as sobrescreve. Erros de storage vão para o `onError`. Os anexos são salvos como data URLs, então arquivos grandes podem estourar a cota de ~5 MB do localStorage.
|
|
221
|
+
|
|
222
|
+
## Retentativas e rate limiting
|
|
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
|
+
O `retryMiddleware` reenvia a requisição em caso de 408, 409, 429, 5xx e erros de rede, com backoff exponencial (`initialDelay * factor^n`, com jitter), respeitando `Retry-After` / `retry-after-ms`. Passe `shouldRetry(error, attempt)` para personalizar e `onRetry` para observar. Só a requisição inicial é repetida — erros depois que o stream começou não são.
|
|
234
|
+
|
|
235
|
+
O `rateLimitMiddleware` enfileira as requisições no cliente: no máximo `maxRequests` por `interval` e `maxConcurrent` streams abertos (um slot é liberado quando o stream termina ou é cancelado). Abortar uma requisição na fila a rejeita imediatamente.
|
|
236
|
+
|
|
237
|
+
Os provedores lançam `LLMAPIError` com `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
|
+
No servidor, o `createLLMHandler` pode limitar as requisições por cliente (identificado por `x-forwarded-for` / `x-real-ip` por padrão) e responde com `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
|
+
O limitador do servidor fica em memória, por instância — em deploys com várias instâncias, coloque um limitador compartilhado (por exemplo, baseado em Redis) na frente do handler.
|
|
257
|
+
|
|
258
|
+
## System prompt
|
|
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
|
+
O `system` também aceita um ref ou getter (no `useChat`, `useCompletion` e `useObject`) e é relido a cada requisição.
|
|
269
|
+
|
|
270
|
+
## Templates de prompt
|
|
271
|
+
|
|
272
|
+
Os nomes das variáveis são inferidos a partir da string do template, então variáveis ausentes ou com erro de digitação viram erros de tipo:
|
|
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
|
+
Valores ausentes também lançam erro em runtime. Escape um placeholder com barra invertida: `\{{literal}}`.
|
|
285
|
+
|
|
286
|
+
Prompts reativos com `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
|
+
Templates com várias mensagens:
|
|
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
|
+
## Referência da API
|
|
308
|
+
|
|
309
|
+
### `useChat(options)`
|
|
310
|
+
|
|
311
|
+
Retorna uma interface de chat reativa.
|
|
312
|
+
|
|
313
|
+
**Opções:**
|
|
314
|
+
|
|
315
|
+
| Opção | Tipo | Descrição |
|
|
316
|
+
|--------|------|-------------|
|
|
317
|
+
| `provider` | `LLMProvider` | Instância do provedor (obrigatório) |
|
|
318
|
+
| `model` | `string` | ID do modelo (obrigatório) |
|
|
319
|
+
| `system` | `MaybeRefOrGetter<string>` | System prompt |
|
|
320
|
+
| `tools` | `ToolDefinition[]` | Ferramentas disponíveis |
|
|
321
|
+
| `onToolCall` | `(call) => unknown` | Handler das chamadas de ferramentas |
|
|
322
|
+
| `onFinish` | `(msg, ctx) => void` | Chamado quando a resposta termina |
|
|
323
|
+
| `onError` | `(error) => void` | Handler de erros |
|
|
324
|
+
| `maxToolRoundtrips` | `number` | Máximo de rodadas de chamadas de ferramentas (padrão: 5) |
|
|
325
|
+
| `storage` | `ChatStorage` | Salva e restaura as mensagens pelo `id` |
|
|
326
|
+
|
|
327
|
+
**Retorno:**
|
|
328
|
+
|
|
329
|
+
| Propriedade | Tipo | Descrição |
|
|
330
|
+
|----------|------|-------------|
|
|
331
|
+
| `messages` | `Ref<UIMessage[]>` | Mensagens do chat |
|
|
332
|
+
| `status` | `Ref<ChatStatus>` | `'ready' \| 'submitted' \| 'streaming' \| 'error'` |
|
|
333
|
+
| `error` | `Ref<Error \| undefined>` | Último erro |
|
|
334
|
+
| `input` | `Ref<string>` | Texto do input (v-model) |
|
|
335
|
+
| `isLoading` | `Ref<boolean>` | Se há uma requisição em andamento |
|
|
336
|
+
| `sendMessage` | `(text? \| { text?, files? }) => Promise` | Envia uma mensagem, opcionalmente com anexos |
|
|
337
|
+
| `stop` | `() => void` | Aborta o stream atual |
|
|
338
|
+
| `regenerate` | `() => Promise` | Remove a última mensagem do assistente e gera de novo |
|
|
339
|
+
| `setMessages` | `(msgs) => void` | Substitui o histórico de mensagens |
|
|
340
|
+
| `handleSubmit` | `(event?: Event) => void` | Handler de submit do formulário (envia `input.value`) |
|
|
341
|
+
| `clearError` | `() => void` | Limpa o estado de erro |
|
|
342
|
+
| `isRestored` | `Ref<boolean>` | `false` enquanto o storage assíncrono carrega |
|
|
343
|
+
|
|
344
|
+
## Módulo 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
|
+
Os composables e as factories de provedores são importados automaticamente.
|
|
360
|
+
|
|
361
|
+
## Segurança
|
|
362
|
+
|
|
363
|
+
Os provedores lançam um erro se forem usados no navegador sem permissão explícita:
|
|
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
|
+
Em produção, faça proxy das chamadas à API pelo seu servidor ou use o módulo Nuxt com `runtimeConfig`.
|
|
377
|
+
|
|
378
|
+
## Formato das mensagens
|
|
379
|
+
|
|
380
|
+
As mensagens usam um formato baseado em partes para conteúdo rico:
|
|
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
|
+
## Licença
|
|
400
|
+
|
|
401
|
+
MIT
|