vue-llm 0.2.0 → 0.3.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.
@@ -0,0 +1,7 @@
1
+ import type { LLMProvider } from './types';
2
+ export interface GoogleConfig {
3
+ apiKey: string;
4
+ baseURL?: string;
5
+ dangerouslyAllowBrowser?: boolean;
6
+ }
7
+ export declare function createGoogle(config: GoogleConfig): LLMProvider;
@@ -1,6 +1,7 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class w extends TransformStream{constructor(){let e="";super({transform(t,p){e+=t;const r=e.split(`
2
- `);e=r.pop()??"";let o={};for(const l of r){if(l===""){o.data!==void 0&&p.enqueue({event:o.event,data:o.data,id:o.id,retry:o.retry}),o={};continue}if(l.startsWith(":"))continue;const f=l.indexOf(":");if(f===-1)continue;const u=l.slice(0,f),n=l.slice(f+1).replace(/^ /,"");switch(u){case"event":o.event=n;break;case"data":o.data=o.data!==void 0?o.data+`
3
- `+n:n;break;case"id":o.id=n;break;case"retry":o.retry=parseInt(n,10);break}}},flush(t){if(e.trim()){const p=e.split(`
4
- `);let r={};for(const o of p){if(o===""&&r.data!==void 0){t.enqueue({event:r.event,data:r.data,id:r.id,retry:r.retry}),r={};continue}const l=o.indexOf(":");if(l===-1||o.startsWith(":"))continue;const f=o.slice(0,l),u=o.slice(l+1).replace(/^ /,"");f==="data"&&(r.data=r.data!==void 0?r.data+`
5
- `+u:u)}}}})}}function _(c){return{id:"openai",supportsStreaming:!0,validateConfig(){if(!c.apiKey)throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');if(!c.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true.")},async chat(e){const t=c.baseURL??"https://api.openai.com/v1/chat/completions",p={model:e.model,messages:v(e.messages),stream:!0,stream_options:{include_usage:!0}};e.tools?.length&&(p.tools=e.tools.map(u=>({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}})));const r=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:e.signal});if(!r.ok){const u=await r.text();throw new Error(`[vue-llm] OpenAI API error ${r.status}: ${u}`)}if(!r.body)throw new Error("[vue-llm] No response body from OpenAI");let o;const l=new Promise(u=>{o=u});return{stream:r.body.pipeThrough(new TextDecoderStream).pipeThrough(new w).pipeThrough(new TransformStream({transform(u,n){if(u.data==="[DONE]")return;let m;try{m=JSON.parse(u.data)}catch{return}const i=m.choices?.[0];if(!i){m.usage&&o({finishReason:"stop",usage:{promptTokens:m.usage.prompt_tokens,completionTokens:m.usage.completion_tokens,totalTokens:m.usage.total_tokens}});return}const d=i.delta;if(d.content&&n.enqueue({type:"text-delta",text:d.content}),d.tool_calls)for(const s of d.tool_calls)s.id&&n.enqueue({type:"tool-call-start",toolCallId:s.id,toolName:s.function?.name??""}),s.function?.arguments&&n.enqueue({type:"tool-call-delta",toolCallId:s.id??"",args:s.function.arguments});if(i.finish_reason){const s=d.tool_calls?.filter(a=>a.id)??[];for(const a of s)a.id&&n.enqueue({type:"tool-call-end",toolCallId:a.id});const y=i.finish_reason==="tool_calls"?"tool-calls":i.finish_reason==="length"?"length":"stop";n.enqueue({type:"finish",finishReason:y,usage:void 0})}}})),response:l}}}}function v(c){return c.map(e=>e.role==="tool"?{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.toolCallId}:e.role==="assistant"&&e.toolCalls?.length?{role:"assistant",content:typeof e.content=="string"&&e.content?e.content:null,tool_calls:e.toolCalls.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:typeof t.args=="string"?t.args:JSON.stringify(t.args)}}))}:{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?{type:"text",text:t.text}:t.type==="image"?{type:"image_url",image_url:{url:t.url}}:t)})}function x(c){return{id:"anthropic",supportsStreaming:!0,validateConfig(){if(!c.apiKey)throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');if(!c.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true.")},async chat(e){const t=(c.baseURL??"https://api.anthropic.com")+"/v1/messages",p=e.messages.find(i=>i.role==="system"),r=e.messages.filter(i=>i.role!=="system"),o={model:e.model,messages:k(r),max_tokens:e.providerOptions?.maxTokens??4096,stream:!0};p&&(o.system=typeof p.content=="string"?p.content:p.content.map(i=>({type:"text",text:i.type==="text"?i.text:""}))),e.tools?.length&&(o.tools=e.tools.map(i=>({name:i.name,description:i.description,input_schema:i.parameters})));const l=await fetch(t,{method:"POST",headers:{"x-api-key":c.apiKey,"anthropic-version":"2023-06-01","Content-Type":"application/json"},body:JSON.stringify(o),signal:e.signal});if(!l.ok){const i=await l.text();throw new Error(`[vue-llm] Anthropic API error ${l.status}: ${i}`)}if(!l.body)throw new Error("[vue-llm] No response body from Anthropic");let f;const u=new Promise(i=>{f=i});let n="";return{stream:l.body.pipeThrough(new TextDecoderStream).pipeThrough(new w).pipeThrough(new TransformStream({transform(i,d){let s;try{s=JSON.parse(i.data)}catch{return}switch(i.event??s.type){case"content_block_start":{const a=s.content_block;a?.type==="tool_use"&&(n=a.id,d.enqueue({type:"tool-call-start",toolCallId:n,toolName:a.name}));break}case"content_block_delta":{const a=s.delta;a?.type==="text_delta"&&a.text&&d.enqueue({type:"text-delta",text:a.text}),a?.type==="thinking_delta"&&a.text&&d.enqueue({type:"reasoning-delta",text:a.text}),a?.type==="input_json_delta"&&a.partial_json&&d.enqueue({type:"tool-call-delta",toolCallId:n,args:a.partial_json});break}case"content_block_stop":{n&&(d.enqueue({type:"tool-call-end",toolCallId:n}),n="");break}case"message_delta":{const a=s.delta,h=s.usage,g=a?.stop_reason==="tool_use"?"tool-calls":a?.stop_reason==="max_tokens"?"length":"stop";d.enqueue({type:"finish",finishReason:g,usage:h?{promptTokens:0,completionTokens:h.output_tokens??0,totalTokens:h.output_tokens??0}:void 0}),f({finishReason:g,usage:void 0});break}case"error":{const a=s.error;d.enqueue({type:"error",error:new Error(`[vue-llm] Anthropic stream error: ${a?.message??"unknown"}`)});break}}}})),response:u}}}}function k(c){return c.map(e=>{if(e.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:e.toolCallId,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)}]};if(e.role==="assistant"&&e.toolCalls?.length){const t=[];typeof e.content=="string"&&e.content&&t.push({type:"text",text:e.content});for(const p of e.toolCalls)t.push({type:"tool_use",id:p.id,name:p.name,input:p.args});return{role:"assistant",content:t}}return{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?{type:"text",text:t.text}:t.type==="image"?{type:"image",source:{type:"url",url:t.url,media_type:t.mediaType??"image/png"}}:t)}})}function b(c){return{id:"ollama",supportsStreaming:!0,validateConfig(){},async chat(e){const t=(c?.baseURL??"http://localhost:11434")+"/api/chat",p={model:e.model,messages:T(e.messages),stream:!0};e.tools?.length&&(p.tools=e.tools.map(n=>({type:"function",function:{name:n.name,description:n.description,parameters:n.parameters}})));const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:e.signal});if(!r.ok){const n=await r.text();throw new Error(`[vue-llm] Ollama API error ${r.status}: ${n}`)}if(!r.body)throw new Error("[vue-llm] No response body from Ollama");let o;const l=new Promise(n=>{o=n});let f="";return{stream:r.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(n,m){f+=n;const i=f.split(`
6
- `);f=i.pop()??"";for(const d of i){if(!d.trim())continue;let s;try{s=JSON.parse(d)}catch{continue}if(s.message?.content&&m.enqueue({type:"text-delta",text:s.message.content}),s.message?.tool_calls)for(const y of s.message.tool_calls){const a=`ollama-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;m.enqueue({type:"tool-call-start",toolCallId:a,toolName:y.function.name}),m.enqueue({type:"tool-call-delta",toolCallId:a,args:JSON.stringify(y.function.arguments)}),m.enqueue({type:"tool-call-end",toolCallId:a})}s.done&&(m.enqueue({type:"finish",finishReason:"stop"}),o({finishReason:"stop",usage:s.eval_count?{promptTokens:s.prompt_eval_count??0,completionTokens:s.eval_count,totalTokens:(s.prompt_eval_count??0)+s.eval_count}:void 0}))}}})),response:l}}}}function T(c){return c.map(e=>({role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?t.text:"").join("")}))}exports.createAnthropic=x;exports.createOllama=b;exports.createOpenAI=_;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class k extends TransformStream{constructor(){let e="";super({transform(t,u){e+=t;const s=e.split(`
2
+ `);e=s.pop()??"";let o={};for(const c of s){if(c===""){o.data!==void 0&&u.enqueue({event:o.event,data:o.data,id:o.id,retry:o.retry}),o={};continue}if(c.startsWith(":"))continue;const d=c.indexOf(":");if(d===-1)continue;const f=c.slice(0,d),i=c.slice(d+1).replace(/^ /,"");switch(f){case"event":o.event=i;break;case"data":o.data=o.data!==void 0?o.data+`
3
+ `+i:i;break;case"id":o.id=i;break;case"retry":o.retry=parseInt(i,10);break}}},flush(t){if(e.trim()){const u=e.split(`
4
+ `);let s={};for(const o of u){if(o===""&&s.data!==void 0){t.enqueue({event:s.event,data:s.data,id:s.id,retry:s.retry}),s={};continue}const c=o.indexOf(":");if(c===-1||o.startsWith(":"))continue;const d=o.slice(0,c),f=o.slice(c+1).replace(/^ /,"");d==="data"&&(s.data=s.data!==void 0?s.data+`
5
+ `+f:f)}}}})}}function v(p){return{id:"openai",supportsStreaming:!0,validateConfig(){if(!p.apiKey)throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');if(!p.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true.")},async chat(e){const t=p.baseURL??"https://api.openai.com/v1/chat/completions",u={model:e.model,messages:T(e.messages),stream:!0,stream_options:{include_usage:!0}};e.tools?.length&&(u.tools=e.tools.map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})));const s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${p.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:e.signal});if(!s.ok){const f=await s.text();throw new Error(`[vue-llm] OpenAI API error ${s.status}: ${f}`)}if(!s.body)throw new Error("[vue-llm] No response body from OpenAI");let o;const c=new Promise(f=>{o=f});return{stream:s.body.pipeThrough(new TextDecoderStream).pipeThrough(new k).pipeThrough(new TransformStream({transform(f,i){if(f.data==="[DONE]")return;let m;try{m=JSON.parse(f.data)}catch{return}const l=m.choices?.[0];if(!l){m.usage&&o({finishReason:"stop",usage:{promptTokens:m.usage.prompt_tokens,completionTokens:m.usage.completion_tokens,totalTokens:m.usage.total_tokens}});return}const r=l.delta;if(r.content&&i.enqueue({type:"text-delta",text:r.content}),r.tool_calls)for(const n of r.tool_calls)n.id&&i.enqueue({type:"tool-call-start",toolCallId:n.id,toolName:n.function?.name??""}),n.function?.arguments&&i.enqueue({type:"tool-call-delta",toolCallId:n.id??"",args:n.function.arguments});if(l.finish_reason){const n=r.tool_calls?.filter(a=>a.id)??[];for(const a of n)a.id&&i.enqueue({type:"tool-call-end",toolCallId:a.id});const h=l.finish_reason==="tool_calls"?"tool-calls":l.finish_reason==="length"?"length":"stop";i.enqueue({type:"finish",finishReason:h,usage:void 0})}}})),response:c}}}}function T(p){return p.map(e=>e.role==="tool"?{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.toolCallId}:e.role==="assistant"&&e.toolCalls?.length?{role:"assistant",content:typeof e.content=="string"&&e.content?e.content:null,tool_calls:e.toolCalls.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:typeof t.args=="string"?t.args:JSON.stringify(t.args)}}))}:{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?{type:"text",text:t.text}:t.type==="image"?{type:"image_url",image_url:{url:t.url}}:t)})}function x(p){return{id:"anthropic",supportsStreaming:!0,validateConfig(){if(!p.apiKey)throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');if(!p.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true.")},async chat(e){const t=(p.baseURL??"https://api.anthropic.com")+"/v1/messages",u=e.messages.find(l=>l.role==="system"),s=e.messages.filter(l=>l.role!=="system"),o={model:e.model,messages:_(s),max_tokens:e.providerOptions?.maxTokens??4096,stream:!0};u&&(o.system=typeof u.content=="string"?u.content:u.content.map(l=>({type:"text",text:l.type==="text"?l.text:""}))),e.tools?.length&&(o.tools=e.tools.map(l=>({name:l.name,description:l.description,input_schema:l.parameters})));const c=await fetch(t,{method:"POST",headers:{"x-api-key":p.apiKey,"anthropic-version":"2023-06-01","Content-Type":"application/json"},body:JSON.stringify(o),signal:e.signal});if(!c.ok){const l=await c.text();throw new Error(`[vue-llm] Anthropic API error ${c.status}: ${l}`)}if(!c.body)throw new Error("[vue-llm] No response body from Anthropic");let d;const f=new Promise(l=>{d=l});let i="";return{stream:c.body.pipeThrough(new TextDecoderStream).pipeThrough(new k).pipeThrough(new TransformStream({transform(l,r){let n;try{n=JSON.parse(l.data)}catch{return}switch(l.event??n.type){case"content_block_start":{const a=n.content_block;a?.type==="tool_use"&&(i=a.id,r.enqueue({type:"tool-call-start",toolCallId:i,toolName:a.name}));break}case"content_block_delta":{const a=n.delta;a?.type==="text_delta"&&a.text&&r.enqueue({type:"text-delta",text:a.text}),a?.type==="thinking_delta"&&a.text&&r.enqueue({type:"reasoning-delta",text:a.text}),a?.type==="input_json_delta"&&a.partial_json&&r.enqueue({type:"tool-call-delta",toolCallId:i,args:a.partial_json});break}case"content_block_stop":{i&&(r.enqueue({type:"tool-call-end",toolCallId:i}),i="");break}case"message_delta":{const a=n.delta,w=n.usage,g=a?.stop_reason==="tool_use"?"tool-calls":a?.stop_reason==="max_tokens"?"length":"stop";r.enqueue({type:"finish",finishReason:g,usage:w?{promptTokens:0,completionTokens:w.output_tokens??0,totalTokens:w.output_tokens??0}:void 0}),d({finishReason:g,usage:void 0});break}case"error":{const a=n.error;r.enqueue({type:"error",error:new Error(`[vue-llm] Anthropic stream error: ${a?.message??"unknown"}`)});break}}}})),response:f}}}}function _(p){return p.map(e=>{if(e.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:e.toolCallId,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)}]};if(e.role==="assistant"&&e.toolCalls?.length){const t=[];typeof e.content=="string"&&e.content&&t.push({type:"text",text:e.content});for(const u of e.toolCalls)t.push({type:"tool_use",id:u.id,name:u.name,input:u.args});return{role:"assistant",content:t}}return{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?{type:"text",text:t.text}:t.type==="image"?{type:"image",source:{type:"url",url:t.url,media_type:t.mediaType??"image/png"}}:t)}})}function b(p){return{id:"google",supportsStreaming:!0,validateConfig(){if(!p.apiKey)throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');if(!p.dangerouslyAllowBrowser&&typeof window<"u")throw new Error("[vue-llm] API keys must not be used in the browser. Use a server proxy to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true.")},async chat(e){const u=`${p.baseURL??"https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${p.apiKey}`,s={contents:C(e.messages)},o=e.messages.find(r=>r.role==="system");o&&(s.systemInstruction={parts:[{text:typeof o.content=="string"?o.content:""}]}),e.tools?.length&&(s.tools=[{functionDeclarations:e.tools.map(r=>({name:r.name,description:r.description,parameters:r.parameters}))}]),s.generationConfig={...e.providerOptions?.response_format?.type==="json_object"?{responseMimeType:"application/json"}:{}};const c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:e.signal});if(!c.ok){const r=await c.text();throw new Error(`[vue-llm] Google AI API error ${c.status}: ${r}`)}if(!c.body)throw new Error("[vue-llm] No response body from Google AI");let d;const f=new Promise(r=>{d=r}),i=new Map;let m=0;return{stream:c.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({buffer:"",transform(r,n){this.buffer+=r;const h=this.buffer.split(`
6
+ `);this.buffer=h.pop();for(const a of h)a.startsWith("data: ")&&n.enqueue(a.slice(6))},flush(r){const n=this.buffer.trim();n.startsWith("data: ")&&r.enqueue(n.slice(6))}})).pipeThrough(new TransformStream({transform(r,n){let h;try{h=JSON.parse(r)}catch{return}const a=h.candidates?.[0];if(!a)return;const w=a.content?.parts;if(w){for(const g of w)if(g.text!==void 0&&n.enqueue({type:"text-delta",text:g.text}),g.functionCall){const y=`tc_gemini_${++m}`;i.set(g.functionCall.name,y),n.enqueue({type:"tool-call-start",toolCallId:y,toolName:g.functionCall.name}),n.enqueue({type:"tool-call-delta",toolCallId:y,args:JSON.stringify(g.functionCall.args??{})}),n.enqueue({type:"tool-call-end",toolCallId:y})}}if(a.finishReason){const g=a.finishReason==="STOP"?"stop":a.finishReason==="MAX_TOKENS"?"length":a.finishReason==="TOOL_CALLS"?"tool-calls":"stop",y=h.usageMetadata;n.enqueue({type:"finish",finishReason:g,usage:y?{promptTokens:y.promptTokenCount??0,completionTokens:y.candidatesTokenCount??0,totalTokens:y.totalTokenCount??0}:void 0}),d({finishReason:g,usage:y?{promptTokens:y.promptTokenCount??0,completionTokens:y.candidatesTokenCount??0,totalTokens:y.totalTokenCount??0}:void 0})}}})),response:f}}}}function C(p){const e=[];for(const t of p){if(t.role==="system")continue;if(t.role==="tool"){e.push({role:"function",parts:[{functionResponse:{name:t.toolCallId??"",response:{result:typeof t.content=="string"?JSON.parse(t.content):t.content}}}]});continue}const u=t.role==="assistant"?"model":"user",s=[];if(typeof t.content=="string")t.content&&s.push({text:t.content});else if(Array.isArray(t.content))for(const o of t.content)o.type==="text"&&s.push({text:o.text}),o.type==="image"&&s.push({inlineData:{mimeType:"image/jpeg",data:o.url}});if(t.toolCalls?.length)for(const o of t.toolCalls)s.push({functionCall:{name:o.name,args:typeof o.args=="string"?JSON.parse(o.args):o.args}});s.length>0&&e.push({role:u,parts:s})}return e}function I(p){return{id:"ollama",supportsStreaming:!0,validateConfig(){},async chat(e){const t=(p?.baseURL??"http://localhost:11434")+"/api/chat",u={model:e.model,messages:S(e.messages),stream:!0};e.tools?.length&&(u.tools=e.tools.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.parameters}})));const s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:e.signal});if(!s.ok){const i=await s.text();throw new Error(`[vue-llm] Ollama API error ${s.status}: ${i}`)}if(!s.body)throw new Error("[vue-llm] No response body from Ollama");let o;const c=new Promise(i=>{o=i});let d="";return{stream:s.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(i,m){d+=i;const l=d.split(`
7
+ `);d=l.pop()??"";for(const r of l){if(!r.trim())continue;let n;try{n=JSON.parse(r)}catch{continue}if(n.message?.content&&m.enqueue({type:"text-delta",text:n.message.content}),n.message?.tool_calls)for(const h of n.message.tool_calls){const a=`ollama-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;m.enqueue({type:"tool-call-start",toolCallId:a,toolName:h.function.name}),m.enqueue({type:"tool-call-delta",toolCallId:a,args:JSON.stringify(h.function.arguments)}),m.enqueue({type:"tool-call-end",toolCallId:a})}n.done&&(m.enqueue({type:"finish",finishReason:"stop"}),o({finishReason:"stop",usage:n.eval_count?{promptTokens:n.prompt_eval_count??0,completionTokens:n.eval_count,totalTokens:(n.prompt_eval_count??0)+n.eval_count}:void 0}))}}})),response:c}}}}function S(p){return p.map(e=>({role:e.role,content:typeof e.content=="string"?e.content:e.content.map(t=>t.type==="text"?t.text:"").join("")}))}exports.createAnthropic=x;exports.createGoogle=b;exports.createOllama=I;exports.createOpenAI=v;
@@ -2,5 +2,7 @@ export { createOpenAI } from './providers/openai';
2
2
  export type { OpenAIConfig } from './providers/openai';
