vue-llm 0.1.5 → 0.2.1

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.
@@ -0,0 +1,27 @@
1
+ import { type Ref } from 'vue';
2
+ import type { ChatStatus, FinishReason, Usage } from '../types';
3
+ import type { LLMProvider } from '../providers/types';
4
+ export interface UseCompletionOptions {
5
+ id?: string;
6
+ provider: LLMProvider;
7
+ model: string;
8
+ system?: string;
9
+ onFinish?: (completion: string, context: {
10
+ finishReason: FinishReason;
11
+ usage?: Usage;
12
+ }) => void;
13
+ onError?: (error: Error) => void;
14
+ }
15
+ export interface UseCompletionReturn {
16
+ completion: Ref<string>;
17
+ status: Ref<ChatStatus>;
18
+ error: Ref<Error | undefined>;
19
+ isLoading: Ref<boolean>;
20
+ id: string;
21
+ input: Ref<string>;
22
+ complete: (prompt?: string) => Promise<string>;
23
+ stop: () => void;
24
+ clearError: () => void;
25
+ handleSubmit: (event?: Event) => void;
26
+ }
27
+ export declare function useCompletion(options: UseCompletionOptions): UseCompletionReturn;
@@ -0,0 +1,28 @@
1
+ import { type Ref } from 'vue';
2
+ import type { ChatStatus, FinishReason, Usage } from '../types';
3
+ import type { LLMProvider } from '../providers/types';
4
+ export interface UseObjectOptions<T> {
5
+ id?: string;
6
+ provider: LLMProvider;
7
+ model: string;
8
+ system?: string;
9
+ schema: Record<string, unknown>;
10
+ onFinish?: (object: T, context: {
11
+ finishReason: FinishReason;
12
+ usage?: Usage;
13
+ }) => void;
14
+ onError?: (error: Error) => void;
15
+ }
16
+ export interface UseObjectReturn<T> {
17
+ object: Ref<T | undefined>;
18
+ partialObject: Ref<Partial<T> | undefined>;
19
+ status: Ref<ChatStatus>;
20
+ error: Ref<Error | undefined>;
21
+ isLoading: Ref<boolean>;
22
+ id: string;
23
+ input: Ref<string>;
24
+ submit: (prompt?: string) => Promise<T | undefined>;
25
+ stop: () => void;
26
+ clearError: () => void;
27
+ }
28
+ export declare function useObject<T = unknown>(options: UseObjectOptions<T>): UseObjectReturn<T>;
package/dist/index.cjs CHANGED
@@ -1 +1,3 @@
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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("vue");class I{constructor(s,e,t){this.messages=s,this.status=e,this.generateId=t}messages;status;generateId;async processStream(s,e,t){this.status.value="streaming";const r=this.getOrCreateAssistantMessage(),c=new Map,o=[];let g="stop",w;const x=s.getReader();try{for(;!e.aborted;){const{done:b,value:f}=await x.read();if(b)break;if(this.applyChunk(r,f,c),f.type==="tool-call-end"){const C=c.get(f.toolCallId)??"{}";let h;try{h=JSON.parse(C)}catch{h=C}const y={toolCallId:f.toolCallId,toolName:this.getToolName(r,f.toolCallId),args:h};if(o.push(y),t.onToolCall){const d=this.findToolCallPart(r,f.toolCallId);d&&(d.state="running",d.args=h),this.triggerReactivity();try{const m=await t.onToolCall(y);m!==void 0&&d&&(d.state="result",d.result=m,this.triggerReactivity())}catch(m){d&&(d.state="error",d.error=m instanceof Error?m.message:String(m),this.triggerReactivity())}}}if(f.type==="finish"&&(g=f.finishReason,w=f.usage),f.type==="error")throw f.error;this.triggerReactivity()}}catch(b){if(!e.aborted){const f=b instanceof Error?b:new Error(String(b));throw t.onError?.(f),f}}finally{x.releaseLock()}return this.finalizeTextParts(r),this.triggerReactivity(),t.onFinish?.(r,{finishReason:g,usage:w}),{finishReason:g,usage:w,toolCalls:o}}getOrCreateAssistantMessage(){const s=this.messages.value,e=s[s.length-1];if(e?.role==="assistant")return e;const t={id:this.generateId(),role:"assistant",parts:[],createdAt:new Date};return s.push(t),t}applyChunk(s,e,t){switch(e.type){case"text-delta":{const r=s.parts[s.parts.length-1];r?.type==="text"&&r.state==="streaming"?r.text+=e.text:s.parts.push({type:"text",text:e.text,state:"streaming"});break}case"reasoning-delta":{const r=s.parts[s.parts.length-1];r?.type==="reasoning"&&r.state==="streaming"?r.text+=e.text:s.parts.push({type:"reasoning",text:e.text,state:"streaming"});break}case"tool-call-start":s.parts.push({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,args:void 0,state:"pending"}),t.set(e.toolCallId,"");break;case"tool-call-delta":t.set(e.toolCallId,(t.get(e.toolCallId)??"")+e.args);break}}finalizeTextParts(s){for(const e of s.parts)(e.type==="text"||e.type==="reasoning")&&e.state==="streaming"&&(e.state="done")}findToolCallPart(s,e){return s.parts.find(t=>t.type==="tool-call"&&t.toolCallId===e)}getToolName(s,e){return this.findToolCallPart(s,e)?.toolName??""}triggerReactivity(){this.messages.value=[...this.messages.value]}}const O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function R(a=16){const s=crypto.getRandomValues(new Uint8Array(a));let e="";for(let t=0;t<a;t++)e+=O[s[t]%O.length];return e}function N(a){const s=a.id??R(),e=u.ref(a.initialMessages??[]),t=u.ref("ready"),r=u.ref(void 0),c=u.ref("");let o=null;const g=new I(e,t,R),w=()=>{const l=[];a.system&&l.push({role:"system",content:a.system});for(const v of e.value){if(v.role==="system")continue;const i=v.parts.filter(p=>p.type==="text").map(p=>p.text).join(""),E=v.parts.filter(p=>p.type==="tool-call").map(p=>({id:p.toolCallId,name:p.toolName,args:p.args}));if(v.role==="user")l.push({role:"user",content:i});else if(v.role==="assistant"){l.push({role:"assistant",content:i,toolCalls:E.length>0?E:void 0});for(const p of v.parts)p.type!=="tool-call"||p.state!=="result"||l.push({role:"tool",content:JSON.stringify(p.result),toolCallId:p.toolCallId})}}return l},x=async l=>{const v=a.maxToolRoundtrips??5;let n=0;for(;n<v;){const i=w();a.provider.validateConfig();const{stream:E}=await a.provider.chat({model:a.model,messages:i,tools:a.tools,signal:l,providerOptions:{...a.providerOptions,...u.toValue(a.body)}}),p=await g.processStream(E,l,{onFinish:a.onFinish,onError:a.onError,onToolCall:a.onToolCall});if(p.finishReason!=="tool-calls"||p.toolCalls.length===0)break;n++}},b=async l=>{const v=typeof l=="string"?l:l?.text??c.value;if(!v.trim())return;(typeof l!="object"||l===null||!("text"in l))&&(c.value="");const n={id:R(),role:"user",parts:[{type:"text",text:v,state:"done"}],createdAt:new Date};e.value=[...e.value,n],r.value=void 0,t.value="submitted",o?.abort(),o=new AbortController;try{await x(o.signal),t.value="ready"}catch(i){if(o.signal.aborted){t.value="ready";return}r.value=i instanceof Error?i:new Error(String(i)),t.value="error"}},f=async()=>{const l=e.value,v=l.reduce((n,i,E)=>i.role==="assistant"?E:n,-1);if(v!==-1){e.value=l.slice(0,v),r.value=void 0,t.value="submitted",o?.abort(),o=new AbortController;try{await x(o.signal),t.value="ready"}catch(n){if(o.signal.aborted){t.value="ready";return}r.value=n instanceof Error?n:new Error(String(n)),t.value="error"}}},C=()=>{o?.abort(),o=null,t.value="ready"},h=l=>{e.value=typeof l=="function"?l(e.value):l},y=l=>{l?.preventDefault?.(),c.value.trim()&&b()},d=u.computed(()=>t.value==="submitted"||t.value==="streaming"),m=({toolCallId:l,result:v})=>{for(const n of e.value)for(const i of n.parts)if(i.type==="tool-call"&&i.toolCallId===l){i.state="result",i.result=v,e.value=[...e.value];return}},S=()=>{r.value=void 0,t.value==="error"&&(t.value="ready")};return u.onScopeDispose(()=>{o?.abort()}),{messages:e,status:u.computed(()=>t.value),error:r,id:s,input:c,sendMessage:b,regenerate:f,stop:C,setMessages:h,handleSubmit:y,isLoading:d,addToolResult:m,clearError:S}}function T(a){const s=a.id??R(),e=u.ref(""),t=u.ref("ready"),r=u.ref(void 0),c=u.ref("");let o=null;const g=async C=>{const h=C??c.value;if(!h.trim())return e.value;C||(c.value=""),e.value="",r.value=void 0,t.value="submitted",o?.abort(),o=new AbortController;try{a.provider.validateConfig();const y=a.system?[{role:"system",content:a.system},{role:"user",content:h}]:[{role:"user",content:h}],{stream:d}=await a.provider.chat({model:a.model,messages:y,signal:o.signal});t.value="streaming";const m=d.getReader();let S="stop",l;for(;!o.signal.aborted;){const{done:v,value:n}=await m.read();if(v)break;if(n.type==="text-delta")e.value+=n.text;else if(n.type==="finish")S=n.finishReason,l=n.usage;else if(n.type==="error")throw n.error}return m.releaseLock(),t.value="ready",a.onFinish?.(e.value,{finishReason:S,usage:l}),e.value}catch(y){if(!o||o.signal.aborted)return t.value="ready",e.value;const d=y instanceof Error?y:new Error(String(y));return r.value=d,t.value="error",a.onError?.(d),e.value}},w=()=>{o?.abort(),o=null,t.value="ready"},x=()=>{r.value=void 0,t.value==="error"&&(t.value="ready")},b=C=>{C?.preventDefault?.(),c.value.trim()&&g()},f=u.computed(()=>t.value==="submitted"||t.value==="streaming");return u.onScopeDispose(()=>{o?.abort()}),{completion:e,status:u.computed(()=>t.value),error:r,isLoading:f,id:s,input:c,complete:g,stop:w,clearError:x,handleSubmit:b}}function P(a){const s=a.id??R(),e=u.ref(void 0),t=u.ref(void 0),r=u.ref("ready"),c=u.ref(void 0),o=u.ref("");let g=null;const w=async C=>{const h=C??o.value;if(!h.trim())return e.value;C||(o.value=""),e.value=void 0,t.value=void 0,c.value=void 0,r.value="submitted",g?.abort(),g=new AbortController;try{a.provider.validateConfig();const y=[a.system??"","Respond with valid JSON matching this schema:",JSON.stringify(a.schema,null,2),"Output ONLY the JSON object, no other text."].filter(Boolean).join(`
2
+
3
+ `),{stream:d}=await a.provider.chat({model:a.model,messages:[{role:"system",content:y},{role:"user",content:h}],signal:g.signal,providerOptions:{response_format:{type:"json_object"}}});r.value="streaming";const m=d.getReader();let S="",l="stop",v;for(;!g.signal.aborted;){const{done:n,value:i}=await m.read();if(n)break;if(i.type==="text-delta"){S+=i.text;try{t.value=M(S)}catch{}}else if(i.type==="finish")l=i.finishReason,v=i.usage;else if(i.type==="error")throw i.error}m.releaseLock();try{e.value=JSON.parse(S),t.value=e.value}catch{throw new Error(`Failed to parse JSON response: ${S.slice(0,200)}`)}return r.value="ready",a.onFinish?.(e.value,{finishReason:l,usage:v}),e.value}catch(y){if(g.signal.aborted)return r.value="ready",e.value;const d=y instanceof Error?y:new Error(String(y));c.value=d,r.value="error",a.onError?.(d);return}},x=()=>{g?.abort(),g=null,r.value="ready"},b=()=>{c.value=void 0,r.value==="error"&&(r.value="ready")},f=u.computed(()=>r.value==="submitted"||r.value==="streaming");return u.onScopeDispose(()=>{g?.abort()}),{object:e,partialObject:t,status:u.computed(()=>r.value),error:c,isLoading:f,id:s,input:o,submit:w,stop:x,clearError:b}}function M(a){let s=a.trim();if(!s.startsWith("{"))return;let e=0,t=!1,r=!1;for(let c=0;c<s.length;c++){const o=s[c];if(r){r=!1;continue}if(o==="\\"){r=!0;continue}if(o==='"'){t=!t;continue}t||(o==="{"&&e++,o==="}"&&e--)}for(;e>0;)s+="}",e--;try{return JSON.parse(s)}catch{return}}exports.useChat=N;exports.useCompletion=T;exports.useObject=P;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  export { useChat } from './composables/use-chat';
2
2
  export type { UseChatOptions, UseChatReturn } from './composables/use-chat';
