vue-llm 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/composables/use-chat.d.ts +2 -1
- package/dist/composables/use-completion.d.ts +2 -1
- package/dist/composables/use-object.d.ts +2 -1
- package/dist/composables/use-prompt.d.ts +2 -1
- package/dist/index.cjs +3 -3
- package/dist/index.js +297 -287
- package/dist/providers/sse.d.ts +18 -0
- package/dist/providers/types.d.ts +5 -0
- package/dist/providers.cjs +4 -8
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +257 -321
- package/dist/server.cjs +2 -3
- package/dist/server.d.ts +8 -1
- package/dist/server.js +109 -100
- package/dist/sse-DU5m1n6r.js +104 -0
- package/dist/sse-PZGBuYKy.cjs +2 -0
- package/dist/utils/vue.d.ts +4 -0
- package/package.json +6 -4
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ChatRequest, ChatStreamChunk, LLMProvider } from './types';
|
|
2
|
+
import { type SSEEvent } from '../core/sse-parser';
|
|
3
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
4
|
+
export interface SSEProviderEvent extends SSEEvent {
|
|
5
|
+
json: unknown;
|
|
6
|
+
}
|
|
7
|
+
export interface SSEProviderConfig {
|
|
8
|
+
url: string | ((request: ChatRequest) => string);
|
|
9
|
+
id?: string;
|
|
10
|
+
name?: string;
|
|
11
|
+
method?: string;
|
|
12
|
+
headers?: HeadersInit | (() => MaybePromise<HeadersInit>);
|
|
13
|
+
credentials?: RequestCredentials;
|
|
14
|
+
body?: (request: ChatRequest) => unknown;
|
|
15
|
+
mapEvent?: (event: SSEProviderEvent) => ChatStreamChunk | ChatStreamChunk[] | null | undefined;
|
|
16
|
+
}
|
|
17
|
+
export declare function createSSEProvider(config: SSEProviderConfig): LLMProvider;
|
|
18
|
+
export {};
|
package/dist/providers.cjs
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("./file-DusIs8wR.cjs"),
|
|
2
|
-
`);
|
|
3
|
-
|
|
4
|
-
`);let i={};for(const t of a){if(t===""&&i.data!==void 0){n.enqueue({event:i.event,data:i.data,id:i.id,retry:i.retry}),i={};continue}const o=t.indexOf(":");if(o===-1||t.startsWith(":"))continue;const u=t.slice(0,o),d=t.slice(o+1).replace(/^ /,"");u==="data"&&(i.data=i.data!==void 0?i.data+`
|
|
5
|
-
`+d:d)}}}})}}function _(s){return{id:"openai",supportsStreaming:!0,validateConfig(){if(!s.apiKey)throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');if(!s.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 n=s.baseURL??"https://api.openai.com/v1/chat/completions",a={model:e.model,messages:k(e.messages),stream:!0,stream_options:{include_usage:!0}};e.providerOptions?.response_format&&(a.response_format=e.providerOptions.response_format),e.tools?.length&&(a.tools=e.tools.map(d=>({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})));const i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${s.apiKey}`,"Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(a),signal:e.signal});if(!i.ok)throw await v.createAPIError("openai","OpenAI API",i);if(!i.body)throw new Error("[vue-llm] No response body from OpenAI");let t;const o=new Promise(d=>{t=d});return{stream:i.body.pipeThrough(new TextDecoderStream).pipeThrough(new b).pipeThrough(new TransformStream({transform(d,f){if(d.data==="[DONE]")return;let y;try{y=JSON.parse(d.data)}catch{return}const c=y.choices?.[0];if(!c){y.usage&&t({finishReason:"stop",usage:{promptTokens:y.usage.prompt_tokens,completionTokens:y.usage.completion_tokens,totalTokens:y.usage.total_tokens}});return}const l=c.delta;if(l.content&&f.enqueue({type:"text-delta",text:l.content}),l.tool_calls)for(const p of l.tool_calls)p.id&&f.enqueue({type:"tool-call-start",toolCallId:p.id,toolName:p.function?.name??""}),p.function?.arguments&&f.enqueue({type:"tool-call-delta",toolCallId:p.id??"",args:p.function.arguments});if(c.finish_reason){const p=l.tool_calls?.filter(r=>r.id)??[];for(const r of p)r.id&&f.enqueue({type:"tool-call-end",toolCallId:r.id});const m=c.finish_reason==="tool_calls"?"tool-calls":c.finish_reason==="length"?"length":"stop";f.enqueue({type:"finish",finishReason:m,usage:void 0})}}})),response:o}}}}function k(s){return s.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(n=>({id:n.id,type:"function",function:{name:n.name,arguments:typeof n.args=="string"?n.args:JSON.stringify(n.args)}}))}:{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(x)})}function x(s){if(s.type==="text")return{type:"text",text:s.text};const e=T.resolveFilePart(s);if(e.mediaType.startsWith("image/"))return{type:"image_url",image_url:{url:e.url}};if(!e.base64)throw new Error(`[vue-llm] OpenAI requires ${e.mediaType} attachments as data URLs, got a remote URL`);if(e.mediaType==="application/pdf")return{type:"file",file:{filename:e.filename??"document.pdf",file_data:e.url}};const n=C[e.mediaType];if(n)return{type:"input_audio",input_audio:{data:e.base64,format:n}};if(T.isTextMediaType(e.mediaType))return{type:"text",text:T.decodeBase64Text(e.base64)};throw new Error(`[vue-llm] OpenAI does not support ${e.mediaType} attachments`)}const C={"audio/wav":"wav","audio/x-wav":"wav","audio/mpeg":"mp3","audio/mp3":"mp3"};function I(s){return{id:"anthropic",supportsStreaming:!0,validateConfig(){if(!s.apiKey)throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');if(!s.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 n=(s.baseURL??"https://api.anthropic.com")+"/v1/messages",a=e.messages.find(c=>c.role==="system"),i=e.messages.filter(c=>c.role!=="system"),t={model:e.model,messages:O(i),max_tokens:e.providerOptions?.maxTokens??4096,stream:!0};a&&(t.system=typeof a.content=="string"?a.content:a.content.map(c=>({type:"text",text:c.type==="text"?c.text:""}))),e.tools?.length&&(t.tools=e.tools.map(c=>({name:c.name,description:c.description,input_schema:c.parameters})));const o=await fetch(n,{method:"POST",headers:{"x-api-key":s.apiKey,"anthropic-version":"2023-06-01","Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(t),signal:e.signal});if(!o.ok)throw await v.createAPIError("anthropic","Anthropic API",o);if(!o.body)throw new Error("[vue-llm] No response body from Anthropic");let u;const d=new Promise(c=>{u=c});let f="";return{stream:o.body.pipeThrough(new TextDecoderStream).pipeThrough(new b).pipeThrough(new TransformStream({transform(c,l){let p;try{p=JSON.parse(c.data)}catch{return}switch(c.event??p.type){case"content_block_start":{const r=p.content_block;r?.type==="tool_use"&&(f=r.id,l.enqueue({type:"tool-call-start",toolCallId:f,toolName:r.name}));break}case"content_block_delta":{const r=p.delta;r?.type==="text_delta"&&r.text&&l.enqueue({type:"text-delta",text:r.text}),r?.type==="thinking_delta"&&r.text&&l.enqueue({type:"reasoning-delta",text:r.text}),r?.type==="input_json_delta"&&r.partial_json&&l.enqueue({type:"tool-call-delta",toolCallId:f,args:r.partial_json});break}case"content_block_stop":{f&&(l.enqueue({type:"tool-call-end",toolCallId:f}),f="");break}case"message_delta":{const r=p.delta,w=p.usage,g=r?.stop_reason==="tool_use"?"tool-calls":r?.stop_reason==="max_tokens"?"length":"stop";l.enqueue({type:"finish",finishReason:g,usage:w?{promptTokens:0,completionTokens:w.output_tokens??0,totalTokens:w.output_tokens??0}:void 0}),u({finishReason:g,usage:void 0});break}case"error":{const r=p.error;l.enqueue({type:"error",error:new Error(`[vue-llm] Anthropic stream error: ${r?.message??"unknown"}`)});break}}}})),response:d}}}}function O(s){return s.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 n=[];typeof e.content=="string"&&e.content&&n.push({type:"text",text:e.content});for(const a of e.toolCalls)n.push({type:"tool_use",id:a.id,name:a.name,input:a.args});return{role:"assistant",content:n}}return{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(A)}})}function A(s){if(s.type==="text")return{type:"text",text:s.text};const e=T.resolveFilePart(s),n=e.base64?{type:"base64",media_type:e.mediaType,data:e.base64}:{type:"url",url:e.url};if(e.mediaType.startsWith("image/"))return{type:"image",source:n};if(e.mediaType==="application/pdf")return{type:"document",source:n,...e.filename?{title:e.filename}:{}};if(T.isTextMediaType(e.mediaType)&&e.base64)return{type:"document",source:{type:"text",media_type:"text/plain",data:T.decodeBase64Text(e.base64)},...e.filename?{title:e.filename}:{}};throw new Error(`[vue-llm] Anthropic does not support ${e.mediaType} attachments`)}function S(s){return{id:"google",supportsStreaming:!0,validateConfig(){if(!s.apiKey)throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');if(!s.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 a=`${s.baseURL??"https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${s.apiKey}`,i={contents:P(e.messages)},t=e.messages.find(l=>l.role==="system");t&&(i.systemInstruction={parts:[{text:typeof t.content=="string"?t.content:""}]}),e.tools?.length&&(i.tools=[{functionDeclarations:e.tools.map(l=>({name:l.name,description:l.description,parameters:l.parameters}))}]),i.generationConfig={...e.providerOptions?.response_format?.type==="json_object"?{responseMimeType:"application/json"}:{}};const o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(i),signal:e.signal});if(!o.ok)throw await v.createAPIError("google","Google AI API",o);if(!o.body)throw new Error("[vue-llm] No response body from Google AI");let u;const d=new Promise(l=>{u=l});let f=0,y=!1;return{stream:o.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({buffer:"",transform(l,p){this.buffer+=l;const m=this.buffer.split(`
|
|
6
|
-
`);this.buffer=m.pop();for(const r of m)r.startsWith("data: ")&&p.enqueue(r.slice(6))},flush(l){const p=this.buffer.trim();p.startsWith("data: ")&&l.enqueue(p.slice(6))}})).pipeThrough(new TransformStream({transform(l,p){let m;try{m=JSON.parse(l)}catch{return}const r=m.candidates?.[0];if(!r)return;const w=r.content?.parts;if(w){for(const g of w)if(g.text!==void 0&&p.enqueue({type:"text-delta",text:g.text}),g.functionCall){const h=`tc_gemini_${++f}`;y=!0,p.enqueue({type:"tool-call-start",toolCallId:h,toolName:g.functionCall.name}),p.enqueue({type:"tool-call-delta",toolCallId:h,args:JSON.stringify(g.functionCall.args??{})}),p.enqueue({type:"tool-call-end",toolCallId:h})}}if(r.finishReason){const g=y?"tool-calls":r.finishReason==="MAX_TOKENS"?"length":"stop",h=m.usageMetadata;p.enqueue({type:"finish",finishReason:g,usage:h?{promptTokens:h.promptTokenCount??0,completionTokens:h.candidatesTokenCount??0,totalTokens:h.totalTokenCount??0}:void 0}),u({finishReason:g,usage:h?{promptTokens:h.promptTokenCount??0,completionTokens:h.candidatesTokenCount??0,totalTokens:h.totalTokenCount??0}:void 0})}}})),response:d}}}}function P(s){const e=[],n=new Map;for(const a of s){if(a.role==="system")continue;if(a.role==="tool"){const o={functionResponse:{name:n.get(a.toolCallId??"")??a.toolCallId??"",response:{result:N(a.content)}}},u=e.at(-1);u?.role==="user"&&u.parts.every(d=>d.functionResponse)?u.parts.push(o):e.push({role:"user",parts:[o]});continue}for(const o of a.toolCalls??[])n.set(o.id,o.name);const i=a.role==="assistant"?"model":"user",t=[];if(typeof a.content=="string")a.content&&t.push({text:a.content});else if(Array.isArray(a.content)){for(const o of a.content)if(o.type==="text"&&t.push({text:o.text}),o.type==="image"||o.type==="file"){const u=T.resolveFilePart(o);t.push(u.base64?{inlineData:{mimeType:u.mediaType,data:u.base64}}:{fileData:{mimeType:u.mediaType,fileUri:u.url}})}}if(a.toolCalls?.length)for(const o of a.toolCalls)t.push({functionCall:{name:o.name,args:typeof o.args=="string"?JSON.parse(o.args):o.args}});t.length>0&&e.push({role:i,parts:t})}return e}function N(s){if(typeof s!="string")return s;try{return JSON.parse(s)}catch{return s}}function R(s){return{id:"ollama",supportsStreaming:!0,validateConfig(){},async chat(e){const n=(s?.baseURL??"http://localhost:11434")+"/api/chat",a={model:e.model,messages:E(e.messages),stream:!0};e.tools?.length&&(a.tools=e.tools.map(y=>({type:"function",function:{name:y.name,description:y.description,parameters:y.parameters}})));const i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(a),signal:e.signal});if(!i.ok)throw await v.createAPIError("ollama","Ollama API",i);if(!i.body)throw new Error("[vue-llm] No response body from Ollama");let t;const o=new Promise(y=>{t=y});let u="",d=!1;return{stream:i.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(y,c){u+=y;const l=u.split(`
|
|
7
|
-
`);u=l.pop()??"";for(const p of l){if(!p.trim())continue;let m;try{m=JSON.parse(p)}catch{continue}if(m.message?.content&&c.enqueue({type:"text-delta",text:m.message.content}),m.message?.tool_calls)for(const r of m.message.tool_calls){d=!0;const w=`ollama-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;c.enqueue({type:"tool-call-start",toolCallId:w,toolName:r.function.name}),c.enqueue({type:"tool-call-delta",toolCallId:w,args:JSON.stringify(r.function.arguments)}),c.enqueue({type:"tool-call-end",toolCallId:w})}if(m.done){const r=d?"tool-calls":"stop";c.enqueue({type:"finish",finishReason:r}),t({finishReason:r,usage:m.eval_count?{promptTokens:m.prompt_eval_count??0,completionTokens:m.eval_count,totalTokens:(m.prompt_eval_count??0)+m.eval_count}:void 0})}}}})),response:o}}}}function E(s){const e=new Map;return s.map(n=>{if(n.role==="tool")return{role:"tool",content:typeof n.content=="string"?n.content:JSON.stringify(n.content),tool_name:e.get(n.toolCallId??"")};if(n.role==="assistant"&&n.toolCalls?.length){for(const t of n.toolCalls)e.set(t.id,t.name);return{role:"assistant",content:typeof n.content=="string"?n.content:"",tool_calls:n.toolCalls.map(t=>({function:{name:t.name,arguments:typeof t.args=="string"?JSON.parse(t.args):t.args}}))}}if(typeof n.content=="string")return{role:n.role,content:n.content};const a=[],i=[];for(const t of n.content){if(t.type==="text"){a.push(t.text);continue}const o=T.resolveFilePart(t);if(!o.base64)throw new Error("[vue-llm] Ollama requires attachments as data URLs, got a remote URL");if(o.mediaType.startsWith("image/"))i.push(o.base64);else if(T.isTextMediaType(o.mediaType))a.push(T.decodeBase64Text(o.base64));else throw new Error(`[vue-llm] Ollama does not support ${o.mediaType} attachments`)}return{role:n.role,content:a.join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("./sse-PZGBuYKy.cjs"),T=require("./file-DusIs8wR.cjs"),_=require("./errors-CVDNhYqZ.cjs");function b(o){return{id:"openai",supportsStreaming:!0,validateConfig(){if(!o.apiKey)throw new Error('[vue-llm] OpenAI API key is required. Pass it via createOpenAI({ apiKey: "..." })');if(!o.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=o.baseURL??"https://api.openai.com/v1/chat/completions",s={model:e.model,messages:k(e.messages),stream:!0,stream_options:{include_usage:!0}};e.providerOptions?.response_format&&(s.response_format=e.providerOptions.response_format),e.tools?.length&&(s.tools=e.tools.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})));const c=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${o.apiKey}`,"Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(s),signal:e.signal});if(!c.ok)throw await _.createAPIError("openai","OpenAI API",c);if(!c.body)throw new Error("[vue-llm] No response body from OpenAI");let r;const n=new Promise(m=>{r=m});return{stream:c.body.pipeThrough(new TextDecoderStream).pipeThrough(new v.SSEParserStream).pipeThrough(new TransformStream({transform(m,y){if(m.data==="[DONE]")return;let d;try{d=JSON.parse(m.data)}catch{return}const p=d.choices?.[0];if(!p){d.usage&&r({finishReason:"stop",usage:{promptTokens:d.usage.prompt_tokens,completionTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens}});return}const i=p.delta;if(i.content&&y.enqueue({type:"text-delta",text:i.content}),i.tool_calls)for(const l of i.tool_calls)l.id&&y.enqueue({type:"tool-call-start",toolCallId:l.id,toolName:l.function?.name??""}),l.function?.arguments&&y.enqueue({type:"tool-call-delta",toolCallId:l.id??"",args:l.function.arguments});if(p.finish_reason){const l=i.tool_calls?.filter(a=>a.id)??[];for(const a of l)a.id&&y.enqueue({type:"tool-call-end",toolCallId:a.id});const u=p.finish_reason==="tool_calls"?"tool-calls":p.finish_reason==="length"?"length":"stop";y.enqueue({type:"finish",finishReason:u,usage:void 0})}}})),response:n}}}}function k(o){return o.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(x)})}function x(o){if(o.type==="text")return{type:"text",text:o.text};const e=T.resolveFilePart(o);if(e.mediaType.startsWith("image/"))return{type:"image_url",image_url:{url:e.url}};if(!e.base64)throw new Error(`[vue-llm] OpenAI requires ${e.mediaType} attachments as data URLs, got a remote URL`);if(e.mediaType==="application/pdf")return{type:"file",file:{filename:e.filename??"document.pdf",file_data:e.url}};const t=C[e.mediaType];if(t)return{type:"input_audio",input_audio:{data:e.base64,format:t}};if(T.isTextMediaType(e.mediaType))return{type:"text",text:T.decodeBase64Text(e.base64)};throw new Error(`[vue-llm] OpenAI does not support ${e.mediaType} attachments`)}const C={"audio/wav":"wav","audio/x-wav":"wav","audio/mpeg":"mp3","audio/mp3":"mp3"};function O(o){return{id:"anthropic",supportsStreaming:!0,validateConfig(){if(!o.apiKey)throw new Error('[vue-llm] Anthropic API key is required. Pass it via createAnthropic({ apiKey: "..." })');if(!o.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=(o.baseURL??"https://api.anthropic.com")+"/v1/messages",s=e.messages.find(p=>p.role==="system"),c=e.messages.filter(p=>p.role!=="system"),r={model:e.model,messages:I(c),max_tokens:e.providerOptions?.maxTokens??4096,stream:!0};s&&(r.system=typeof s.content=="string"?s.content:s.content.map(p=>({type:"text",text:p.type==="text"?p.text:""}))),e.tools?.length&&(r.tools=e.tools.map(p=>({name:p.name,description:p.description,input_schema:p.parameters})));const n=await fetch(t,{method:"POST",headers:{"x-api-key":o.apiKey,"anthropic-version":"2023-06-01","Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(r),signal:e.signal});if(!n.ok)throw await _.createAPIError("anthropic","Anthropic API",n);if(!n.body)throw new Error("[vue-llm] No response body from Anthropic");let f;const m=new Promise(p=>{f=p});let y="";return{stream:n.body.pipeThrough(new TextDecoderStream).pipeThrough(new v.SSEParserStream).pipeThrough(new TransformStream({transform(p,i){let l;try{l=JSON.parse(p.data)}catch{return}switch(p.event??l.type){case"content_block_start":{const a=l.content_block;a?.type==="tool_use"&&(y=a.id,i.enqueue({type:"tool-call-start",toolCallId:y,toolName:a.name}));break}case"content_block_delta":{const a=l.delta;a?.type==="text_delta"&&a.text&&i.enqueue({type:"text-delta",text:a.text}),a?.type==="thinking_delta"&&a.text&&i.enqueue({type:"reasoning-delta",text:a.text}),a?.type==="input_json_delta"&&a.partial_json&&i.enqueue({type:"tool-call-delta",toolCallId:y,args:a.partial_json});break}case"content_block_stop":{y&&(i.enqueue({type:"tool-call-end",toolCallId:y}),y="");break}case"message_delta":{const a=l.delta,w=l.usage,g=a?.stop_reason==="tool_use"?"tool-calls":a?.stop_reason==="max_tokens"?"length":"stop";i.enqueue({type:"finish",finishReason:g,usage:w?{promptTokens:0,completionTokens:w.output_tokens??0,totalTokens:w.output_tokens??0}:void 0}),f({finishReason:g,usage:void 0});break}case"error":{const a=l.error;i.enqueue({type:"error",error:new Error(`[vue-llm] Anthropic stream error: ${a?.message??"unknown"}`)});break}}}})),response:m}}}}function I(o){return o.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 s of e.toolCalls)t.push({type:"tool_use",id:s.id,name:s.name,input:s.args});return{role:"assistant",content:t}}return{role:e.role,content:typeof e.content=="string"?e.content:e.content.map(A)}})}function A(o){if(o.type==="text")return{type:"text",text:o.text};const e=T.resolveFilePart(o),t=e.base64?{type:"base64",media_type:e.mediaType,data:e.base64}:{type:"url",url:e.url};if(e.mediaType.startsWith("image/"))return{type:"image",source:t};if(e.mediaType==="application/pdf")return{type:"document",source:t,...e.filename?{title:e.filename}:{}};if(T.isTextMediaType(e.mediaType)&&e.base64)return{type:"document",source:{type:"text",media_type:"text/plain",data:T.decodeBase64Text(e.base64)},...e.filename?{title:e.filename}:{}};throw new Error(`[vue-llm] Anthropic does not support ${e.mediaType} attachments`)}function S(o){return{id:"google",supportsStreaming:!0,validateConfig(){if(!o.apiKey)throw new Error('[vue-llm] Google AI API key is required. Pass it via createGoogle({ apiKey: "..." })');if(!o.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 s=`${o.baseURL??"https://generativelanguage.googleapis.com/v1beta"}/models/${e.model}:streamGenerateContent?alt=sse&key=${o.apiKey}`,c={contents:P(e.messages)},r=e.messages.find(i=>i.role==="system");r&&(c.systemInstruction={parts:[{text:typeof r.content=="string"?r.content:""}]}),e.tools?.length&&(c.tools=[{functionDeclarations:e.tools.map(i=>({name:i.name,description:i.description,parameters:i.parameters}))}]),c.generationConfig={...e.providerOptions?.response_format?.type==="json_object"?{responseMimeType:"application/json"}:{}};const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(c),signal:e.signal});if(!n.ok)throw await _.createAPIError("google","Google AI API",n);if(!n.body)throw new Error("[vue-llm] No response body from Google AI");let f;const m=new Promise(i=>{f=i});let y=0,d=!1;return{stream:n.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({buffer:"",transform(i,l){this.buffer+=i;const u=this.buffer.split(`
|
|
2
|
+
`);this.buffer=u.pop();for(const a of u)a.startsWith("data: ")&&l.enqueue(a.slice(6))},flush(i){const l=this.buffer.trim();l.startsWith("data: ")&&i.enqueue(l.slice(6))}})).pipeThrough(new TransformStream({transform(i,l){let u;try{u=JSON.parse(i)}catch{return}const a=u.candidates?.[0];if(!a)return;const w=a.content?.parts;if(w){for(const g of w)if(g.text!==void 0&&l.enqueue({type:"text-delta",text:g.text}),g.functionCall){const h=`tc_gemini_${++y}`;d=!0,l.enqueue({type:"tool-call-start",toolCallId:h,toolName:g.functionCall.name}),l.enqueue({type:"tool-call-delta",toolCallId:h,args:JSON.stringify(g.functionCall.args??{})}),l.enqueue({type:"tool-call-end",toolCallId:h})}}if(a.finishReason){const g=d?"tool-calls":a.finishReason==="MAX_TOKENS"?"length":"stop",h=u.usageMetadata;l.enqueue({type:"finish",finishReason:g,usage:h?{promptTokens:h.promptTokenCount??0,completionTokens:h.candidatesTokenCount??0,totalTokens:h.totalTokenCount??0}:void 0}),f({finishReason:g,usage:h?{promptTokens:h.promptTokenCount??0,completionTokens:h.candidatesTokenCount??0,totalTokens:h.totalTokenCount??0}:void 0})}}})),response:m}}}}function P(o){const e=[],t=new Map;for(const s of o){if(s.role==="system")continue;if(s.role==="tool"){const n={functionResponse:{name:t.get(s.toolCallId??"")??s.toolCallId??"",response:{result:N(s.content)}}},f=e.at(-1);f?.role==="user"&&f.parts.every(m=>m.functionResponse)?f.parts.push(n):e.push({role:"user",parts:[n]});continue}for(const n of s.toolCalls??[])t.set(n.id,n.name);const c=s.role==="assistant"?"model":"user",r=[];if(typeof s.content=="string")s.content&&r.push({text:s.content});else if(Array.isArray(s.content)){for(const n of s.content)if(n.type==="text"&&r.push({text:n.text}),n.type==="image"||n.type==="file"){const f=T.resolveFilePart(n);r.push(f.base64?{inlineData:{mimeType:f.mediaType,data:f.base64}}:{fileData:{mimeType:f.mediaType,fileUri:f.url}})}}if(s.toolCalls?.length)for(const n of s.toolCalls)r.push({functionCall:{name:n.name,args:typeof n.args=="string"?JSON.parse(n.args):n.args}});r.length>0&&e.push({role:c,parts:r})}return e}function N(o){if(typeof o!="string")return o;try{return JSON.parse(o)}catch{return o}}function E(o){return{id:"ollama",supportsStreaming:!0,validateConfig(){},async chat(e){const t=(o?.baseURL??"http://localhost:11434")+"/api/chat",s={model:e.model,messages:R(e.messages),stream:!0};e.tools?.length&&(s.tools=e.tools.map(d=>({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})));const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...e.providerOptions?.headers},body:JSON.stringify(s),signal:e.signal});if(!c.ok)throw await _.createAPIError("ollama","Ollama API",c);if(!c.body)throw new Error("[vue-llm] No response body from Ollama");let r;const n=new Promise(d=>{r=d});let f="",m=!1;return{stream:c.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(d,p){f+=d;const i=f.split(`
|
|
3
|
+
`);f=i.pop()??"";for(const l of i){if(!l.trim())continue;let u;try{u=JSON.parse(l)}catch{continue}if(u.message?.content&&p.enqueue({type:"text-delta",text:u.message.content}),u.message?.tool_calls)for(const a of u.message.tool_calls){m=!0;const w=`ollama-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;p.enqueue({type:"tool-call-start",toolCallId:w,toolName:a.function.name}),p.enqueue({type:"tool-call-delta",toolCallId:w,args:JSON.stringify(a.function.arguments)}),p.enqueue({type:"tool-call-end",toolCallId:w})}if(u.done){const a=m?"tool-calls":"stop";p.enqueue({type:"finish",finishReason:a}),r({finishReason:a,usage:u.eval_count?{promptTokens:u.prompt_eval_count??0,completionTokens:u.eval_count,totalTokens:(u.prompt_eval_count??0)+u.eval_count}:void 0})}}}})),response:n}}}}function R(o){const e=new Map;return o.map(t=>{if(t.role==="tool")return{role:"tool",content:typeof t.content=="string"?t.content:JSON.stringify(t.content),tool_name:e.get(t.toolCallId??"")};if(t.role==="assistant"&&t.toolCalls?.length){for(const r of t.toolCalls)e.set(r.id,r.name);return{role:"assistant",content:typeof t.content=="string"?t.content:"",tool_calls:t.toolCalls.map(r=>({function:{name:r.name,arguments:typeof r.args=="string"?JSON.parse(r.args):r.args}}))}}if(typeof t.content=="string")return{role:t.role,content:t.content};const s=[],c=[];for(const r of t.content){if(r.type==="text"){s.push(r.text);continue}const n=T.resolveFilePart(r);if(!n.base64)throw new Error("[vue-llm] Ollama requires attachments as data URLs, got a remote URL");if(n.mediaType.startsWith("image/"))c.push(n.base64);else if(T.isTextMediaType(n.mediaType))s.push(T.decodeBase64Text(n.base64));else throw new Error(`[vue-llm] Ollama does not support ${n.mediaType} attachments`)}return{role:t.role,content:s.join(`
|
|
8
4
|
|
|
9
|
-
`),...
|
|
5
|
+
`),...c.length>0?{images:c}:{}}})}exports.createSSEProvider=v.createSSEProvider;exports.createAnthropic=O;exports.createGoogle=S;exports.createOllama=E;exports.createOpenAI=b;
|
package/dist/providers.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export { createGoogle } from './providers/google';
|
|
|
6
6
|
export type { GoogleConfig } from './providers/google';
|
|
7
7
|
export { createOllama } from './providers/ollama';
|
|
8
8
|
export type { OllamaConfig } from './providers/ollama';
|
|
9
|
+
export { createSSEProvider } from './providers/sse';
|
|
10
|
+
export type { SSEProviderConfig, SSEProviderEvent } from './providers/sse';
|