3
3
  export { createAnthropic } from './providers/anthropic';
4
4
  export type { AnthropicConfig } from './providers/anthropic';
5
+ export { createGoogle } from './providers/google';
6
+ export type { GoogleConfig } from './providers/google';
5
7
  export { createOllama } from './providers/ollama';
6
8
  export type { OllamaConfig } from './providers/ollama';
package/dist/providers.js CHANGED
@@ -1,16 +1,16 @@
1
- class w extends TransformStream {
1
+ class k extends TransformStream {
2
2
  constructor() {
3
3
  let e = "";
4
4
  super({
5
- transform(t, p) {
5
+ transform(t, u) {
6
6
  e += t;
7
- const r = e.split(`
7
+ const s = e.split(`
8
8
  `);
9
- e = r.pop() ?? "";
9
+ e = s.pop() ?? "";
10
10
  let o = {};
11
- for (const l of r) {
12
- if (l === "") {
13
- o.data !== void 0 && p.enqueue({
11
+ for (const c of s) {
12
+ if (c === "") {
13
+ o.data !== void 0 && u.enqueue({
14
14
  event: o.event,
15
15
  data: o.data,
16
16
  id: o.id,
@@ -18,110 +18,110 @@ class w extends TransformStream {
18
18
  }), o = {};
19
19
  continue;
20
20
  }
21
- if (l.startsWith(":")) continue;
22
- const f = l.indexOf(":");
23
- if (f === -1) continue;
24
- const u = l.slice(0, f), n = l.slice(f + 1).replace(/^ /, "");
25
- switch (u) {
21
+ if (c.startsWith(":")) continue;
22
+ const d = c.indexOf(":");
23
+ if (d === -1) continue;
24
+ const f = c.slice(0, d), i = c.slice(d + 1).replace(/^ /, "");
25
+ switch (f) {
26
26
  case "event":
27
- o.event = n;
27
+ o.event = i;
28
28
  break;
29
29
  case "data":
30
30
  o.data = o.data !== void 0 ? o.data + `
31
- ` + n : n;
31
+ ` + i : i;
32
32
  break;
33
33
  case "id":
34
- o.id = n;
34
+ o.id = i;
35
35
  break;
36
36
  case "retry":
37
- o.retry = parseInt(n, 10);
37
+ o.retry = parseInt(i, 10);
38
38
  break;
39
39
  }
40
40
  }
41
41
  },
42
42
  flush(t) {
43
43
  if (e.trim()) {
44
- const p = e.split(`
44
+ const u = e.split(`
45
45
  `);
46
- let r = {};
47
- for (const o of p) {
48
- if (o === "" && r.data !== void 0) {
46
+ let s = {};
47
+ for (const o of u) {
48
+ if (o === "" && s.data !== void 0) {
49
49
  t.enqueue({
50
- event: r.event,
51
- data: r.data,
52
- id: r.id,
53
- retry: r.retry
54
- }), r = {};
50
+ event: s.event,
51
+ data: s.data,
52
+ id: s.id,
53
+ retry: s.retry
54
+ }), s = {};
55
55
  continue;
56
56
  }
57
- const l = o.indexOf(":");
58
- if (l === -1 || o.startsWith(":")) continue;
59
- const f = o.slice(0, l), u = o.slice(l + 1).replace(/^ /, "");
60
- f === "data" && (r.data = r.data !== void 0 ? r.data + `
61
- ` + u : u);
57
+ const c = o.indexOf(":");
58
+ if (c === -1 || o.startsWith(":")) continue;
59
+ const d = o.slice(0, c), f = o.slice(c + 1).replace(/^ /, "");
60
+ d === "data" && (s.data = s.data !== void 0 ? s.data + `
61
+ ` + f : f);
62
62
  }
63
63
  }
64
64
  }
65
65
  });
66
66
  }
67
67
  }
68
- function k(c) {
68
+ function b(p) {
69
69
  return {
70
70
  id: "openai",
71
71
  supportsStreaming: !0,
72
72
  validateConfig() {
73
- if (!c.apiKey)
73
+ if (!p.apiKey)
74
74
  throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');
75
- if (!c.dangerouslyAllowBrowser && typeof window < "u")
75
+ if (!p.dangerouslyAllowBrowser && typeof window < "u")
76
76
  throw new Error(
77
77
  "[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true."
78
78
  );
79
79
  },
80
80
  async chat(e) {
81
- const t = c.baseURL ?? "https://api.openai.com/v1/chat/completions", p = {
81
+ const t = p.baseURL ?? "https://api.openai.com/v1/chat/completions", u = {
82
82
  model: e.model,
83
- messages: _(e.messages),
83
+ messages: v(e.messages),
84
84
  stream: !0,
85
85
  stream_options: { include_usage: !0 }
86
86
  };
87
- e.tools?.length && (p.tools = e.tools.map((u) => ({
87
+ e.tools?.length && (u.tools = e.tools.map((f) => ({
88
88
  type: "function",
89
89
  function: {
90
- name: u.name,
91
- description: u.description,
92
- parameters: u.parameters
90
+ name: f.name,
91
+ description: f.description,
92
+ parameters: f.parameters
93
93
  }
94
94
  })));
95
- const r = await fetch(t, {
95
+ const s = await fetch(t, {
96
96
  method: "POST",
97
97
  headers: {
98
- Authorization: `Bearer ${c.apiKey}`,
98
+ Authorization: `Bearer ${p.apiKey}`,
99
99
  "Content-Type": "application/json"
100
100
  },
101
- body: JSON.stringify(p),
101
+ body: JSON.stringify(u),
102
102
  signal: e.signal
103
103
  });
104
- if (!r.ok) {
105
- const u = await r.text();
106
- throw new Error(`[vue-llm] OpenAI API error ${r.status}: ${u}`);
104
+ if (!s.ok) {
105
+ const f = await s.text();
106
+ throw new Error(`[vue-llm] OpenAI API error ${s.status}: ${f}`);
107
107
  }
108
- if (!r.body)
108
+ if (!s.body)
109
109
  throw new Error("[vue-llm] No response body from OpenAI");
110
110
  let o;
111
- const l = new Promise((u) => {
112
- o = u;
111
+ const c = new Promise((f) => {
112
+ o = f;
113
113
  });
114
- return { stream: r.body.pipeThrough(new TextDecoderStream()).pipeThrough(new w()).pipeThrough(new TransformStream({
115
- transform(u, n) {
116
- if (u.data === "[DONE]") return;
114
+ return { stream: s.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
115
+ transform(f, i) {
116
+ if (f.data === "[DONE]") return;
117
117
  let m;
118
118
  try {
119
- m = JSON.parse(u.data);
119
+ m = JSON.parse(f.data);
120
120
  } catch {
121
121
  return;
122
122
  }
123
- const i = m.choices?.[0];
124
- if (!i) {
123
+ const l = m.choices?.[0];
124
+ if (!l) {
125
125
  m.usage && o({
126
126
  finishReason: "stop",
127
127
  usage: {
@@ -132,32 +132,32 @@ function k(c) {
132
132
  });
133
133
  return;
134
134
  }
135
- const d = i.delta;
136
- if (d.content && n.enqueue({ type: "text-delta", text: d.content }), d.tool_calls)
137
- for (const s of d.tool_calls)
138
- s.id && n.enqueue({
135
+ const r = l.delta;
136
+ if (r.content && i.enqueue({ type: "text-delta", text: r.content }), r.tool_calls)
137
+ for (const n of r.tool_calls)
138
+ n.id && i.enqueue({
139
139
  type: "tool-call-start",
140
- toolCallId: s.id,
141
- toolName: s.function?.name ?? ""
142
- }), s.function?.arguments && n.enqueue({
140
+ toolCallId: n.id,
141
+ toolName: n.function?.name ?? ""
142
+ }), n.function?.arguments && i.enqueue({
143
143
  type: "tool-call-delta",
144
- toolCallId: s.id ?? "",
145
- args: s.function.arguments
144
+ toolCallId: n.id ?? "",
145
+ args: n.function.arguments
146
146
  });
147
- if (i.finish_reason) {
148
- const s = d.tool_calls?.filter((a) => a.id) ?? [];
149
- for (const a of s)
150
- a.id && n.enqueue({ type: "tool-call-end", toolCallId: a.id });
151
- const y = i.finish_reason === "tool_calls" ? "tool-calls" : i.finish_reason === "length" ? "length" : "stop";
152
- n.enqueue({ type: "finish", finishReason: y, usage: void 0 });
147
+ if (l.finish_reason) {
148
+ const n = r.tool_calls?.filter((a) => a.id) ?? [];
149
+ for (const a of n)
150
+ a.id && i.enqueue({ type: "tool-call-end", toolCallId: a.id });
151
+ const h = l.finish_reason === "tool_calls" ? "tool-calls" : l.finish_reason === "length" ? "length" : "stop";
152
+ i.enqueue({ type: "finish", finishReason: h, usage: void 0 });
153
153
  }
154
154
  }
155
- })), response: l };
155
+ })), response: c };
156
156
  }
157
157
  };
158
158
  }
159
- function _(c) {
160
- return c.map((e) => e.role === "tool" ? {
159
+ function v(p) {
160
+ return p.map((e) => e.role === "tool" ? {
161
161
  role: "tool",
162
162
  content: typeof e.content == "string" ? e.content : JSON.stringify(e.content),
163
163
  tool_call_id: e.toolCallId
@@ -177,94 +177,94 @@ function _(c) {
177
177
  content: typeof e.content == "string" ? e.content : e.content.map((t) => t.type === "text" ? { type: "text", text: t.text } : t.type === "image" ? { type: "image_url", image_url: { url: t.url } } : t)
178
178
  });
179
179
  }
180
- function b(c) {
180
+ function C(p) {
181
181
  return {
182
182
  id: "anthropic",
183
183
  supportsStreaming: !0,
184
184
  validateConfig() {
185
- if (!c.apiKey)
185
+ if (!p.apiKey)
186
186
  throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');
187
- if (!c.dangerouslyAllowBrowser && typeof window < "u")
187
+ if (!p.dangerouslyAllowBrowser && typeof window < "u")
188
188
  throw new Error(
189
189
  "[vue-llm] API keys must not be used in the browser. Use a server proxy (/api/chat) to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true."
190
190
  );
191
191
  },
192
192
  async chat(e) {
193
- const t = (c.baseURL ?? "https://api.anthropic.com") + "/v1/messages", p = e.messages.find((i) => i.role === "system"), r = e.messages.filter((i) => i.role !== "system"), o = {
193
+ const t = (p.baseURL ?? "https://api.anthropic.com") + "/v1/messages", u = e.messages.find((l) => l.role === "system"), s = e.messages.filter((l) => l.role !== "system"), o = {
194
194
  model: e.model,
195
- messages: v(r),
195
+ messages: x(s),
196
196
  max_tokens: e.providerOptions?.maxTokens ?? 4096,
197
197
  stream: !0
198
198
  };
199
- p && (o.system = typeof p.content == "string" ? p.content : p.content.map((i) => ({ type: "text", text: i.type === "text" ? i.text : "" }))), e.tools?.length && (o.tools = e.tools.map((i) => ({
200
- name: i.name,
201
- description: i.description,
202
- input_schema: i.parameters
199
+ u && (o.system = typeof u.content == "string" ? u.content : u.content.map((l) => ({ type: "text", text: l.type === "text" ? l.text : "" }))), e.tools?.length && (o.tools = e.tools.map((l) => ({
200
+ name: l.name,
201
+ description: l.description,
202
+ input_schema: l.parameters
203
203
  })));
204
- const l = await fetch(t, {
204
+ const c = await fetch(t, {
205
205
  method: "POST",
206
206
  headers: {
207
- "x-api-key": c.apiKey,
207
+ "x-api-key": p.apiKey,
208
208
  "anthropic-version": "2023-06-01",
209
209
  "Content-Type": "application/json"
210
210
  },
211
211
  body: JSON.stringify(o),
212
212
  signal: e.signal
213
213
  });
214
- if (!l.ok) {
215
- const i = await l.text();
216
- throw new Error(`[vue-llm] Anthropic API error ${l.status}: ${i}`);
214
+ if (!c.ok) {
215
+ const l = await c.text();
216
+ throw new Error(`[vue-llm] Anthropic API error ${c.status}: ${l}`);
217
217
  }
218
- if (!l.body)
218
+ if (!c.body)
219
219
  throw new Error("[vue-llm] No response body from Anthropic");
220
- let f;
221
- const u = new Promise((i) => {
222
- f = i;
220
+ let d;
221
+ const f = new Promise((l) => {
222
+ d = l;
223
223
  });
224
- let n = "";
225
- return { stream: l.body.pipeThrough(new TextDecoderStream()).pipeThrough(new w()).pipeThrough(new TransformStream({
226
- transform(i, d) {
227
- let s;
224
+ let i = "";
225
+ return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new k()).pipeThrough(new TransformStream({
226
+ transform(l, r) {
227
+ let n;
228
228
  try {
229
- s = JSON.parse(i.data);
229
+ n = JSON.parse(l.data);
230
230
  } catch {
231
231
  return;
232
232
  }
233
- switch (i.event ?? s.type) {
233
+ switch (l.event ?? n.type) {
234
234
  case "content_block_start": {
235
- const a = s.content_block;
236
- a?.type === "tool_use" && (n = a.id, d.enqueue({
235
+ const a = n.content_block;
236
+ a?.type === "tool_use" && (i = a.id, r.enqueue({
237
237
  type: "tool-call-start",
238
- toolCallId: n,
238
+ toolCallId: i,
239
239
  toolName: a.name
240
240
  }));
241
241
  break;
242
242
  }
243
243
  case "content_block_delta": {
244
- const a = s.delta;
245
- a?.type === "text_delta" && a.text && d.enqueue({ type: "text-delta", text: a.text }), a?.type === "thinking_delta" && a.text && d.enqueue({ type: "reasoning-delta", text: a.text }), a?.type === "input_json_delta" && a.partial_json && d.enqueue({
244
+ const a = n.delta;
245
+ a?.type === "text_delta" && a.text && r.enqueue({ type: "text-delta", text: a.text }), a?.type === "thinking_delta" && a.text && r.enqueue({ type: "reasoning-delta", text: a.text }), a?.type === "input_json_delta" && a.partial_json && r.enqueue({
246
246
  type: "tool-call-delta",
247
- toolCallId: n,
247
+ toolCallId: i,
248
248
  args: a.partial_json
249
249
  });
250
250
  break;
251
251
  }
252
252
  case "content_block_stop": {
253
- n && (d.enqueue({ type: "tool-call-end", toolCallId: n }), n = "");
253
+ i && (r.enqueue({ type: "tool-call-end", toolCallId: i }), i = "");
254
254
  break;
255
255
  }
256
256
  case "message_delta": {
257
- const a = s.delta, h = s.usage, g = a?.stop_reason === "tool_use" ? "tool-calls" : a?.stop_reason === "max_tokens" ? "length" : "stop";
258
- d.enqueue({
257
+ const a = n.delta, w = n.usage, g = a?.stop_reason === "tool_use" ? "tool-calls" : a?.stop_reason === "max_tokens" ? "length" : "stop";
258
+ r.enqueue({
259
259
  type: "finish",
260
260
  finishReason: g,
261
- usage: h ? { promptTokens: 0, completionTokens: h.output_tokens ?? 0, totalTokens: h.output_tokens ?? 0 } : void 0
262
- }), f({ finishReason: g, usage: void 0 });
261
+ usage: w ? { promptTokens: 0, completionTokens: w.output_tokens ?? 0, totalTokens: w.output_tokens ?? 0 } : void 0
262
+ }), d({ finishReason: g, usage: void 0 });
263
263
  break;
264
264
  }
265
265
  case "error": {
266
- const a = s.error;
267
- d.enqueue({
266
+ const a = n.error;
267
+ r.enqueue({
268
268
  type: "error",
269
269
  error: new Error(`[vue-llm] Anthropic stream error: ${a?.message ?? "unknown"}`)
270
270
  });
@@ -272,12 +272,12 @@ function b(c) {
272
272
  }
273
273
  }
274
274
  }
275
- })), response: u };
275
+ })), response: f };
276
276
  }
277
277
  };
278
278
  }
279
- function v(c) {
280
- return c.map((e) => {
279
+ function x(p) {
280
+ return p.map((e) => {
281
281
  if (e.role === "tool")
282
282
  return {
283
283
  role: "user",
@@ -290,12 +290,12 @@ function v(c) {
290
290
  if (e.role === "assistant" && e.toolCalls?.length) {
291
291
  const t = [];
292
292
  typeof e.content == "string" && e.content && t.push({ type: "text", text: e.content });
293
- for (const p of e.toolCalls)
293
+ for (const u of e.toolCalls)
294
294
  t.push({
295
295
  type: "tool_use",
296
- id: p.id,
297
- name: p.name,
298
- input: p.args
296
+ id: u.id,
297
+ name: u.name,
298
+ input: u.args
299
299
  });
300
300
  return { role: "assistant", content: t };
301
301
  }
@@ -308,92 +308,235 @@ function v(c) {
308
308
  };
309
309
  });
310
310
  }
311
- function T(c) {
311
+ function I(p) {
312
+ return {
313
+ id: "google",
314
+ supportsStreaming: !0,
315
+ validateConfig() {
316
+ if (!p.apiKey)
317
+ throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');
318
+ if (!p.dangerouslyAllowBrowser && typeof window < "u")
319
+ throw new Error(
320
+ "[vue-llm] API keys must not be used in the browser. Use a server proxy to keep keys safe. If you understand the risk, set dangerouslyAllowBrowser: true."
321
+ );
322
+ },
323
+ async chat(e) {
324
+ const u = `${p.baseURL ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${p.apiKey}`, s = {
325
+ contents: T(e.messages)
326
+ }, o = e.messages.find((r) => r.role === "system");
327
+ o && (s.systemInstruction = {
328
+ parts: [{ text: typeof o.content == "string" ? o.content : "" }]
329
+ }), e.tools?.length && (s.tools = [{
330
+ functionDeclarations: e.tools.map((r) => ({
331
+ name: r.name,
332
+ description: r.description,
333
+ parameters: r.parameters
334
+ }))
335
+ }]), s.generationConfig = {
336
+ ...e.providerOptions?.response_format?.type === "json_object" ? { responseMimeType: "application/json" } : {}
337
+ };
338
+ const c = await fetch(u, {
339
+ method: "POST",
340
+ headers: { "Content-Type": "application/json" },
341
+ body: JSON.stringify(s),
342
+ signal: e.signal
343
+ });
344
+ if (!c.ok) {
345
+ const r = await c.text();
346
+ throw new Error(`[vue-llm] Google AI API error ${c.status}: ${r}`);
347
+ }
348
+ if (!c.body)
349
+ throw new Error("[vue-llm] No response body from Google AI");
350
+ let d;
351
+ const f = new Promise((r) => {
352
+ d = r;
353
+ }), i = /* @__PURE__ */ new Map();
354
+ let m = 0;
355
+ return { stream: c.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
356
+ buffer: "",
357
+ transform(r, n) {
358
+ this.buffer += r;
359
+ const h = this.buffer.split(`
360
+ `);
361
+ this.buffer = h.pop();
362
+ for (const a of h)
363
+ a.startsWith("data: ") && n.enqueue(a.slice(6));
364
+ },
365
+ flush(r) {
366
+ const n = this.buffer.trim();
367
+ n.startsWith("data: ") && r.enqueue(n.slice(6));
368
+ }
369
+ })).pipeThrough(new TransformStream({
370
+ transform(r, n) {
371
+ let h;
372
+ try {
373
+ h = JSON.parse(r);
374
+ } catch {
375
+ return;
376
+ }
377
+ const a = h.candidates?.[0];
378
+ if (!a) return;
379
+ const w = a.content?.parts;
380
+ if (w) {
381
+ for (const g of w)
382
+ if (g.text !== void 0 && n.enqueue({ type: "text-delta", text: g.text }), g.functionCall) {
383
+ const y = `tc_gemini_${++m}`;
384
+ i.set(g.functionCall.name, y), n.enqueue({
385
+ type: "tool-call-start",
386
+ toolCallId: y,
387
+ toolName: g.functionCall.name
388
+ }), n.enqueue({
389
+ type: "tool-call-delta",
390
+ toolCallId: y,
391
+ args: JSON.stringify(g.functionCall.args ?? {})
392
+ }), n.enqueue({ type: "tool-call-end", toolCallId: y });
393
+ }
394
+ }
395
+ if (a.finishReason) {
396
+ const g = a.finishReason === "STOP" ? "stop" : a.finishReason === "MAX_TOKENS" ? "length" : a.finishReason === "TOOL_CALLS" ? "tool-calls" : "stop", y = h.usageMetadata;
397
+ n.enqueue({
398
+ type: "finish",
399
+ finishReason: g,
400
+ usage: y ? {
401
+ promptTokens: y.promptTokenCount ?? 0,
402
+ completionTokens: y.candidatesTokenCount ?? 0,
403
+ totalTokens: y.totalTokenCount ?? 0
404
+ } : void 0
405
+ }), d({
406
+ finishReason: g,
407
+ usage: y ? {
408
+ promptTokens: y.promptTokenCount ?? 0,
409
+ completionTokens: y.candidatesTokenCount ?? 0,
410
+ totalTokens: y.totalTokenCount ?? 0
411
+ } : void 0
412
+ });
413
+ }
414
+ }
415
+ })), response: f };
416
+ }
417
+ };
418
+ }
419
+ function T(p) {
420
+ const e = [];
421
+ for (const t of p) {
422
+ if (t.role === "system") continue;
423
+ if (t.role === "tool") {
424
+ e.push({
425
+ role: "function",
426
+ parts: [{
427
+ functionResponse: {
428
+ name: t.toolCallId ?? "",
429
+ response: { result: typeof t.content == "string" ? JSON.parse(t.content) : t.content }
430
+ }
431
+ }]
432
+ });
433
+ continue;
434
+ }
435
+ const u = t.role === "assistant" ? "model" : "user", s = [];
436
+ if (typeof t.content == "string")
437
+ t.content && s.push({ text: t.content });
438
+ else if (Array.isArray(t.content))
439
+ for (const o of t.content)
440
+ o.type === "text" && s.push({ text: o.text }), o.type === "image" && s.push({ inlineData: { mimeType: "image/jpeg", data: o.url } });
441
+ if (t.toolCalls?.length)
442
+ for (const o of t.toolCalls)
443
+ s.push({
444
+ functionCall: {
445
+ name: o.name,
446
+ args: typeof o.args == "string" ? JSON.parse(o.args) : o.args
447
+ }
448
+ });
449
+ s.length > 0 && e.push({ role: u, parts: s });
450
+ }
451
+ return e;
452
+ }
453
+ function S(p) {
312
454
  return {
313
455
  id: "ollama",
314
456
  supportsStreaming: !0,
315
457
  validateConfig() {
316
458
  },
317
459
  async chat(e) {
318
- const t = (c?.baseURL ?? "http://localhost:11434") + "/api/chat", p = {
460
+ const t = (p?.baseURL ?? "http://localhost:11434") + "/api/chat", u = {
319
461
  model: e.model,
320
- messages: x(e.messages),
462
+ messages: _(e.messages),
321
463
  stream: !0
322
464
  };
323
- e.tools?.length && (p.tools = e.tools.map((n) => ({
465
+ e.tools?.length && (u.tools = e.tools.map((i) => ({
324
466
  type: "function",
325
467
  function: {
326
- name: n.name,
327
- description: n.description,
328
- parameters: n.parameters
468
+ name: i.name,
469
+ description: i.description,
470
+ parameters: i.parameters
329
471
  }
330
472
  })));
331
- const r = await fetch(t, {
473
+ const s = await fetch(t, {
332
474
  method: "POST",
333
475
  headers: { "Content-Type": "application/json" },
334
- body: JSON.stringify(p),
476
+ body: JSON.stringify(u),
335
477
  signal: e.signal
336
478
  });
337
- if (!r.ok) {
338
- const n = await r.text();
339
- throw new Error(`[vue-llm] Ollama API error ${r.status}: ${n}`);
479
+ if (!s.ok) {
480
+ const i = await s.text();
481
+ throw new Error(`[vue-llm] Ollama API error ${s.status}: ${i}`);
340
482
  }
341
- if (!r.body)
483
+ if (!s.body)
342
484
  throw new Error("[vue-llm] No response body from Ollama");
343
485
  let o;
344
- const l = new Promise((n) => {
345
- o = n;
486
+ const c = new Promise((i) => {
487
+ o = i;
346
488
  });
347
- let f = "";
348
- return { stream: r.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
349
- transform(n, m) {
350
- f += n;
351
- const i = f.split(`
489
+ let d = "";
490
+ return { stream: s.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({
491
+ transform(i, m) {
492
+ d += i;
493
+ const l = d.split(`
352
494
  `);
353
- f = i.pop() ?? "";
354
- for (const d of i) {
355
- if (!d.trim()) continue;
356
- let s;
495
+ d = l.pop() ?? "";
496
+ for (const r of l) {
497
+ if (!r.trim()) continue;
498
+ let n;
357
499
  try {
358
- s = JSON.parse(d);
500
+ n = JSON.parse(r);
359
501
  } catch {
360
502
  continue;
361
503
  }
362
- if (s.message?.content && m.enqueue({ type: "text-delta", text: s.message.content }), s.message?.tool_calls)
363
- for (const y of s.message.tool_calls) {
504
+ if (n.message?.content && m.enqueue({ type: "text-delta", text: n.message.content }), n.message?.tool_calls)
505
+ for (const h of n.message.tool_calls) {
364
506
  const a = `ollama-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
365
507
  m.enqueue({
366
508
  type: "tool-call-start",
367
509
  toolCallId: a,
368
- toolName: y.function.name
510
+ toolName: h.function.name
369
511
  }), m.enqueue({
370
512
  type: "tool-call-delta",
371
513
  toolCallId: a,
372
- args: JSON.stringify(y.function.arguments)
514
+ args: JSON.stringify(h.function.arguments)
373
515
  }), m.enqueue({ type: "tool-call-end", toolCallId: a });
374
516
  }
375
- s.done && (m.enqueue({ type: "finish", finishReason: "stop" }), o({
517
+ n.done && (m.enqueue({ type: "finish", finishReason: "stop" }), o({
376
518
  finishReason: "stop",
377
- usage: s.eval_count ? {
378
- promptTokens: s.prompt_eval_count ?? 0,
379
- completionTokens: s.eval_count,
380
- totalTokens: (s.prompt_eval_count ?? 0) + s.eval_count
519
+ usage: n.eval_count ? {
520
+ promptTokens: n.prompt_eval_count ?? 0,
521
+ completionTokens: n.eval_count,
522
+ totalTokens: (n.prompt_eval_count ?? 0) + n.eval_count
381
523
  } : void 0
382
524
  }));
383
525
  }
384
526
  }
385
- })), response: l };
527
+ })), response: c };
386
528
  }
387
529
  };
388
530
  }
389
- function x(c) {
390
- return c.map((e) => ({
531
+ function _(p) {
532
+ return p.map((e) => ({
391
533
  role: e.role,
392
534
  content: typeof e.content == "string" ? e.content : e.content.map((t) => t.type === "text" ? t.text : "").join("")
393
535
  }));
394
536
  }
395
537
  export {
396
- b as createAnthropic,
397
- T as createOllama,
398
- k as createOpenAI
538
+ C as createAnthropic,
539
+ I as createGoogle,
540
+ S as createOllama,
541
+ b as createOpenAI
399
542
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue-llm",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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": [