3
+ export { useCompletion } from './composables/use-completion';
4
+ export type { UseCompletionOptions, UseCompletionReturn } from './composables/use-completion';
5
+ export { useObject } from './composables/use-object';
6
+ export type { UseObjectOptions, UseObjectReturn } from './composables/use-object';
3
7
  export type { UIMessage, UIMessagePart, TextPart, ReasoningPart, ToolCallPart, FilePart, SourcePart, ToolDefinition, ChatStatus, FinishReason, Usage, } from './types';
4
8
  export type { LLMProvider, ChatRequest, ChatMessage, ChatStreamResult, ChatStreamChunk, ChatResponse, } from './providers/types';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { ref as I, computed as R, onScopeDispose as S, toValue as M } from "vue";
2
- class A {
1
+ import { ref as m, computed as R, onScopeDispose as O, toValue as T } from "vue";
2
+ class P {
3
3
  constructor(s, t, e) {
4
4
  this.messages = s, this.status = t, this.generateId = e;
5
5
  }
@@ -8,46 +8,46 @@ class A {
8
8
  generateId;
9
9
  async processStream(s, t, e) {
10
10
  this.status.value = "streaming";
11
- const a = this.getOrCreateAssistantMessage(), v = /* @__PURE__ */ new Map(), u = [];
12
- let m = "stop", C;
11
+ const r = this.getOrCreateAssistantMessage(), u = /* @__PURE__ */ new Map(), o = [];
12
+ let f = "stop", w;
13
13
  const x = s.getReader();
14
14
  try {
15
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;
16
+ const { done: b, value: v } = await x.read();
17
+ if (b) break;
18
+ if (this.applyChunk(r, v, u), v.type === "tool-call-end") {
19
+ const C = u.get(v.toolCallId) ?? "{}";
20
+ let h;
21
21
  try {
22
- y = JSON.parse(b);
22
+ h = JSON.parse(C);
23
23
  } catch {
24
- y = b;
24
+ h = C;
25
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();
26
+ const y = { toolCallId: v.toolCallId, toolName: this.getToolName(r, v.toolCallId), args: h };
27
+ if (o.push(y), e.onToolCall) {
28
+ const c = this.findToolCallPart(r, v.toolCallId);
29
+ c && (c.state = "running", c.args = h), this.triggerReactivity();
30
30
  try {
31
- const p = await e.onToolCall(w);
32
- p !== void 0 && g && (g.state = "result", g.result = p, this.triggerReactivity());
31
+ const p = await e.onToolCall(y);
32
+ p !== void 0 && c && (c.state = "result", c.result = p, this.triggerReactivity());
33
33
  } catch (p) {
34
- g && (g.state = "error", g.error = p instanceof Error ? p.message : String(p), this.triggerReactivity());
34
+ c && (c.state = "error", c.error = p instanceof Error ? p.message : String(p), this.triggerReactivity());
35
35
  }
36
36
  }
37
37
  }
38
- if (n.type === "finish" && (m = n.finishReason, C = n.usage), n.type === "error")
39
- throw n.error;
38
+ if (v.type === "finish" && (f = v.finishReason, w = v.usage), v.type === "error")
39
+ throw v.error;
40
40
  this.triggerReactivity();
41
41
  }
42
- } catch (f) {
42
+ } catch (b) {
43
43
  if (!t.aborted) {
44
- const n = f instanceof Error ? f : new Error(String(f));
45
- throw e.onError?.(n), n;
44
+ const v = b instanceof Error ? b : new Error(String(b));
45
+ throw e.onError?.(v), v;
46
46
  }
47
47
  } finally {
48
48
  x.releaseLock();
49
49
  }
50
- return this.finalizeTextParts(a), this.triggerReactivity(), e.onFinish?.(a, { finishReason: m, usage: C }), { finishReason: m, usage: C, toolCalls: u };
50
+ return this.finalizeTextParts(r), this.triggerReactivity(), e.onFinish?.(r, { finishReason: f, usage: w }), { finishReason: f, usage: w, toolCalls: o };
51
51
  }
52
52
  getOrCreateAssistantMessage() {
53
53
  const s = this.messages.value, t = s[s.length - 1];
@@ -63,13 +63,13 @@ class A {
63
63
  applyChunk(s, t, e) {
64
64
  switch (t.type) {
65
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" });
66
+ const r = s.parts[s.parts.length - 1];
67
+ r?.type === "text" && r.state === "streaming" ? r.text += t.text : s.parts.push({ type: "text", text: t.text, state: "streaming" });
68
68
  break;
69
69
  }
70
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" });
71
+ const r = s.parts[s.parts.length - 1];
72
+ r?.type === "reasoning" && r.state === "streaming" ? r.text += t.text : s.parts.push({ type: "reasoning", text: t.text, state: "streaming" });
73
73
  break;
74
74
  }
75
75
  case "tool-call-start":
@@ -105,132 +105,299 @@ class A {
105
105
  this.messages.value = [...this.messages.value];
106
106
  }
107
107
  }
108
- const E = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
109
- function T(o = 16) {
110
- const s = crypto.getRandomValues(new Uint8Array(o));
108
+ const N = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
109
+ function I(a = 16) {
110
+ const s = crypto.getRandomValues(new Uint8Array(a));
111
111
  let t = "";
112
- for (let e = 0; e < o; e++)
113
- t += E[s[e] % E.length];
112
+ for (let e = 0; e < a; e++)
113
+ t += N[s[e] % N.length];
114
114
  return t;
115
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({
116
+ function j(a) {
117
+ const s = a.id ?? I(), t = m(a.initialMessages ?? []), e = m("ready"), r = m(void 0), u = m("");
118
+ let o = null;
119
+ const f = new P(t, e, I), w = () => {
120
+ const l = [];
121
+ a.system && l.push({ role: "system", content: a.system });
122
+ for (const d of t.value) {
123
+ if (d.role === "system") continue;
124
+ const i = d.parts.filter((g) => g.type === "text").map((g) => g.text).join(""), E = d.parts.filter((g) => g.type === "tool-call").map((g) => ({ id: g.toolCallId, name: g.toolName, args: g.args }));
125
+ if (d.role === "user")
126
+ l.push({ role: "user", content: i });
127
+ else if (d.role === "assistant") {
128
+ l.push({
129
129
  role: "assistant",
130
- content: c,
131
- toolCalls: h.length > 0 ? h : void 0
130
+ content: i,
131
+ toolCalls: E.length > 0 ? E : void 0
132
132
  });
133
- for (const l of i.parts)
134
- l.type !== "tool-call" || l.state !== "result" || r.push({
133
+ for (const g of d.parts)
134
+ g.type !== "tool-call" || g.state !== "result" || l.push({
135
135
  role: "tool",
136
- content: JSON.stringify(l.result),
137
- toolCallId: l.toolCallId
136
+ content: JSON.stringify(g.result),
137
+ toolCallId: g.toolCallId
138
138
  });
139
139
  }
140
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,
141
+ return l;
142
+ }, x = async (l) => {
143
+ const d = a.maxToolRoundtrips ?? 5;
144
+ let n = 0;
145
+ for (; n < d; ) {
146
+ const i = w();
147
+ a.provider.validateConfig();
148
+ const { stream: E } = await a.provider.chat({
149
+ model: a.model,
150
+ messages: i,
151
+ tools: a.tools,
152
+ signal: l,
153
153
  providerOptions: {
154
- ...o.providerOptions,
155
- ...M(o.body)
154
+ ...a.providerOptions,
155
+ ...T(a.body)
156
156
  }
157
- }), l = await m.processStream(h, r, {
158
- onFinish: o.onFinish,
159
- onError: o.onError,
160
- onToolCall: o.onToolCall
157
+ }), g = await f.processStream(E, l, {
158
+ onFinish: a.onFinish,
159
+ onError: a.onError,
160
+ onToolCall: a.onToolCall
161
161
  });
162
- if (l.finishReason !== "tool-calls" || l.toolCalls.length === 0)
162
+ if (g.finishReason !== "tool-calls" || g.toolCalls.length === 0)
163
163
  break;
164
- d++;
164
+ n++;
165
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(),
166
+ }, b = async (l) => {
167
+ const d = typeof l == "string" ? l : l?.text ?? u.value;
168
+ if (!d.trim()) return;
169
+ (typeof l != "object" || l === null || !("text" in l)) && (u.value = "");
170
+ const n = {
171
+ id: I(),
172
172
  role: "user",
173
- parts: [{ type: "text", text: i, state: "done" }],
173
+ parts: [{ type: "text", text: d, state: "done" }],
174
174
  createdAt: /* @__PURE__ */ new Date()
175
175
  };
176
- t.value = [...t.value, d], a.value = void 0, e.value = "submitted", u?.abort(), u = new AbortController();
176
+ t.value = [...t.value, n], r.value = void 0, e.value = "submitted", o?.abort(), o = new AbortController();
177
177
  try {
178
- await x(u.signal), e.value = "ready";
179
- } catch (c) {
180
- if (u.signal.aborted) {
178
+ await x(o.signal), e.value = "ready";
179
+ } catch (i) {
180
+ if (o.signal.aborted) {
181
181
  e.value = "ready";
182
182
  return;
183
183
  }
184
- a.value = c instanceof Error ? c : new Error(String(c)), e.value = "error";
184
+ r.value = i instanceof Error ? i : new Error(String(i)), e.value = "error";
185
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();
186
+ }, v = async () => {
187
+ const l = t.value, d = l.reduce((n, i, E) => i.role === "assistant" ? E : n, -1);
188
+ if (d !== -1) {
189
+ t.value = l.slice(0, d), r.value = void 0, e.value = "submitted", o?.abort(), o = new AbortController();
190
190
  try {
191
- await x(u.signal), e.value = "ready";
192
- } catch (d) {
193
- if (u.signal.aborted) {
191
+ await x(o.signal), e.value = "ready";
192
+ } catch (n) {
193
+ if (o.signal.aborted) {
194
194
  e.value = "ready";
195
195
  return;
196
196
  }
197
- a.value = d instanceof Error ? d : new Error(String(d)), e.value = "error";
197
+ r.value = n instanceof Error ? n : new Error(String(n)), e.value = "error";
198
198
  }
199
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];
200
+ }, C = () => {
201
+ o?.abort(), o = null, e.value = "ready";
202
+ }, h = (l) => {
203
+ t.value = typeof l == "function" ? l(t.value) : l;
204
+ }, y = (l) => {
205
+ l?.preventDefault?.(), u.value.trim() && b();
206
+ }, c = R(() => e.value === "submitted" || e.value === "streaming"), p = ({ toolCallId: l, result: d }) => {
207
+ for (const n of t.value)
208
+ for (const i of n.parts)
209
+ if (i.type === "tool-call" && i.toolCallId === l) {
210
+ i.state = "result", i.result = d, t.value = [...t.value];
211
211
  return;
212
212
  }
213
- }, P = () => {
214
- a.value = void 0, e.value === "error" && (e.value = "ready");
213
+ }, S = () => {
214
+ r.value = void 0, e.value === "error" && (e.value = "ready");
215
215
  };
216
- return S(() => {
217
- u?.abort();
216
+ return O(() => {
217
+ o?.abort();
218
218
  }), {
219
219
  messages: t,
220
220
  status: R(() => e.value),
221
- error: a,
221
+ error: r,
222
222
  id: s,
223
- input: v,
224
- sendMessage: f,
225
- regenerate: n,
226
- stop: b,
227
- setMessages: y,
228
- handleSubmit: w,
229
- isLoading: g,
223
+ input: u,
224
+ sendMessage: b,
225
+ regenerate: v,
226
+ stop: C,
227
+ setMessages: h,
228
+ handleSubmit: y,
229
+ isLoading: c,
230
230
  addToolResult: p,
231
- clearError: P
231
+ clearError: S
232
+ };
233
+ }
234
+ function J(a) {
235
+ const s = a.id ?? I(), t = m(""), e = m("ready"), r = m(void 0), u = m("");
236
+ let o = null;
237
+ const f = async (C) => {
238
+ const h = C ?? u.value;
239
+ if (!h.trim()) return t.value;
240
+ C || (u.value = ""), t.value = "", r.value = void 0, e.value = "submitted", o?.abort(), o = new AbortController();
241
+ try {
242
+ a.provider.validateConfig();
243
+ const y = a.system ? [
244
+ { role: "system", content: a.system },
245
+ { role: "user", content: h }
246
+ ] : [{ role: "user", content: h }], { stream: c } = await a.provider.chat({
247
+ model: a.model,
248
+ messages: y,
249
+ signal: o.signal
250
+ });
251
+ e.value = "streaming";
252
+ const p = c.getReader();
253
+ let S = "stop", l;
254
+ for (; !o.signal.aborted; ) {
255
+ const { done: d, value: n } = await p.read();
256
+ if (d) break;
257
+ if (n.type === "text-delta")
258
+ t.value += n.text;
259
+ else if (n.type === "finish")
260
+ S = n.finishReason, l = n.usage;
261
+ else if (n.type === "error")
262
+ throw n.error;
263
+ }
264
+ return p.releaseLock(), e.value = "ready", a.onFinish?.(t.value, { finishReason: S, usage: l }), t.value;
265
+ } catch (y) {
266
+ if (!o || o.signal.aborted)
267
+ return e.value = "ready", t.value;
268
+ const c = y instanceof Error ? y : new Error(String(y));
269
+ return r.value = c, e.value = "error", a.onError?.(c), t.value;
270
+ }
271
+ }, w = () => {
272
+ o?.abort(), o = null, e.value = "ready";
273
+ }, x = () => {
274
+ r.value = void 0, e.value === "error" && (e.value = "ready");
275
+ }, b = (C) => {
276
+ C?.preventDefault?.(), u.value.trim() && f();
277
+ }, v = R(() => e.value === "submitted" || e.value === "streaming");
278
+ return O(() => {
279
+ o?.abort();
280
+ }), {
281
+ completion: t,
282
+ status: R(() => e.value),
283
+ error: r,
284
+ isLoading: v,
285
+ id: s,
286
+ input: u,
287
+ complete: f,
288
+ stop: w,
289
+ clearError: x,
290
+ handleSubmit: b
291
+ };
292
+ }
293
+ function L(a) {
294
+ const s = a.id ?? I(), t = m(void 0), e = m(void 0), r = m("ready"), u = m(void 0), o = m("");
295
+ let f = null;
296
+ const w = async (C) => {
297
+ const h = C ?? o.value;
298
+ if (!h.trim()) return t.value;
299
+ C || (o.value = ""), t.value = void 0, e.value = void 0, u.value = void 0, r.value = "submitted", f?.abort(), f = new AbortController();
300
+ try {
301
+ a.provider.validateConfig();
302
+ const y = [
303
+ a.system ?? "",
304
+ "Respond with valid JSON matching this schema:",
305
+ JSON.stringify(a.schema, null, 2),
306
+ "Output ONLY the JSON object, no other text."
307
+ ].filter(Boolean).join(`
308
+
309
+ `), { stream: c } = await a.provider.chat({
310
+ model: a.model,
311
+ messages: [
312
+ { role: "system", content: y },
313
+ { role: "user", content: h }
314
+ ],
315
+ signal: f.signal,
316
+ providerOptions: {
317
+ response_format: { type: "json_object" }
318
+ }
319
+ });
320
+ r.value = "streaming";
321
+ const p = c.getReader();
322
+ let S = "", l = "stop", d;
323
+ for (; !f.signal.aborted; ) {
324
+ const { done: n, value: i } = await p.read();
325
+ if (n) break;
326
+ if (i.type === "text-delta") {
327
+ S += i.text;
328
+ try {
329
+ e.value = A(S);
330
+ } catch {
331
+ }
332
+ } else if (i.type === "finish")
333
+ l = i.finishReason, d = i.usage;
334
+ else if (i.type === "error")
335
+ throw i.error;
336
+ }
337
+ p.releaseLock();
338
+ try {
339
+ t.value = JSON.parse(S), e.value = t.value;
340
+ } catch {
341
+ throw new Error(`Failed to parse JSON response: ${S.slice(0, 200)}`);
342
+ }
343
+ return r.value = "ready", a.onFinish?.(t.value, { finishReason: l, usage: d }), t.value;
344
+ } catch (y) {
345
+ if (f.signal.aborted)
346
+ return r.value = "ready", t.value;
347
+ const c = y instanceof Error ? y : new Error(String(y));
348
+ u.value = c, r.value = "error", a.onError?.(c);
349
+ return;
350
+ }
351
+ }, x = () => {
352
+ f?.abort(), f = null, r.value = "ready";
353
+ }, b = () => {
354
+ u.value = void 0, r.value === "error" && (r.value = "ready");
355
+ }, v = R(() => r.value === "submitted" || r.value === "streaming");
356
+ return O(() => {
357
+ f?.abort();
358
+ }), {
359
+ object: t,
360
+ partialObject: e,
361
+ status: R(() => r.value),
362
+ error: u,
363
+ isLoading: v,
364
+ id: s,
365
+ input: o,
366
+ submit: w,
367
+ stop: x,
368
+ clearError: b
232
369
  };
233
370
  }
371
+ function A(a) {
372
+ let s = a.trim();
373
+ if (!s.startsWith("{")) return;
374
+ let t = 0, e = !1, r = !1;
375
+ for (let u = 0; u < s.length; u++) {
376
+ const o = s[u];
377
+ if (r) {
378
+ r = !1;
379
+ continue;
380
+ }
381
+ if (o === "\\") {
382
+ r = !0;
383
+ continue;
384
+ }
385
+ if (o === '"') {
386
+ e = !e;
387
+ continue;
388
+ }
389
+ e || (o === "{" && t++, o === "}" && t--);
390
+ }
391
+ for (; t > 0; )
392
+ s += "}", t--;
393
+ try {
394
+ return JSON.parse(s);
395
+ } catch {
396
+ return;
397
+ }
398
+ }
234
399
  export {
235
- O as useChat
400
+ j as useChat,
401
+ J as useCompletion,
402
+ L as useObject
236
403
  };
package/dist/nuxt.cjs CHANGED
@@ -1 +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;
1
+ "use strict";const o=require("@nuxt/kit");var r=typeof document<"u"?document.currentScript:null;const n=o.defineNuxtModule({meta:{name:"vue-llm",configKey:"vueLlm",compatibility:{nuxt:">=3.5.0"}},defaults:{},setup(i,t){const e=o.createResolver(typeof document>"u"?require("url").pathToFileURL(__filename).href:r&&r.tagName.toUpperCase()==="SCRIPT"&&r.src||new URL("nuxt.cjs",document.baseURI).href);o.addImports([{name:"useChat",from:e.resolve("./index")},{name:"useCompletion",from:e.resolve("./index")},{name:"useObject",from:e.resolve("./index")}]),o.addImports([{name:"createOpenAI",from:e.resolve("./providers")},{name:"createAnthropic",from:e.resolve("./providers")},{name:"createOllama",from:e.resolve("./providers")}]),t.options.runtimeConfig.vueLlm={...t.options.runtimeConfig.vueLlm,openaiApiKey:"",anthropicApiKey:""}}});module.exports=n;
package/dist/nuxt.js CHANGED
@@ -1,4 +1,4 @@
1
- import { defineNuxtModule as t, createResolver as i, addImports as r } from "@nuxt/kit";
1
+ import { defineNuxtModule as t, createResolver as m, addImports as r } from "@nuxt/kit";
2
2
  const a = t({
3
3
  meta: {
4
4
  name: "vue-llm",
@@ -6,10 +6,12 @@ const a = t({
6
6
  compatibility: { nuxt: ">=3.5.0" }
7
7
  },
8
8
  defaults: {},
9
- setup(m, o) {
10
- const e = i(import.meta.url);
9
+ setup(n, o) {
10
+ const e = m(import.meta.url);
11
11
  r([
12
- { name: "useChat", from: e.resolve("./index") }
12
+ { name: "useChat", from: e.resolve("./index") },
13
+ { name: "useCompletion", from: e.resolve("./index") },
14
+ { name: "useObject", from: e.resolve("./index") }
13
15
  ]), r([
14
16
  { name: "createOpenAI", from: e.resolve("./providers") },
15
17
  { name: "createAnthropic", from: e.resolve("./providers") },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue-llm",
3
- "version": "0.1.5",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "description": "AI/LLM composables for Vue — useChat, useCompletion, streaming, multi-provider. The missing AI SDK for Vue.",
6
6
  "keywords": [