vue-llm 0.0.0-stage → 0.1.5
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/LICENSE +21 -0
- package/README.md +221 -2
- package/dist/components/StreamMarkdown.vue.d.ts +6 -0
- package/dist/components.cjs +1 -0
- package/dist/components.d.ts +1 -0
- package/dist/components.js +29 -0
- package/dist/composables/use-chat.d.ts +46 -0
- package/dist/core/sse-parser.d.ts +9 -0
- package/dist/core/stream-processor.d.ts +37 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +236 -0
- package/dist/nuxt.cjs +1 -0
- package/dist/nuxt.d.ts +2 -0
- package/dist/nuxt.js +26 -0
- package/dist/providers/anthropic.d.ts +7 -0
- package/dist/providers/ollama.d.ts +5 -0
- package/dist/providers/openai.d.ts +7 -0
- package/dist/providers/types.d.ts +66 -0
- package/dist/providers.cjs +6 -0
- package/dist/providers.d.ts +6 -0
- package/dist/providers.js +399 -0
- package/dist/types.d.ts +50 -0
- package/dist/utils/generate-id.d.ts +1 -0
- package/dist/vue-llm.css +1 -0
- package/package.json +96 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dadashi44
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,222 @@
|
|
|
1
|
-
#
|
|
1
|
+
# vue-llm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AI/LLM composables for Vue. The missing AI SDK for the Vue ecosystem.
|
|
4
|
+
|
|
5
|
+
`useChat()` with streaming, tool calling, multi-provider support — in 10 lines of code.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **`useChat()`** — reactive composable with streaming, abort, regenerate
|
|
10
|
+
- **Multi-provider** — OpenAI, Anthropic, Ollama out of the box
|
|
11
|
+
- **Tool calling** — automatic roundtrips with `onToolCall` handler
|
|
12
|
+
- **Streaming** — SSE parser, text/reasoning/tool-call deltas
|
|
13
|
+
- **Security** — `dangerouslyAllowBrowser` guard protects API keys
|
|
14
|
+
- **Nuxt module** — auto-imports, server-side runtime config
|
|
15
|
+
- **Zero runtime deps** — only `vue` as peer dependency
|
|
16
|
+
- **TypeScript** — full type safety, exported types
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install vue-llm
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```vue
|
|
25
|
+
<script setup>
|
|
26
|
+
import { useChat } from 'vue-llm'
|
|
27
|
+
import { createOpenAI } from 'vue-llm/providers'
|
|
28
|
+
|
|
29
|
+
const ai = createOpenAI({
|
|
30
|
+
apiKey: 'sk-...',
|
|
31
|
+
dangerouslyAllowBrowser: true, // only for prototyping
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const { messages, input, handleSubmit, isLoading } = useChat({
|
|
35
|
+
provider: ai,
|
|
36
|
+
model: 'gpt-4o',
|
|
37
|
+
})
|
|
38
|
+
</script>
|
|
39
|
+
|
|
40
|
+
<template>
|
|
41
|
+
<div v-for="msg in messages" :key="msg.id">
|
|
42
|
+
<strong>{{ msg.role }}:</strong>
|
|
43
|
+
<span v-for="(part, i) in msg.parts" :key="i">
|
|
44
|
+
<template v-if="part.type === 'text'">{{ part.text }}</template>
|
|
45
|
+
</span>
|
|
46
|
+
</div>
|
|
47
|
+
|
|
48
|
+
<form @submit.prevent="handleSubmit">
|
|
49
|
+
<input v-model="input" placeholder="Ask something..." />
|
|
50
|
+
<button :disabled="isLoading">Send</button>
|
|
51
|
+
</form>
|
|
52
|
+
</template>
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Providers
|
|
56
|
+
|
|
57
|
+
### OpenAI
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { createOpenAI } from 'vue-llm/providers'
|
|
61
|
+
|
|
62
|
+
const ai = createOpenAI({
|
|
63
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
64
|
+
model: 'gpt-4o', // default model
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Anthropic
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { createAnthropic } from 'vue-llm/providers'
|
|
72
|
+
|
|
73
|
+
const ai = createAnthropic({
|
|
74
|
+
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const { messages, sendMessage } = useChat({
|
|
78
|
+
provider: ai,
|
|
79
|
+
model: 'claude-sonnet-4-20250514',
|
|
80
|
+
})
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Ollama (local)
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { createOllama } from 'vue-llm/providers'
|
|
87
|
+
|
|
88
|
+
const ai = createOllama() // localhost:11434 by default
|
|
89
|
+
|
|
90
|
+
const { messages, sendMessage } = useChat({
|
|
91
|
+
provider: ai,
|
|
92
|
+
model: 'llama3',
|
|
93
|
+
})
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Tool Calling
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const { messages, sendMessage } = useChat({
|
|
100
|
+
provider: ai,
|
|
101
|
+
model: 'gpt-4o',
|
|
102
|
+
tools: [
|
|
103
|
+
{
|
|
104
|
+
name: 'get_weather',
|
|
105
|
+
description: 'Get weather for a city',
|
|
106
|
+
parameters: {
|
|
107
|
+
type: 'object',
|
|
108
|
+
properties: {
|
|
109
|
+
city: { type: 'string', description: 'City name' },
|
|
110
|
+
},
|
|
111
|
+
required: ['city'],
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
onToolCall: async ({ toolName, args }) => {
|
|
116
|
+
if (toolName === 'get_weather') {
|
|
117
|
+
return { temperature: 22, condition: 'sunny' }
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
maxToolRoundtrips: 3,
|
|
121
|
+
})
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## System Prompt
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
const { messages, sendMessage } = useChat({
|
|
128
|
+
provider: ai,
|
|
129
|
+
model: 'gpt-4o',
|
|
130
|
+
system: 'You are a helpful assistant that speaks like a pirate.',
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## API Reference
|
|
135
|
+
|
|
136
|
+
### `useChat(options)`
|
|
137
|
+
|
|
138
|
+
Returns a reactive chat interface.
|
|
139
|
+
|
|
140
|
+
**Options:**
|
|
141
|
+
|
|
142
|
+
| Option | Type | Description |
|
|
143
|
+
|--------|------|-------------|
|
|
144
|
+
| `provider` | `LLMProvider` | Provider instance (required) |
|
|
145
|
+
| `model` | `string` | Model ID (required) |
|
|
146
|
+
| `system` | `string` | System prompt |
|
|
147
|
+
| `tools` | `ToolDefinition[]` | Available tools |
|
|
148
|
+
| `onToolCall` | `(call) => unknown` | Tool call handler |
|
|
149
|
+
| `onFinish` | `(msg, ctx) => void` | Called when response completes |
|
|
150
|
+
| `onError` | `(error) => void` | Error handler |
|
|
151
|
+
| `maxToolRoundtrips` | `number` | Max tool call rounds (default: 5) |
|
|
152
|
+
|
|
153
|
+
**Returns:**
|
|
154
|
+
|
|
155
|
+
| Property | Type | Description |
|
|
156
|
+
|----------|------|-------------|
|
|
157
|
+
| `messages` | `Ref<UIMessage[]>` | Chat messages |
|
|
158
|
+
| `status` | `Ref<ChatStatus>` | `'ready' \| 'submitted' \| 'streaming' \| 'error'` |
|
|
159
|
+
| `error` | `Ref<Error \| undefined>` | Last error |
|
|
160
|
+
| `input` | `Ref<string>` | Input text (v-model) |
|
|
161
|
+
| `isLoading` | `ComputedRef<boolean>` | Whether a request is active |
|
|
162
|
+
| `sendMessage` | `(text?) => Promise` | Send a message |
|
|
163
|
+
| `stop` | `() => void` | Abort current stream |
|
|
164
|
+
| `regenerate` | `() => Promise` | Re-send last user message |
|
|
165
|
+
| `setMessages` | `(msgs) => void` | Replace message history |
|
|
166
|
+
| `handleSubmit` | `() => Promise` | Form submit handler (sends `input.value`) |
|
|
167
|
+
| `clearError` | `() => void` | Clear error state |
|
|
168
|
+
|
|
169
|
+
## Nuxt Module
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
// nuxt.config.ts
|
|
173
|
+
export default defineNuxtConfig({
|
|
174
|
+
modules: ['vue-llm/nuxt'],
|
|
175
|
+
runtimeConfig: {
|
|
176
|
+
vueLlm: {
|
|
177
|
+
openaiApiKey: '',
|
|
178
|
+
anthropicApiKey: '',
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
})
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Composables and provider factories are auto-imported.
|
|
185
|
+
|
|
186
|
+
## Security
|
|
187
|
+
|
|
188
|
+
Providers throw an error if used in the browser without explicit opt-in:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// This will throw in browser:
|
|
192
|
+
const ai = createOpenAI({ apiKey: 'sk-...' })
|
|
193
|
+
|
|
194
|
+
// Opt-in for prototyping only:
|
|
195
|
+
const ai = createOpenAI({
|
|
196
|
+
apiKey: 'sk-...',
|
|
197
|
+
dangerouslyAllowBrowser: true,
|
|
198
|
+
})
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
For production, proxy API calls through your server or use the Nuxt module with `runtimeConfig`.
|
|
202
|
+
|
|
203
|
+
## Message Format
|
|
204
|
+
|
|
205
|
+
Messages use a parts-based format for rich content:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
interface UIMessage {
|
|
209
|
+
id: string
|
|
210
|
+
role: 'user' | 'assistant'
|
|
211
|
+
parts: UIMessagePart[]
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
type UIMessagePart =
|
|
215
|
+
| { type: 'text'; text: string; state: 'streaming' | 'done' }
|
|
216
|
+
| { type: 'reasoning'; text: string; state: 'streaming' | 'done' }
|
|
217
|
+
| { type: 'tool-call'; toolCallId: string; toolName: string; args: unknown; state: string }
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## License
|
|
221
|
+
|
|
222
|
+
MIT
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
type __VLS_Props = {
|
|
2
|
+
content: string;
|
|
3
|
+
streaming?: boolean;
|
|
4
|
+
};
|
|
5
|
+
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
|
+
export default _default;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),c=["innerHTML"],s={key:0,class:"vue-llm-cursor","aria-hidden":"true"},l=e.defineComponent({__name:"StreamMarkdown",props:{content:{},streaming:{type:Boolean}},setup(t){return(o,n)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createElementVNode("div",{class:"vue-llm-markdown",innerHTML:t.content},null,8,c),t.streaming?(e.openBlock(),e.createElementBlock("span",s,"▊")):e.createCommentVNode("",!0)],64))}}),m=(t,o)=>{const n=t.__vccOpts||t;for(const[r,a]of o)n[r]=a;return n},d=m(l,[["__scopeId","data-v-189a3a91"]]);exports.StreamMarkdown=d;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default as StreamMarkdown } from './components/StreamMarkdown.vue';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { defineComponent as s, openBlock as o, createElementBlock as r, Fragment as m, createElementVNode as l, createCommentVNode as _ } from "vue";
|
|
2
|
+
const d = ["innerHTML"], i = {
|
|
3
|
+
key: 0,
|
|
4
|
+
class: "vue-llm-cursor",
|
|
5
|
+
"aria-hidden": "true"
|
|
6
|
+
}, u = /* @__PURE__ */ s({
|
|
7
|
+
__name: "StreamMarkdown",
|
|
8
|
+
props: {
|
|
9
|
+
content: {},
|
|
10
|
+
streaming: { type: Boolean }
|
|
11
|
+
},
|
|
12
|
+
setup(e) {
|
|
13
|
+
return (n, t) => (o(), r(m, null, [
|
|
14
|
+
l("div", {
|
|
15
|
+
class: "vue-llm-markdown",
|
|
16
|
+
innerHTML: e.content
|
|
17
|
+
}, null, 8, d),
|
|
18
|
+
e.streaming ? (o(), r("span", i, "▊")) : _("", !0)
|
|
19
|
+
], 64));
|
|
20
|
+
}
|
|
21
|
+
}), p = (e, n) => {
|
|
22
|
+
const t = e.__vccOpts || e;
|
|
23
|
+
for (const [a, c] of n)
|
|
24
|
+
t[a] = c;
|
|
25
|
+
return t;
|
|
26
|
+
}, v = /* @__PURE__ */ p(u, [["__scopeId", "data-v-189a3a91"]]);
|
|
27
|
+
export {
|
|
28
|
+
v as StreamMarkdown
|
|
29
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type MaybeRef, type Ref } from 'vue';
|
|
2
|
+
import type { ChatStatus, FinishReason, ToolDefinition, UIMessage, Usage } from '../types';
|
|
3
|
+
import type { LLMProvider } from '../providers/types';
|
|
4
|
+
export interface UseChatOptions {
|
|
5
|
+
id?: string;
|
|
6
|
+
provider: LLMProvider;
|
|
7
|
+
model: string;
|
|
8
|
+
system?: string;
|
|
9
|
+
initialMessages?: UIMessage[];
|
|
10
|
+
body?: MaybeRef<Record<string, unknown>>;
|
|
11
|
+
providerOptions?: Record<string, unknown>;
|
|
12
|
+
tools?: ToolDefinition[];
|
|
13
|
+
onToolCall?: (toolCall: {
|
|
14
|
+
toolCallId: string;
|
|
15
|
+
toolName: string;
|
|
16
|
+
args: unknown;
|
|
17
|
+
}) => unknown | Promise<unknown>;
|
|
18
|
+
onFinish?: (message: UIMessage, context: {
|
|
19
|
+
finishReason: FinishReason;
|
|
20
|
+
usage?: Usage;
|
|
21
|
+
}) => void;
|
|
22
|
+
onError?: (error: Error) => void;
|
|
23
|
+
maxToolRoundtrips?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface UseChatReturn {
|
|
26
|
+
messages: Ref<UIMessage[]>;
|
|
27
|
+
status: Ref<ChatStatus>;
|
|
28
|
+
error: Ref<Error | undefined>;
|
|
29
|
+
id: string;
|
|
30
|
+
input: Ref<string>;
|
|
31
|
+
sendMessage: (message?: string | {
|
|
32
|
+
text?: string;
|
|
33
|
+
files?: File[];
|
|
34
|
+
}) => Promise<void>;
|
|
35
|
+
regenerate: () => Promise<void>;
|
|
36
|
+
stop: () => void;
|
|
37
|
+
setMessages: (messages: UIMessage[] | ((prev: UIMessage[]) => UIMessage[])) => void;
|
|
38
|
+
handleSubmit: (event?: Event) => void;
|
|
39
|
+
isLoading: Ref<boolean>;
|
|
40
|
+
addToolResult: (options: {
|
|
41
|
+
toolCallId: string;
|
|
42
|
+
result: unknown;
|
|
43
|
+
}) => void;
|
|
44
|
+
clearError: () => void;
|
|
45
|
+
}
|
|
46
|
+
export declare function useChat(options: UseChatOptions): UseChatReturn;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Ref } from 'vue';
|
|
2
|
+
import type { ChatStatus, UIMessage } from '../types';
|
|
3
|
+
import type { ChatStreamChunk } from '../providers/types';
|
|
4
|
+
import type { FinishReason, Usage } from '../types';
|
|
5
|
+
export interface StreamCallbacks {
|
|
6
|
+
onFinish?: (message: UIMessage, context: {
|
|
7
|
+
finishReason: FinishReason;
|
|
8
|
+
usage?: Usage;
|
|
9
|
+
}) => void;
|
|
10
|
+
onError?: (error: Error) => void;
|
|
11
|
+
onToolCall?: (toolCall: {
|
|
12
|
+
toolCallId: string;
|
|
13
|
+
toolName: string;
|
|
14
|
+
args: unknown;
|
|
15
|
+
}) => unknown | Promise<unknown>;
|
|
16
|
+
}
|
|
17
|
+
export declare class StreamProcessor {
|
|
18
|
+
private messages;
|
|
19
|
+
private status;
|
|
20
|
+
private generateId;
|
|
21
|
+
constructor(messages: Ref<UIMessage[]>, status: Ref<ChatStatus>, generateId: () => string);
|
|
22
|
+
processStream(stream: ReadableStream<ChatStreamChunk>, signal: AbortSignal, callbacks: StreamCallbacks): Promise<{
|
|
23
|
+
finishReason: FinishReason;
|
|
24
|
+
usage?: Usage;
|
|
25
|
+
toolCalls: {
|
|
26
|
+
toolCallId: string;
|
|
27
|
+
toolName: string;
|
|
28
|
+
args: unknown;
|
|
29
|
+
}[];
|
|
30
|
+
}>;
|
|
31
|
+
private getOrCreateAssistantMessage;
|
|
32
|
+
private applyChunk;
|
|
33
|
+
private finalizeTextParts;
|
|
34
|
+
private findToolCallPart;
|
|
35
|
+
private getToolName;
|
|
36
|
+
private triggerReactivity;
|
|
37
|
+
}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("vue");class P{constructor(s,t,e){this.messages=s,this.status=t,this.generateId=e}messages;status;generateId;async processStream(s,t,e){this.status.value="streaming";const a=this.getOrCreateAssistantMessage(),y=new Map,u=[];let C="stop",b;const x=s.getReader();try{for(;!t.aborted;){const{done:f,value:n}=await x.read();if(f)break;if(this.applyChunk(a,n,y),n.type==="tool-call-end"){const w=y.get(n.toolCallId)??"{}";let h;try{h=JSON.parse(w)}catch{h=w}const I={toolCallId:n.toolCallId,toolName:this.getToolName(a,n.toolCallId),args:h};if(u.push(I),e.onToolCall){const g=this.findToolCallPart(a,n.toolCallId);g&&(g.state="running",g.args=h),this.triggerReactivity();try{const p=await e.onToolCall(I);p!==void 0&&g&&(g.state="result",g.result=p,this.triggerReactivity())}catch(p){g&&(g.state="error",g.error=p instanceof Error?p.message:String(p),this.triggerReactivity())}}}if(n.type==="finish"&&(C=n.finishReason,b=n.usage),n.type==="error")throw n.error;this.triggerReactivity()}}catch(f){if(!t.aborted){const n=f instanceof Error?f:new Error(String(f));throw e.onError?.(n),n}}finally{x.releaseLock()}return this.finalizeTextParts(a),this.triggerReactivity(),e.onFinish?.(a,{finishReason:C,usage:b}),{finishReason:C,usage:b,toolCalls:u}}getOrCreateAssistantMessage(){const s=this.messages.value,t=s[s.length-1];if(t?.role==="assistant")return t;const e={id:this.generateId(),role:"assistant",parts:[],createdAt:new Date};return s.push(e),e}applyChunk(s,t,e){switch(t.type){case"text-delta":{const a=s.parts[s.parts.length-1];a?.type==="text"&&a.state==="streaming"?a.text+=t.text:s.parts.push({type:"text",text:t.text,state:"streaming"});break}case"reasoning-delta":{const a=s.parts[s.parts.length-1];a?.type==="reasoning"&&a.state==="streaming"?a.text+=t.text:s.parts.push({type:"reasoning",text:t.text,state:"streaming"});break}case"tool-call-start":s.parts.push({type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,args:void 0,state:"pending"}),e.set(t.toolCallId,"");break;case"tool-call-delta":e.set(t.toolCallId,(e.get(t.toolCallId)??"")+t.args);break}}finalizeTextParts(s){for(const t of s.parts)(t.type==="text"||t.type==="reasoning")&&t.state==="streaming"&&(t.state="done")}findToolCallPart(s,t){return s.parts.find(e=>e.type==="tool-call"&&e.toolCallId===t)}getToolName(s,t){return this.findToolCallPart(s,t)?.toolName??""}triggerReactivity(){this.messages.value=[...this.messages.value]}}const R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function T(o=16){const s=crypto.getRandomValues(new Uint8Array(o));let t="";for(let e=0;e<o;e++)t+=R[s[e]%R.length];return t}function E(o){const s=o.id??T(),t=v.ref(o.initialMessages??[]),e=v.ref("ready"),a=v.ref(void 0),y=v.ref("");let u=null;const C=new P(t,e,T),b=()=>{const r=[];o.system&&r.push({role:"system",content:o.system});for(const i of t.value){if(i.role==="system")continue;const c=i.parts.filter(l=>l.type==="text").map(l=>l.text).join(""),m=i.parts.filter(l=>l.type==="tool-call").map(l=>({id:l.toolCallId,name:l.toolName,args:l.args}));if(i.role==="user")r.push({role:"user",content:c});else if(i.role==="assistant"){r.push({role:"assistant",content:c,toolCalls:m.length>0?m:void 0});for(const l of i.parts)l.type!=="tool-call"||l.state!=="result"||r.push({role:"tool",content:JSON.stringify(l.result),toolCallId:l.toolCallId})}}return r},x=async r=>{const i=o.maxToolRoundtrips??5;let d=0;for(;d<i;){const c=b();o.provider.validateConfig();const{stream:m}=await o.provider.chat({model:o.model,messages:c,tools:o.tools,signal:r,providerOptions:{...o.providerOptions,...v.toValue(o.body)}}),l=await C.processStream(m,r,{onFinish:o.onFinish,onError:o.onError,onToolCall:o.onToolCall});if(l.finishReason!=="tool-calls"||l.toolCalls.length===0)break;d++}},f=async r=>{const i=typeof r=="string"?r:r?.text??y.value;if(!i.trim())return;(typeof r!="object"||r===null||!("text"in r))&&(y.value="");const d={id:T(),role:"user",parts:[{type:"text",text:i,state:"done"}],createdAt:new Date};t.value=[...t.value,d],a.value=void 0,e.value="submitted",u?.abort(),u=new AbortController;try{await x(u.signal),e.value="ready"}catch(c){if(u.signal.aborted){e.value="ready";return}a.value=c instanceof Error?c:new Error(String(c)),e.value="error"}},n=async()=>{const r=t.value,i=r.reduce((d,c,m)=>c.role==="assistant"?m:d,-1);if(i!==-1){t.value=r.slice(0,i),a.value=void 0,e.value="submitted",u?.abort(),u=new AbortController;try{await x(u.signal),e.value="ready"}catch(d){if(u.signal.aborted){e.value="ready";return}a.value=d instanceof Error?d:new Error(String(d)),e.value="error"}}},w=()=>{u?.abort(),u=null,e.value="ready"},h=r=>{t.value=typeof r=="function"?r(t.value):r},I=r=>{r?.preventDefault?.(),y.value.trim()&&f()},g=v.computed(()=>e.value==="submitted"||e.value==="streaming"),p=({toolCallId:r,result:i})=>{for(const d of t.value)for(const c of d.parts)if(c.type==="tool-call"&&c.toolCallId===r){c.state="result",c.result=i,t.value=[...t.value];return}},S=()=>{a.value=void 0,e.value==="error"&&(e.value="ready")};return v.onScopeDispose(()=>{u?.abort()}),{messages:t,status:v.computed(()=>e.value),error:a,id:s,input:y,sendMessage:f,regenerate:n,stop:w,setMessages:h,handleSubmit:I,isLoading:g,addToolResult:p,clearError:S}}exports.useChat=E;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { useChat } from './composables/use-chat';
|
|
2
|
+
export type { UseChatOptions, UseChatReturn } from './composables/use-chat';
|
|
3
|
+
export type { UIMessage, UIMessagePart, TextPart, ReasoningPart, ToolCallPart, FilePart, SourcePart, ToolDefinition, ChatStatus, FinishReason, Usage, } from './types';
|
|
4
|
+
export type { LLMProvider, ChatRequest, ChatMessage, ChatStreamResult, ChatStreamChunk, ChatResponse, } from './providers/types';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { ref as I, computed as R, onScopeDispose as S, toValue as M } from "vue";
|
|
2
|
+
class A {
|
|
3
|
+
constructor(s, t, e) {
|
|
4
|
+
this.messages = s, this.status = t, this.generateId = e;
|
|
5
|
+
}
|
|
6
|
+
messages;
|
|
7
|
+
status;
|
|
8
|
+
generateId;
|
|
9
|
+
async processStream(s, t, e) {
|
|
10
|
+
this.status.value = "streaming";
|
|
11
|
+
const a = this.getOrCreateAssistantMessage(), v = /* @__PURE__ */ new Map(), u = [];
|
|
12
|
+
let m = "stop", C;
|
|
13
|
+
const x = s.getReader();
|
|
14
|
+
try {
|
|
15
|
+
for (; !t.aborted; ) {
|
|
16
|
+
const { done: f, value: n } = await x.read();
|
|
17
|
+
if (f) break;
|
|
18
|
+
if (this.applyChunk(a, n, v), n.type === "tool-call-end") {
|
|
19
|
+
const b = v.get(n.toolCallId) ?? "{}";
|
|
20
|
+
let y;
|
|
21
|
+
try {
|
|
22
|
+
y = JSON.parse(b);
|
|
23
|
+
} catch {
|
|
24
|
+
y = b;
|
|
25
|
+
}
|
|
26
|
+
const w = { toolCallId: n.toolCallId, toolName: this.getToolName(a, n.toolCallId), args: y };
|
|
27
|
+
if (u.push(w), e.onToolCall) {
|
|
28
|
+
const g = this.findToolCallPart(a, n.toolCallId);
|
|
29
|
+
g && (g.state = "running", g.args = y), this.triggerReactivity();
|
|
30
|
+
try {
|
|
31
|
+
const p = await e.onToolCall(w);
|
|
32
|
+
p !== void 0 && g && (g.state = "result", g.result = p, this.triggerReactivity());
|
|
33
|
+
} catch (p) {
|
|
34
|
+
g && (g.state = "error", g.error = p instanceof Error ? p.message : String(p), this.triggerReactivity());
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (n.type === "finish" && (m = n.finishReason, C = n.usage), n.type === "error")
|
|
39
|
+
throw n.error;
|
|
40
|
+
this.triggerReactivity();
|
|
41
|
+
}
|
|
42
|
+
} catch (f) {
|
|
43
|
+
if (!t.aborted) {
|
|
44
|
+
const n = f instanceof Error ? f : new Error(String(f));
|
|
45
|
+
throw e.onError?.(n), n;
|
|
46
|
+
}
|
|
47
|
+
} finally {
|
|
48
|
+
x.releaseLock();
|
|
49
|
+
}
|
|
50
|
+
return this.finalizeTextParts(a), this.triggerReactivity(), e.onFinish?.(a, { finishReason: m, usage: C }), { finishReason: m, usage: C, toolCalls: u };
|
|
51
|
+
}
|
|
52
|
+
getOrCreateAssistantMessage() {
|
|
53
|
+
const s = this.messages.value, t = s[s.length - 1];
|
|
54
|
+
if (t?.role === "assistant") return t;
|
|
55
|
+
const e = {
|
|
56
|
+
id: this.generateId(),
|
|
57
|
+
role: "assistant",
|
|
58
|
+
parts: [],
|
|
59
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
60
|
+
};
|
|
61
|
+
return s.push(e), e;
|
|
62
|
+
}
|
|
63
|
+
applyChunk(s, t, e) {
|
|
64
|
+
switch (t.type) {
|
|
65
|
+
case "text-delta": {
|
|
66
|
+
const a = s.parts[s.parts.length - 1];
|
|
67
|
+
a?.type === "text" && a.state === "streaming" ? a.text += t.text : s.parts.push({ type: "text", text: t.text, state: "streaming" });
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
case "reasoning-delta": {
|
|
71
|
+
const a = s.parts[s.parts.length - 1];
|
|
72
|
+
a?.type === "reasoning" && a.state === "streaming" ? a.text += t.text : s.parts.push({ type: "reasoning", text: t.text, state: "streaming" });
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
case "tool-call-start":
|
|
76
|
+
s.parts.push({
|
|
77
|
+
type: "tool-call",
|
|
78
|
+
toolCallId: t.toolCallId,
|
|
79
|
+
toolName: t.toolName,
|
|
80
|
+
args: void 0,
|
|
81
|
+
state: "pending"
|
|
82
|
+
}), e.set(t.toolCallId, "");
|
|
83
|
+
break;
|
|
84
|
+
case "tool-call-delta":
|
|
85
|
+
e.set(
|
|
86
|
+
t.toolCallId,
|
|
87
|
+
(e.get(t.toolCallId) ?? "") + t.args
|
|
88
|
+
);
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
finalizeTextParts(s) {
|
|
93
|
+
for (const t of s.parts)
|
|
94
|
+
(t.type === "text" || t.type === "reasoning") && t.state === "streaming" && (t.state = "done");
|
|
95
|
+
}
|
|
96
|
+
findToolCallPart(s, t) {
|
|
97
|
+
return s.parts.find(
|
|
98
|
+
(e) => e.type === "tool-call" && e.toolCallId === t
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
getToolName(s, t) {
|
|
102
|
+
return this.findToolCallPart(s, t)?.toolName ?? "";
|
|
103
|
+
}
|
|
104
|
+
triggerReactivity() {
|
|
105
|
+
this.messages.value = [...this.messages.value];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const E = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
109
|
+
function T(o = 16) {
|
|
110
|
+
const s = crypto.getRandomValues(new Uint8Array(o));
|
|
111
|
+
let t = "";
|
|
112
|
+
for (let e = 0; e < o; e++)
|
|
113
|
+
t += E[s[e] % E.length];
|
|
114
|
+
return t;
|
|
115
|
+
}
|
|
116
|
+
function O(o) {
|
|
117
|
+
const s = o.id ?? T(), t = I(o.initialMessages ?? []), e = I("ready"), a = I(void 0), v = I("");
|
|
118
|
+
let u = null;
|
|
119
|
+
const m = new A(t, e, T), C = () => {
|
|
120
|
+
const r = [];
|
|
121
|
+
o.system && r.push({ role: "system", content: o.system });
|
|
122
|
+
for (const i of t.value) {
|
|
123
|
+
if (i.role === "system") continue;
|
|
124
|
+
const c = i.parts.filter((l) => l.type === "text").map((l) => l.text).join(""), h = i.parts.filter((l) => l.type === "tool-call").map((l) => ({ id: l.toolCallId, name: l.toolName, args: l.args }));
|
|
125
|
+
if (i.role === "user")
|
|
126
|
+
r.push({ role: "user", content: c });
|
|
127
|
+
else if (i.role === "assistant") {
|
|
128
|
+
r.push({
|
|
129
|
+
role: "assistant",
|
|
130
|
+
content: c,
|
|
131
|
+
toolCalls: h.length > 0 ? h : void 0
|
|
132
|
+
});
|
|
133
|
+
for (const l of i.parts)
|
|
134
|
+
l.type !== "tool-call" || l.state !== "result" || r.push({
|
|
135
|
+
role: "tool",
|
|
136
|
+
content: JSON.stringify(l.result),
|
|
137
|
+
toolCallId: l.toolCallId
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return r;
|
|
142
|
+
}, x = async (r) => {
|
|
143
|
+
const i = o.maxToolRoundtrips ?? 5;
|
|
144
|
+
let d = 0;
|
|
145
|
+
for (; d < i; ) {
|
|
146
|
+
const c = C();
|
|
147
|
+
o.provider.validateConfig();
|
|
148
|
+
const { stream: h } = await o.provider.chat({
|
|
149
|
+
model: o.model,
|
|
150
|
+
messages: c,
|
|
151
|
+
tools: o.tools,
|
|
152
|
+
signal: r,
|
|
153
|
+
providerOptions: {
|
|
154
|
+
...o.providerOptions,
|
|
155
|
+
...M(o.body)
|
|
156
|
+
}
|
|
157
|
+
}), l = await m.processStream(h, r, {
|
|
158
|
+
onFinish: o.onFinish,
|
|
159
|
+
onError: o.onError,
|
|
160
|
+
onToolCall: o.onToolCall
|
|
161
|
+
});
|
|
162
|
+
if (l.finishReason !== "tool-calls" || l.toolCalls.length === 0)
|
|
163
|
+
break;
|
|
164
|
+
d++;
|
|
165
|
+
}
|
|
166
|
+
}, f = async (r) => {
|
|
167
|
+
const i = typeof r == "string" ? r : r?.text ?? v.value;
|
|
168
|
+
if (!i.trim()) return;
|
|
169
|
+
(typeof r != "object" || r === null || !("text" in r)) && (v.value = "");
|
|
170
|
+
const d = {
|
|
171
|
+
id: T(),
|
|
172
|
+
role: "user",
|
|
173
|
+
parts: [{ type: "text", text: i, state: "done" }],
|
|
174
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
175
|
+
};
|
|
176
|
+
t.value = [...t.value, d], a.value = void 0, e.value = "submitted", u?.abort(), u = new AbortController();
|
|
177
|
+
try {
|
|
178
|
+
await x(u.signal), e.value = "ready";
|
|
179
|
+
} catch (c) {
|
|
180
|
+
if (u.signal.aborted) {
|
|
181
|
+
e.value = "ready";
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
a.value = c instanceof Error ? c : new Error(String(c)), e.value = "error";
|
|
185
|
+
}
|
|
186
|
+
}, n = async () => {
|
|
187
|
+
const r = t.value, i = r.reduce((d, c, h) => c.role === "assistant" ? h : d, -1);
|
|
188
|
+
if (i !== -1) {
|
|
189
|
+
t.value = r.slice(0, i), a.value = void 0, e.value = "submitted", u?.abort(), u = new AbortController();
|
|
190
|
+
try {
|
|
191
|
+
await x(u.signal), e.value = "ready";
|
|
192
|
+
} catch (d) {
|
|
193
|
+
if (u.signal.aborted) {
|
|
194
|
+
e.value = "ready";
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
a.value = d instanceof Error ? d : new Error(String(d)), e.value = "error";
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}, b = () => {
|
|
201
|
+
u?.abort(), u = null, e.value = "ready";
|
|
202
|
+
}, y = (r) => {
|
|
203
|
+
t.value = typeof r == "function" ? r(t.value) : r;
|
|
204
|
+
}, w = (r) => {
|
|
205
|
+
r?.preventDefault?.(), v.value.trim() && f();
|
|
206
|
+
}, g = R(() => e.value === "submitted" || e.value === "streaming"), p = ({ toolCallId: r, result: i }) => {
|
|
207
|
+
for (const d of t.value)
|
|
208
|
+
for (const c of d.parts)
|
|
209
|
+
if (c.type === "tool-call" && c.toolCallId === r) {
|
|
210
|
+
c.state = "result", c.result = i, t.value = [...t.value];
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
}, P = () => {
|
|
214
|
+
a.value = void 0, e.value === "error" && (e.value = "ready");
|
|
215
|
+
};
|
|
216
|
+
return S(() => {
|
|
217
|
+
u?.abort();
|
|
218
|
+
}), {
|
|
219
|
+
messages: t,
|
|
220
|
+
status: R(() => e.value),
|
|
221
|
+
error: a,
|
|
222
|
+
id: s,
|
|
223
|
+
input: v,
|
|
224
|
+
sendMessage: f,
|
|
225
|
+
regenerate: n,
|
|
226
|
+
stop: b,
|
|
227
|
+
setMessages: y,
|
|
228
|
+
handleSubmit: w,
|
|
229
|
+
isLoading: g,
|
|
230
|
+
addToolResult: p,
|
|
231
|
+
clearError: P
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
export {
|
|
235
|
+
O as useChat
|
|
236
|
+
};
|
package/dist/nuxt.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const r=require("@nuxt/kit");var t=typeof document<"u"?document.currentScript:null;const n=r.defineNuxtModule({meta:{name:"vue-llm",configKey:"vueLlm",compatibility:{nuxt:">=3.5.0"}},defaults:{},setup(i,o){const e=r.createResolver(typeof document>"u"?require("url").pathToFileURL(__filename).href:t&&t.tagName.toUpperCase()==="SCRIPT"&&t.src||new URL("nuxt.cjs",document.baseURI).href);r.addImports([{name:"useChat",from:e.resolve("./index")}]),r.addImports([{name:"createOpenAI",from:e.resolve("./providers")},{name:"createAnthropic",from:e.resolve("./providers")},{name:"createOllama",from:e.resolve("./providers")}]),o.options.runtimeConfig.vueLlm={...o.options.runtimeConfig.vueLlm,openaiApiKey:"",anthropicApiKey:""}}});module.exports=n;
|
package/dist/nuxt.d.ts
ADDED
package/dist/nuxt.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { defineNuxtModule as t, createResolver as i, addImports as r } from "@nuxt/kit";
|
|
2
|
+
const a = t({
|
|
3
|
+
meta: {
|
|
4
|
+
name: "vue-llm",
|
|
5
|
+
configKey: "vueLlm",
|
|
6
|
+
compatibility: { nuxt: ">=3.5.0" }
|
|
7
|
+
},
|
|
8
|
+
defaults: {},
|
|
9
|
+
setup(m, o) {
|
|
10
|
+
const e = i(import.meta.url);
|
|
11
|
+
r([
|
|
12
|
+
{ name: "useChat", from: e.resolve("./index") }
|
|
13
|
+
]), r([
|
|
14
|
+
{ name: "createOpenAI", from: e.resolve("./providers") },
|
|
15
|
+
{ name: "createAnthropic", from: e.resolve("./providers") },
|
|
16
|
+
{ name: "createOllama", from: e.resolve("./providers") }
|
|
17
|
+
]), o.options.runtimeConfig.vueLlm = {
|
|
18
|
+
...o.options.runtimeConfig.vueLlm,
|
|
19
|
+
openaiApiKey: "",
|
|
20
|
+
anthropicApiKey: ""
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
export {
|
|
25
|
+
a as default
|
|
26
|
+
};
|