@opentiny/tiny-robot-kit 0.4.0 → 0.4.1-alpha.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.
package/dist/core.d.ts ADDED
@@ -0,0 +1,281 @@
1
+ import { ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletion, ChatCompletionChunk, ChatCompletionTool } from 'openai/resources/index';
2
+ import { M as MaybePromise } from './types-CePh-Jcx.js';
3
+ import { Ref, ComputedRef } from 'vue';
4
+
5
+ type DeepReadonly<T> = T extends (...args: any[]) => any ? T : T extends Array<infer U> ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
6
+ readonly [K in keyof T]: DeepReadonly<T[K]>;
7
+ } : T;
8
+ type RequestState = 'idle' | 'processing' | 'completed' | 'aborted' | 'error';
9
+ type RequestProcessingState = 'requesting' | 'completing' | string;
10
+ type ChatMessage<Metadata extends object = Record<string, unknown>, State extends object = Record<string, unknown>> = ChatCompletionMessageParam & {
11
+ tool_calls?: Array<ChatCompletionMessageToolCall>;
12
+ loading?: boolean;
13
+ metadata?: Metadata;
14
+ state?: State;
15
+ [key: string]: any;
16
+ };
17
+ interface MessageRequestBody {
18
+ messages: Array<ChatMessage>;
19
+ [key: string]: any;
20
+ }
21
+ type ResponseProvider<T extends ChatCompletion | ChatCompletionChunk = ChatCompletion | ChatCompletionChunk> = (requestBody: MessageRequestBody, abortSignal: AbortSignal) => Promise<T> | AsyncGenerator<T> | Promise<AsyncGenerator<T>>;
22
+ interface PublicMessageState {
23
+ requestState: RequestState;
24
+ processingState?: RequestProcessingState;
25
+ messages: ChatMessage[];
26
+ isProcessing: boolean;
27
+ }
28
+ interface InternalMessageState {
29
+ requestState: RequestState;
30
+ processingState?: RequestProcessingState;
31
+ messages: ChatMessage[];
32
+ }
33
+ interface MessageRuntime {
34
+ currentTurn: ChatMessage[];
35
+ customContext: Record<string, unknown>;
36
+ abortController: AbortController | null;
37
+ responseProvider: ResponseProvider;
38
+ }
39
+ interface MessageEngine {
40
+ getState(): PublicMessageState;
41
+ subscribe(listener: (state: PublicMessageState) => void): () => void;
42
+ subscribe(kinds: MessageUpdateKinds, listener: (state: PublicMessageState) => void): () => void;
43
+ sendMessage(content: string): Promise<void>;
44
+ send(...msgs: ChatMessage[]): Promise<void>;
45
+ abort(): Promise<void>;
46
+ setResponseProvider(provider: ResponseProvider): void;
47
+ }
48
+ type MessageUpdateKind = 'messages' | 'requestState';
49
+ type MessageUpdateKinds = MessageUpdateKind | MessageUpdateKind[];
50
+ type MessageMutationRecipe = (draft: InternalMessageState, skipNotify: () => void) => void;
51
+ interface MutateMessageStateFn {
52
+ /**
53
+ * 在受控上下文中修改消息状态,并按声明的更新类型分发状态变更通知。
54
+ *
55
+ * 这里的“通知”语义对应 `subscribe` 订阅链路,用于驱动依赖 engine 状态快照的观察者;
56
+ * 它并不等同于具体框架的响应式更新机制。对于 Vue 等运行时,界面更新可能同时依赖
57
+ * 框架自身的响应式追踪与 `subscribe` 侧的状态通知,两者职责不同,不应混用。
58
+ */
59
+ (kinds: MessageUpdateKinds, recipe: MessageMutationRecipe): void;
60
+ }
61
+ interface MessageStateAdapter {
62
+ initialize(initialState: InternalMessageState): void;
63
+ getState(): PublicMessageState;
64
+ /**
65
+ * 创建一条适配当前运行时的消息对象。
66
+ *
67
+ * engine 和 core 插件里凡是“新建消息”的入口,都应统一走这个方法,
68
+ * 以便不同平台注入各自的运行时能力。
69
+ *
70
+ * 例如:
71
+ * - native/纯 TS 场景:直接返回原对象即可
72
+ * `createMessage(message) { return message }`
73
+ * - Vue 场景:返回 reactive proxy,使后续对 message.content / message.state 的原地修改能够被追踪
74
+ * `createMessage(message) { return reactive(message) }`
75
+ */
76
+ createMessage<T extends ChatMessage>(message: T): T;
77
+ mutate: MutateMessageStateFn;
78
+ subscribe(listener: (state: PublicMessageState) => void): () => void;
79
+ subscribe(kinds: MessageUpdateKinds, listener: (state: PublicMessageState) => void): () => void;
80
+ }
81
+ interface BasePluginContext {
82
+ getState(): PublicMessageState;
83
+ /**
84
+ * 创建一条适配当前运行时的消息对象。
85
+ *
86
+ * 插件在运行过程中如果需要主动创建并追加消息,应统一通过此接口构造消息实例,
87
+ * 而不是直接持有普通对象字面量。这样可以确保消息对象具备当前平台所要求的运行时能力。
88
+ *
89
+ * 对于采用响应式机制的平台(例如 Vue),该接口通常会返回带有响应式包装的消息实例。
90
+ * 如果插件绕过此接口直接创建普通对象,再参与后续的状态更新或原地字段修改,
91
+ * 可能导致消息内容、状态字段等变更无法被正确追踪。
92
+ */
93
+ createMessage<T extends ChatMessage>(message: T): T;
94
+ /**
95
+ * 在受控上下文中修改状态,并触发与 `subscribe` 对应的状态更新通知。
96
+ *
97
+ * 该通知机制面向 engine 的订阅接口,而不是具体框架的响应式系统本身。
98
+ * 因此,在需要让 `subscribe` 观察者感知到变更时,应通过此接口完成状态写入。
99
+ */
100
+ mutate: MutateMessageStateFn;
101
+ abortSignal: AbortSignal;
102
+ currentTurn: ChatMessage[];
103
+ customContext: Record<string, unknown>;
104
+ setRequestState: (state: RequestState, processingState?: RequestProcessingState) => void;
105
+ setCustomContext: (data: Record<string, unknown>) => void;
106
+ }
107
+ interface BeforeRequestContext extends BasePluginContext {
108
+ requestBody: MessageRequestBody;
109
+ }
110
+ interface AfterRequestContext extends BasePluginContext {
111
+ currentMessage: DeepReadonly<ChatMessage>;
112
+ lastChoice?: ChatCompletion.Choice | ChatCompletionChunk.Choice;
113
+ /**
114
+ * 使用 appendMessage 函数追加消息,可触发消息更新通知。
115
+ */
116
+ appendMessage: (message: ChatMessage | ChatMessage[]) => void;
117
+ requestNext: () => void;
118
+ }
119
+ interface CompletionChunkContext extends BasePluginContext {
120
+ /**
121
+ * 当前消息,只读。需要使用 updateCurrentMessage 函数修改当前消息,才能正常触发消息更新通知。
122
+ */
123
+ currentMessage: DeepReadonly<ChatMessage>;
124
+ /**
125
+ * 使用 updateCurrentMessage 函数修改当前消息,才能正常触发消息更新通知。
126
+ */
127
+ updateCurrentMessage: (recipe: (message: ChatMessage) => void) => void;
128
+ choice: ChatCompletion.Choice | ChatCompletionChunk.Choice;
129
+ chunk: ChatCompletion | ChatCompletionChunk;
130
+ }
131
+ interface MessageEnginePlugin {
132
+ /**
133
+ * 插件名称。
134
+ */
135
+ name?: string;
136
+ /**
137
+ * 是否禁用插件。
138
+ */
139
+ disabled?: boolean | ((context: BasePluginContext) => boolean);
140
+ /**
141
+ * 一次对话回合(turn)开始钩子:用户消息入队后、正式发起请求之前触发。
142
+ * 按插件注册顺序串行执行,便于做有序初始化/校验;出错则中断流程。
143
+ */
144
+ onTurnStart?: (context: BasePluginContext) => MaybePromise<void>;
145
+ /**
146
+ * 一次对话回合(turn)结束的生命周期钩子。
147
+ * 触发时机:本轮对话完成(成功、被中止)后。
148
+ * 执行策略:按插件注册顺序串行执行,有错误则中断流程。
149
+ */
150
+ onTurnEnd?: (context: BasePluginContext) => MaybePromise<void>;
151
+ /**
152
+ * 请求开始前的生命周期钩子。
153
+ * 触发时机:已组装 requestBody,正式发起请求之前。
154
+ * 执行策略:按插件注册顺序串行执行,避免并发修改 requestBody 产生冲突。
155
+ */
156
+ onBeforeRequest?: (context: BeforeRequestContext) => MaybePromise<void>;
157
+ /**
158
+ * 请求完成后的生命周期钩子。
159
+ * 触发时机:本次请求(含流式)结束后。
160
+ * 执行策略:并行执行(Promise.all)。
161
+ */
162
+ onAfterRequest?: (context: AfterRequestContext) => MaybePromise<void>;
163
+ /**
164
+ * 数据块处理钩子,在接收到每个响应数据块时触发。
165
+ * 无论是流式响应(多个增量数据块)还是非流式响应(单个完整数据块),都会触发此钩子。
166
+ */
167
+ onCompletionChunk?: (context: CompletionChunkContext) => void;
168
+ onError?: (context: BasePluginContext & {
169
+ error: unknown;
170
+ }) => void;
171
+ onFinally?: (context: BasePluginContext) => void;
172
+ }
173
+ interface CreateMessageEngineOptions {
174
+ initialMessages?: ChatMessage[];
175
+ /**
176
+ * 请求消息时,要包含的字段(白名单)。默认包含所有字段。
177
+ * 如果 `requestMessageFieldsExclude` 存在,会先取 `requestMessageFields` 中的字段,再排除 `requestMessageFieldsExclude` 中的字段
178
+ */
179
+ requestMessageFields?: string[];
180
+ /**
181
+ * 请求消息时,要排除的字段(黑名单)。默认会排除 `state`、`metadata`、`loading` 字段(这几个字段是给UI展示用的)。
182
+ * 如果 `requestMessageFields` 存在,会先取 `requestMessageFields` 中的字段,再排除 `requestMessageFieldsExclude` 中的字段
183
+ */
184
+ requestMessageFieldsExclude?: string[];
185
+ responseProvider?: ResponseProvider;
186
+ /**
187
+ * 全局的数据块处理钩子,在接收到每个响应数据块时触发。
188
+ * 注意:此钩子与插件中的 onCompletionChunk 有区别。
189
+ * 如果传入了此参数,默认的 chunk 处理逻辑不会自动执行,需要手动调用 runDefault 来执行默认处理逻辑。
190
+ */
191
+ onCompletionChunk?: (context: CompletionChunkContext, runDefault: () => void) => void;
192
+ plugins?: MessageEnginePlugin[];
193
+ }
194
+
195
+ declare const createNativeMessageAdapter: () => MessageStateAdapter;
196
+
197
+ interface VueMessageStateAdapter extends MessageStateAdapter {
198
+ requestState: Ref<RequestState>;
199
+ processingState: Ref<RequestProcessingState | undefined>;
200
+ messages: Ref<ChatMessage[]>;
201
+ isProcessing: ComputedRef<boolean>;
202
+ }
203
+ declare const createVueMessageAdapter: () => VueMessageStateAdapter;
204
+
205
+ declare const createMessageEngine: (adapter: MessageStateAdapter, options?: CreateMessageEngineOptions) => MessageEngine;
206
+
207
+ declare const lengthPlugin: (options?: MessageEnginePlugin & {
208
+ continueContent?: string;
209
+ }) => MessageEnginePlugin;
210
+
211
+ declare const thinkingPlugin: (options?: MessageEnginePlugin) => MessageEnginePlugin;
212
+
213
+ type AssistantMessageWithState = ChatMessage<Record<string, unknown>, {
214
+ toolCall?: Record<string, Record<string, unknown>>;
215
+ }>;
216
+ type ToolCallContext = BasePluginContext & {
217
+ assistantMessage: AssistantMessageWithState;
218
+ toolMessage: ChatMessage;
219
+ };
220
+ declare const toolPlugin: (options: MessageEnginePlugin & {
221
+ /**
222
+ * 获取工具列表的函数。会在请求大模型前调用。
223
+ */
224
+ getTools: () => Promise<ChatCompletionTool[]>;
225
+ /**
226
+ * 在处理包含 tool_calls 的响应前调用。
227
+ */
228
+ beforeCallTools?: (toolCalls: ChatCompletionMessageToolCall[], context: BasePluginContext & {
229
+ assistantMessage: AssistantMessageWithState;
230
+ }) => Promise<void>;
231
+ /**
232
+ * 执行单个工具调用并返回其文本结果的函数。
233
+ */
234
+ callTool: (toolCall: ChatCompletionMessageToolCall, context: ToolCallContext) => Promise<string | Record<string, any>> | AsyncGenerator<string | Record<string, any>>;
235
+ /**
236
+ * 工具调用开始时的回调函数。
237
+ * 触发时机:工具消息已创建并追加后,调用 callTool 之前触发。
238
+ * @param toolCall - 工具调用对象
239
+ * @param context - 插件上下文,包含当前工具消息
240
+ */
241
+ onToolCallStart?: (toolCall: ChatCompletionMessageToolCall, context: ToolCallContext) => void;
242
+ /**
243
+ * 工具调用结束时的回调函数。
244
+ * 触发时机:工具调用完成(成功、失败或取消)时触发。
245
+ * @param toolCall - 工具调用对象
246
+ * @param context - 插件上下文,包含当前工具消息、状态和错误信息
247
+ * @param context.status - 工具调用状态:'success' | 'failed' | 'cancelled'
248
+ * @param context.error - 当状态为 'failed' 或 'cancelled' 时,可能包含错误信息
249
+ */
250
+ onToolCallEnd?: (toolCall: ChatCompletionMessageToolCall, context: ToolCallContext & {
251
+ status: "success" | "failed" | "cancelled";
252
+ error?: Error;
253
+ }) => void;
254
+ /**
255
+ * 当请求被中止时用于工具调用取消的消息内容。
256
+ */
257
+ toolCallCancelledContent?: string;
258
+ /**
259
+ * 当工具调用执行失败(抛错或拒绝)时使用的消息内容。
260
+ */
261
+ toolCallFailedContent?: string;
262
+ /**
263
+ * 是否在请求前自动补充缺失的 tool 消息。
264
+ * 当 assistant 响应了 tool_calls 但未追加对应的 tool 消息时,
265
+ * 插件将自动补充"工具调用已取消"的 tool 消息。默认:false。
266
+ */
267
+ autoFillMissingToolMessages?: boolean;
268
+ }) => MessageEnginePlugin;
269
+
270
+ declare function normalizeToAsyncGenerator<T>(result: Promise<T> | AsyncGenerator<T> | Promise<AsyncGenerator<T>>): AsyncGenerator<T>;
271
+ /**
272
+ * Merge delta data from completion responses
273
+ * Handles string concatenation, object merging, and array merging by index
274
+ *
275
+ * @param target - Target object to merge into
276
+ * @param source - Source object to merge from
277
+ * @returns Merged target object
278
+ */
279
+ declare const combineDeltaData: (target: Record<string, any>, source: Record<string, any>) => Record<string, any>;
280
+
281
+ export { type AfterRequestContext, type BasePluginContext, type BeforeRequestContext, type ChatMessage, type CompletionChunkContext, type CreateMessageEngineOptions, type DeepReadonly, type InternalMessageState, type MessageEngine, type MessageEnginePlugin, type MessageMutationRecipe, type MessageRequestBody, type MessageRuntime, type MessageStateAdapter, type MessageUpdateKind, type MessageUpdateKinds, type MutateMessageStateFn, type PublicMessageState, type RequestProcessingState, type RequestState, type ResponseProvider, type VueMessageStateAdapter, combineDeltaData, createMessageEngine, createNativeMessageAdapter, createVueMessageAdapter, lengthPlugin, normalizeToAsyncGenerator, thinkingPlugin, toolPlugin };
package/dist/core.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var X=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var pe=(e,t)=>{for(var s in t)X(e,s,{get:t[s],enumerable:!0})},me=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fe(t))!de.call(e,o)&&o!==s&&X(e,o,{get:()=>t[o],enumerable:!(n=ge(t,o))||n.enumerable});return e};var Me=e=>me(X({},"__esModule",{value:!0}),e);var Te={};pe(Te,{combineDeltaData:()=>B,createMessageEngine:()=>ce,createNativeMessageAdapter:()=>he,createVueMessageAdapter:()=>ye,lengthPlugin:()=>H,normalizeToAsyncGenerator:()=>O,thinkingPlugin:()=>Q,toolPlugin:()=>le});module.exports=Me(Te);var Ce=e=>typeof e=="function"?null:Array.isArray(e)?e.length>0?new Set(e):null:new Set([e]),$=e=>{let t=new Set,s=(a,l)=>{try{a.listener(l)}catch(m){console.error("Error in message state subscriber:",m)}};return{notify:a=>{let l=new Set(Array.isArray(a)?a:[a]),m=e(),d=Array.from(t);for(let r of d){if(r.kinds){let u=!1;for(let y of r.kinds)if(l.has(y)){u=!0;break}if(!u)continue}s(r,m)}},subscribe:(a,l)=>{let m=typeof a=="function"?a:l;if(!m)throw new Error("subscribe listener is required");let d={kinds:Ce(a),listener:m};return t.add(d),s(d,e()),()=>{t.delete(d)}}}};var he=()=>{let e=!1,t,s=l=>{if(e)throw new Error("Message state adapter is already initialized");t={requestState:l.requestState,processingState:l.processingState,messages:[...l.messages]},e=!0},n=()=>{if(!e)throw new Error("Message state adapter is not initialized");return{requestState:t.requestState,processingState:t.processingState,messages:[...t.messages],isProcessing:t.requestState==="processing"}},o=$(n);return{initialize:s,getState:n,createMessage(l){return l},mutate:(l,m)=>{if(!e)throw new Error("Message state adapter is not initialized");let d=!1;m(t,()=>{d=!0}),d||o.notify(l)},subscribe:o.subscribe}};var w=require("vue");var se=e=>(0,w.reactive)(e),Y=e=>{let t=(0,w.isProxy)(e)?(0,w.toRaw)(e):e;if(Array.isArray(t))return t.map(s=>Y(s));if(t&&typeof t=="object"){let s={};for(let[n,o]of Object.entries(t))s[n]=Y(o);return s}return t},ye=()=>{let e=!1,t=(0,w.ref)("idle"),s=(0,w.ref)(void 0),n=(0,w.ref)([]),o=(0,w.computed)(()=>t.value==="processing"),a=u=>{if(e)throw new Error("Message state adapter is already initialized");t.value=u.requestState,s.value=u.processingState,n.value=u.messages.map(se),e=!0},l=u=>se(u),m=()=>{if(!e)throw new Error("Message state adapter is not initialized");return{requestState:t.value,processingState:s.value,messages:Y(n.value),isProcessing:o.value}},d=$(m);return{requestState:t,processingState:s,messages:n,isProcessing:o,initialize:a,getState:m,createMessage:l,mutate:(u,y)=>{if(!e)throw new Error("Message state adapter is not initialized");let T={get requestState(){return t.value},set requestState(S){t.value=S},get processingState(){return s.value},set processingState(S){s.value=S},get messages(){return n.value},set messages(S){n.value=S.map(l)}},p=!1;if(y(T,()=>{p=!0}),p)return;(Array.isArray(u)?u:[u]).includes("messages")&&(n.value=[...n.value]),d.notify(u)},subscribe:d.subscribe}};var H=(e={})=>{let{continueContent:t="Please continue with your previous answer.",...s}=e;return{name:"length",...s,onAfterRequest:async n=>{let{lastChoice:o,appendMessage:a,requestNext:l}=n;return o?.finish_reason==="length"&&(a({role:"user",content:t}),l()),s.onAfterRequest?.(n)}}};var Q=(e={})=>{let t=(s,n)=>!!s.thinking!==n||!!s.open!==n;return{name:"thinking",...e,onCompletionChunk(s){let{choice:n,currentMessage:o,updateCurrentMessage:a}=s,l=n,m=l?.message?.reasoning_content||l?.delta?.reasoning_content,d=typeof m=="string"&&m.trim()!=="";return d?o.state&&typeof o.state=="object"?t(o.state,d)&&a(r=>{r.state.thinking=!0,r.state.open=!0}):a(r=>{r.state={thinking:d,open:d}}):o.state&&typeof o.state=="object"&&"thinking"in o.state&&t(o.state,d)&&a(r=>{r.state.thinking=!1,r.state.open=!1}),e.onCompletionChunk?.(s)},onTurnEnd(s){let{currentTurn:n,mutate:o}=s,a=n.at(-1);return a?.state&&typeof a.state=="object"&&"thinking"in a.state&&t(a.state,!1)&&o("messages",()=>{a.state.thinking=!1,a.state.open=!1}),e.onTurnEnd?.(s)}}};var N=class extends Error{constructor(t){super(t),this.name="AbortError"}};function Se(e){if(e.aborted)return{promise:Promise.reject(new N(String(e.reason??"Aborted"))),cleanup:()=>{}};let t=null;return{promise:new Promise((o,a)=>{t=()=>{a(new N(String(e.reason??"Aborted")))},e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t&&(e.removeEventListener("abort",t),t=null)}}}function ae(e,t){let{promise:s,cleanup:n}=Se(t);return Promise.race([e,s]).finally(n)}function re(e,t){let s={};for(let n in e)t.includes(n)&&(s[n]=e[n]);return s}function ie(e,t){let s={};for(let n in e)t.includes(n)||(s[n]=e[n]);return s}async function*O(e){if(ne(e)){yield*e;return}let t=await e;if(ne(t)){yield*t;return}yield t}function ne(e){return e&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function"}var Z=e=>typeof e=="object"&&e!==null,oe=e=>Z(e)&&typeof e.index=="number",B=(e,t)=>{for(let[s,n]of Object.entries(t)){let o=e[s];if(o)if(typeof o=="string"&&typeof n=="string")s==="type"&&o||(e[s]=o+n);else if(Array.isArray(o)&&Array.isArray(n))if(o.every(a=>oe(a))&&n.every(a=>oe(a))){let a=new Map(o.map(r=>[r.index,r])),l=new Map(n.map(r=>[r.index,r]));for(let[r,u]of l)if(a.has(r)){let y=a.get(r);a.set(r,B(y,u))}else a.set(r,u);let m=Math.max(...Array.from(a.keys()),-1)+1,d=m>o.length?Array.from({length:m}):o;for(let[r,u]of a)d[r]=u;e[s]=d}else e[s]=[...o,...n];else Z(o)&&Z(n)&&(e[s]=B(o,n));else e[s]=n}return e};function be({messages:e,cancelledContent:t,createMessage:s,mutate:n}){let o=[];for(let a=0;a<e.length;a++){let l=e[a];if(l.role==="assistant"&&l.tool_calls&&l.tool_calls.length>0){let m=new Set(l.tool_calls.map(u=>u.id)),d=new Set;for(let u=a+1;u<e.length;u++){let y=e[u];y.role==="tool"&&y.tool_call_id&&m.has(y.tool_call_id)&&d.add(y.tool_call_id)}let r=l.tool_calls.map(u=>u.id).filter(u=>!d.has(u));r.length>0&&o.push({insertAfterIndex:a,missingToolCallIds:r})}}o.length!==0&&n("messages",a=>{for(let l=o.length-1;l>=0;l--){let{insertAfterIndex:m,missingToolCallIds:d}=o[l],r=d.map(u=>s({role:"tool",tool_call_id:u,content:t}));a.messages.splice(m+1,0,...r)}})}var le=e=>{let{getTools:t,beforeCallTools:s,callTool:n,onToolCallStart:o,onToolCallEnd:a,toolCallCancelledContent:l="Tool call cancelled.",toolCallFailedContent:m="Tool call failed.",autoFillMissingToolMessages:d=!1,...r}=e,u=(p,M)=>{var C,S;return p.state??(p.state={}),(C=p.state).toolCall??(C.toolCall={}),(S=p.state.toolCall)[M]??(S[M]={}),p},y=(...p)=>{let[M,{assistantMessage:C,mutate:S}]=p;S("messages",()=>{let R=u(C,M.id);R.state.toolCall[M.id].status="running"}),o?.(...p)},T=(...p)=>{let[M,{status:C,assistantMessage:S,mutate:R}]=p;R("messages",()=>{let W=u(S,M.id);W.state.toolCall[M.id].status=C}),a?.(...p)};return{name:"tool",...r,onTurnStart:p=>{let{getState:M,createMessage:C,mutate:S}=p,R=M().messages;return d&&be({messages:R,cancelledContent:l,createMessage:C,mutate:S}),r.onTurnStart?.(p)},onBeforeRequest:async p=>{let{requestBody:M}=p,C=await t();return C&&C.length>0&&(M.tools=C),r.onBeforeRequest?.(p)},onAfterRequest:async p=>{let{currentMessage:M,lastChoice:C,appendMessage:S,abortSignal:R,setRequestState:W,requestNext:v,mutate:F,createMessage:E}=p;if(C?.finish_reason!=="tool_calls"||!M.tool_calls?.length)return;W("processing","calling-tools"),await s?.(M.tool_calls,{...p,assistantMessage:M});let U=M.tool_calls.map(async j=>{let G=Math.floor(Date.now()/1e3),J=!1,x=E({role:"tool",tool_call_id:j.id,content:"",metadata:{createdAt:G,updatedAt:G}});S(x);let K={...p,assistantMessage:M,toolMessage:x};y(j,K);try{let i=n(j,K),c=O(i);for await(let f of c)F("messages",()=>{if((typeof f=="string"&&f.length>0||f&&typeof f=="object"&&Object.keys(f).length>0)&&(J=!0),typeof f=="string")x.content+=f;else{let h={};try{let b=Array.isArray(x.content)?x.content.map(g=>g.text).join(""):x.content;h=JSON.parse(b||"{}")}catch(b){console.warn(b)}x.content=JSON.stringify(B(h,f))}x.metadata.updatedAt=Math.floor(Date.now()/1e3)});T(j,{...K,status:"success"})}catch(i){let c=i instanceof Error?i:new Error(String(i));if(R.aborted){T(j,{...K,status:"cancelled",error:c});return}console.error(i),J||F("messages",()=>{x.content=m,x.metadata.updatedAt=Math.floor(Date.now()/1e3)}),T(j,{...K,status:"failed",error:c})}});return await Promise.all(U),R.aborted||v(),r.onAfterRequest?.(p)}}};var Pe=async()=>{throw new Error("Response provider is not set")},Ae=e=>{let t=[];for(let s of e){if(s.name){let n=t.findIndex(o=>o.name===s.name);n!==-1&&t.splice(n,1)}t.push(s)}return t},z=(e,t)=>typeof e.disabled=="function"?e.disabled(t):!!e.disabled,ce=(e,t={})=>{let{initialMessages:s=[],requestMessageFields:n=[],requestMessageFieldsExclude:o=["state","metadata","loading"],responseProvider:a=Pe,onCompletionChunk:l,plugins:m=[]}=t,d={requestState:"idle",processingState:void 0,messages:[...s]};e.initialize(d);let r={currentTurn:[],customContext:{},abortController:null,responseProvider:a},u=[Q(),H()],y=Ae(u.concat(m)),T=()=>e.getState(),p=i=>e.createMessage(i),M=e.subscribe,C=e.mutate,S=i=>!i||Object.keys(i).length===0?!1:Object.values(i).some(c=>!!c),R=i=>{let c=i;return n.length&&(c=c.map(f=>re(f,n))),o.length&&(c=c.map(f=>ie(f,o))),c},W=i=>{Object.assign(r.customContext,i)},v=(i,c)=>{C("requestState",(f,h)=>{if(f.requestState===i&&f.processingState===c){h();return}f.requestState=i,f.processingState=i==="processing"?c??"requesting":void 0})},F=(...i)=>{let c=i.map(f=>p(f));return C("messages",f=>{f.messages.push(...c)}),r.currentTurn.push(...c),c},E=i=>({getState:T,createMessage:p,mutate:C,abortSignal:i,currentTurn:r.currentTurn,customContext:r.customContext,setRequestState:v,setCustomContext:W});async function U(i,c,f={}){v("processing","requesting");let h={messages:T().messages},b=E(c);for(let _ of y.filter(A=>!z(A,b)))await _.onBeforeRequest?.({...b,requestBody:h});h.messages=R(h.messages);let g={role:"assistant",content:"",loading:!0};[g]=F(g),f.setAssistantMessage?.(g);let P=i(h,c),k=O(P),I;for await(let _ of k){v("processing","completing"),C("messages",(q,V)=>{g.loading?g.loading=void 0:V()});let A=(_.choices||[]).find(q=>q.index===0)??_.choices?.[0];if(!A)continue;I=A;let D=()=>{C("messages",()=>{g.metadata||(g.metadata={});let{created:q,...V}=_;g.metadata.createdAt=q,g.metadata.updatedAt=Math.floor(Date.now()/1e3),Object.assign(g.metadata,V);let L="delta"in A&&S(A.delta)&&A.delta||"message"in A&&S(A.message)&&A.message||null;if(L?.role&&(g.role=L.role),L){let{role:xe,...ue}=L;B(g,ue)}})},ee=q=>{C("messages",()=>{q(g)})};if(l){let q=E(c);l({...q,chunk:_,choice:A,currentMessage:g,updateCurrentMessage:ee},D)}else D();let te=E(c);for(let q of y.filter(V=>!z(V,te)))q.onCompletionChunk?.({...te,abortSignal:c,chunk:_,choice:A,currentMessage:g,updateCurrentMessage:ee})}await j(g,i,c,I,f)}async function j(i,c,f,h,b){let g=!1,P=E(f),k=y.filter(I=>!z(I,P)).map(I=>{if(!I.onAfterRequest)return null;let _=D=>{F(...Array.isArray(D)?D:[D])},A=()=>{g=!0};return I.onAfterRequest({...P,currentMessage:i,lastChoice:h,appendMessage:_,requestNext:A})}).filter(I=>I!==null);await ae(Promise.all(k),f),g&&await U(c,f,b)}async function G(){let i=new AbortController;r.abortController=i,r.customContext={};let c=null,f=h=>{c=h};try{v("processing","requesting");let h=E(i.signal);for(let P of y.filter(k=>!z(k,h)))await P.onTurnStart?.(h);let b=r.responseProvider;try{await U(b,i.signal,{setAssistantMessage:f}),v("completed")}catch(P){if(i.signal.aborted||P instanceof N||P instanceof Error&&P.name==="AbortError")v("aborted");else throw P}let g=E(i.signal);for(let P of y.filter(k=>!z(k,g)))await P.onTurnEnd?.(g)}catch(h){v("error");let b=!1,g=E(i.signal);for(let P of y.filter(k=>!z(k,g)))P.onError&&(b=!0,P.onError({...g,error:h}));if(!b)throw h}finally{let h=E(i.signal);for(let b of y.filter(g=>!z(g,h)))try{b.onFinally?.(h)}catch(g){console.error(`Error in onFinally hook for plugin [${b.name||"Anonymous"}]:`,g)}r.abortController=null,r.currentTurn=[],C("messages",(b,g)=>{c?.loading?c.loading=void 0:g()})}}async function J(i){if(!i||!i.trim()){console.warn("Cannot send empty message");return}if(T().requestState==="processing"){console.warn("Cannot send message while processing is in progress");return}let c=Math.floor(Date.now()/1e3);F({role:"user",content:i.trim(),metadata:{createdAt:c,updatedAt:c}}),await G()}async function x(...i){if(T().requestState==="processing"){console.warn("Cannot send message while processing is in progress");return}F(...i),await G()}async function K(){r.abortController?.abort(),T().isProcessing&&await new Promise(i=>{let c=()=>{};c=M("requestState",f=>{f.isProcessing||(c(),i())})})}return{getState:T,subscribe:M,sendMessage:J,send:x,abort:K,setResponseProvider(i){r.responseProvider=i}}};0&&(module.exports={combineDeltaData,createMessageEngine,createNativeMessageAdapter,createVueMessageAdapter,lengthPlugin,normalizeToAsyncGenerator,thinkingPlugin,toolPlugin});
package/dist/core.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as o,b as f,c as l,d as m,e as p,f as c,g as M,h as d}from"./chunk-EES4JUCD.mjs";var w=()=>{let s=!1,t,n=e=>{if(s)throw new Error("Message state adapter is already initialized");t={requestState:e.requestState,processingState:e.processingState,messages:[...e.messages]},s=!0},a=()=>{if(!s)throw new Error("Message state adapter is not initialized");return{requestState:t.requestState,processingState:t.processingState,messages:[...t.messages],isProcessing:t.requestState==="processing"}},r=o(a);return{initialize:n,getState:a,createMessage(e){return e},mutate:(e,g)=>{if(!s)throw new Error("Message state adapter is not initialized");let i=!1;g(t,()=>{i=!0}),i||r.notify(e)},subscribe:r.subscribe}};export{c as combineDeltaData,d as createMessageEngine,w as createNativeMessageAdapter,f as createVueMessageAdapter,l as lengthPlugin,p as normalizeToAsyncGenerator,m as thinkingPlugin,M as toolPlugin};
package/dist/index.d.mts CHANGED
@@ -1,216 +1,7 @@
1
+ import { a as AIModelConfig, c as ChatCompletionRequest, d as ChatCompletionResponse, o as StreamHandler, B as BaseModelProvider, l as ChatMessage, M as MaybePromise, T as ToolCall } from './types-CePh-Jcx.mjs';
2
+ export { A as AIAdapterError, b as AIProvider, C as ChatCompletionOptions, e as ChatCompletionResponseChoice, f as ChatCompletionResponseMessage, g as ChatCompletionResponseUsage, h as ChatCompletionStreamResponse, i as ChatCompletionStreamResponseChoice, j as ChatCompletionStreamResponseDelta, k as ChatHistory, E as ErrorType, m as MessageMetadata, n as MessageRole, S as StreamEventType } from './types-CePh-Jcx.mjs';
1
3
  import { Ref, ComputedRef } from 'vue';
2
4
 
3
- /**
4
- * 模型Provider基类
5
- */
6
- declare abstract class BaseModelProvider {
7
- protected config: AIModelConfig;
8
- /**
9
- * @param config AI模型配置
10
- */
11
- constructor(config: AIModelConfig);
12
- /**
13
- * 发送聊天请求并获取响应
14
- * @param request 聊天请求参数
15
- * @returns 聊天响应
16
- */
17
- abstract chat(request: ChatCompletionRequest): Promise<ChatCompletionResponse>;
18
- /**
19
- * 发送流式聊天请求并通过处理器处理响应
20
- * @param request 聊天请求参数
21
- * @param handler 流式响应处理器
22
- */
23
- abstract chatStream(request: ChatCompletionRequest, handler: StreamHandler): Promise<void>;
24
- /**
25
- * 更新配置
26
- * @param config 新的AI模型配置
27
- */
28
- updateConfig(config: AIModelConfig): void;
29
- /**
30
- * 获取当前配置
31
- * @returns AI模型配置
32
- */
33
- getConfig(): AIModelConfig;
34
- /**
35
- * 验证请求参数
36
- * @param request 聊天请求参数
37
- */
38
- protected validateRequest(request: ChatCompletionRequest): void;
39
- }
40
-
41
- type MaybePromise<T> = T | Promise<T>;
42
- /**
43
- * 消息角色类型
44
- */
45
- type MessageRole = 'system' | 'user' | 'assistant';
46
- interface ToolCall {
47
- index: number;
48
- id: string;
49
- type: 'function';
50
- function: {
51
- name: string;
52
- arguments: string;
53
- result?: string;
54
- };
55
- }
56
- interface MessageMetadata {
57
- createdAt?: number;
58
- updatedAt?: number;
59
- id?: string;
60
- model?: string;
61
- [key: string]: any;
62
- }
63
- /**
64
- * 聊天消息接口
65
- */
66
- interface ChatMessage {
67
- role: string;
68
- content: string;
69
- reasoning_content?: string;
70
- metadata?: MessageMetadata;
71
- tool_calls?: ToolCall[];
72
- tool_call_id?: string;
73
- [key: string]: any;
74
- [key: symbol]: any;
75
- }
76
- /**
77
- * 聊天历史记录
78
- */
79
- type ChatHistory = ChatMessage[];
80
- /**
81
- * 聊天完成请求选项
82
- */
83
- interface ChatCompletionOptions {
84
- model?: string;
85
- temperature?: number;
86
- top_p?: number;
87
- n?: number;
88
- stream?: boolean;
89
- max_tokens?: number;
90
- signal?: AbortSignal;
91
- }
92
- /**
93
- * 聊天完成请求参数
94
- */
95
- interface ChatCompletionRequest {
96
- messages: ChatMessage[];
97
- options?: ChatCompletionOptions;
98
- }
99
- /**
100
- * 聊天完成响应消息
101
- */
102
- interface ChatCompletionResponseMessage {
103
- role: MessageRole;
104
- content: string;
105
- [x: string]: unknown;
106
- }
107
- /**
108
- * 聊天完成响应选择
109
- */
110
- interface ChatCompletionResponseChoice {
111
- index: number;
112
- message: ChatCompletionResponseMessage;
113
- finish_reason: string;
114
- }
115
- /**
116
- * 聊天完成响应使用情况
117
- */
118
- interface ChatCompletionResponseUsage {
119
- prompt_tokens: number;
120
- completion_tokens: number;
121
- total_tokens: number;
122
- }
123
- /**
124
- * 聊天完成响应
125
- */
126
- interface ChatCompletionResponse {
127
- id: string;
128
- object: string;
129
- created: number;
130
- model: string;
131
- choices: ChatCompletionResponseChoice[];
132
- usage: ChatCompletionResponseUsage;
133
- }
134
- /**
135
- * 流式聊天完成响应增量
136
- */
137
- interface ChatCompletionStreamResponseDelta {
138
- content?: string;
139
- role?: MessageRole;
140
- [x: string]: unknown;
141
- }
142
- /**
143
- * 流式聊天完成响应选择
144
- */
145
- interface ChatCompletionStreamResponseChoice {
146
- index: number;
147
- delta: ChatCompletionStreamResponseDelta;
148
- finish_reason: string | null;
149
- }
150
- /**
151
- * 流式聊天完成响应
152
- */
153
- interface ChatCompletionStreamResponse {
154
- id: string;
155
- object: string;
156
- created: number;
157
- model: string;
158
- choices: ChatCompletionStreamResponseChoice[];
159
- }
160
- /**
161
- * AI模型提供商类型
162
- */
163
- type AIProvider = 'openai' | 'deepseek' | 'custom';
164
- /**
165
- * AI模型配置接口
166
- */
167
- interface AIModelConfig {
168
- provider: AIProvider;
169
- providerImplementation?: BaseModelProvider;
170
- apiKey?: string;
171
- apiUrl?: string;
172
- apiVersion?: string;
173
- defaultModel?: string;
174
- defaultOptions?: ChatCompletionOptions;
175
- }
176
- /**
177
- * 错误类型
178
- */
179
- declare enum ErrorType {
180
- NETWORK_ERROR = "network_error",
181
- AUTHENTICATION_ERROR = "authentication_error",
182
- RATE_LIMIT_ERROR = "rate_limit_error",
183
- SERVER_ERROR = "server_error",
184
- MODEL_ERROR = "model_error",
185
- TIMEOUT_ERROR = "timeout_error",
186
- UNKNOWN_ERROR = "unknown_error"
187
- }
188
- /**
189
- * AI适配器错误
190
- */
191
- interface AIAdapterError {
192
- type: ErrorType;
193
- message: string;
194
- statusCode?: number;
195
- originalError?: object;
196
- }
197
- /**
198
- * 流式响应事件类型
199
- */
200
- declare enum StreamEventType {
201
- DATA = "data",
202
- ERROR = "error",
203
- DONE = "done"
204
- }
205
- /**
206
- * 流式响应处理器
207
- */
208
- interface StreamHandler {
209
- onData: (data: ChatCompletionStreamResponse) => void;
210
- onError: (error: AIAdapterError) => void;
211
- onDone: (finishReason?: string) => void;
212
- }
213
-
214
5
  /**
215
6
  * AI客户端类
216
7
  * 负责根据配置选择合适的提供商并处理请求
@@ -294,11 +85,12 @@ interface Tool {
294
85
  type: 'function';
295
86
  function: {
296
87
  name: string;
297
- description: string;
88
+ description?: string;
298
89
  /**
299
90
  * function 的输入参数,以 JSON Schema 对象描述
300
91
  */
301
- parameters: any;
92
+ parameters?: any;
93
+ inputSchema?: any;
302
94
  };
303
95
  [key: string]: any;
304
96
  }
@@ -352,6 +144,7 @@ interface ChatCompletion {
352
144
  choices: CompletionChoice[];
353
145
  usage?: Usage;
354
146
  }
147
+ type ResponseProvider<T = ChatCompletion> = (requestBody: MessageRequestBody, abortSignal: AbortSignal) => Promise<T> | AsyncGenerator<T> | Promise<AsyncGenerator<T>>;
355
148
  interface UseMessageOptions {
356
149
  initialMessages?: ChatMessage[];
357
150
  /**
@@ -365,7 +158,7 @@ interface UseMessageOptions {
365
158
  */
366
159
  requestMessageFieldsExclude?: string[];
367
160
  plugins?: UseMessagePlugin[];
368
- responseProvider: <T = ChatCompletion>(requestBody: MessageRequestBody, abortSignal: AbortSignal) => Promise<T> | AsyncGenerator<T> | Promise<AsyncGenerator<T>>;
161
+ responseProvider: ResponseProvider;
369
162
  /**
370
163
  * 全局的数据块处理钩子,在接收到每个响应数据块时触发。
371
164
  * 注意:此钩子与插件中的 onCompletionChunk 有区别。
@@ -663,21 +456,30 @@ declare function sseStreamToGenerator<T = any>(response: Response, options?: {
663
456
 
664
457
  declare const useConversation: (options: UseConversationOptions) => UseConversationReturn;
665
458
 
666
- declare const fallbackRolePlugin: (options?: UseMessagePlugin & {
667
- fallbackRole?: string;
668
- }) => UseMessagePlugin;
669
-
670
459
  declare const lengthPlugin: (options?: UseMessagePlugin & {
671
460
  continueContent?: string;
672
461
  }) => UseMessagePlugin;
673
462
 
674
463
  declare const thinkingPlugin: (options?: UseMessagePlugin) => UseMessagePlugin;
675
464
 
676
- /**
677
- * 消息排除模式:从 messages 数组中直接移除消息。
678
- * 使用此模式时,消息会被完全从数组中移除,不会保留在 messages 中。
679
- */
680
- declare const EXCLUDE_MODE_REMOVE: "remove";
465
+ interface UseMessageToolActionContext extends BasePluginContext {
466
+ assistantMessage: ChatMessage;
467
+ /**
468
+ * @deprecated use `assistantMessage` instead
469
+ */
470
+ currentMessage: ChatMessage;
471
+ }
472
+ interface UseMessageCallToolContext extends UseMessageToolActionContext {
473
+ toolMessage: ChatMessage;
474
+ }
475
+ interface UseMessageToolCallContext extends BasePluginContext {
476
+ assistantMessage: ChatMessage;
477
+ /**
478
+ * @deprecated use `assistantMessage` instead
479
+ */
480
+ primaryMessage: ChatMessage;
481
+ toolMessage: ChatMessage;
482
+ }
681
483
  declare const toolPlugin: (options: UseMessagePlugin & {
682
484
  /**
683
485
  * 获取工具列表的函数。
@@ -686,25 +488,18 @@ declare const toolPlugin: (options: UseMessagePlugin & {
686
488
  /**
687
489
  * 在处理包含 tool_calls 的响应前调用。
688
490
  */
689
- beforeCallTools?: (toolCalls: ToolCall[], context: BasePluginContext & {
690
- currentMessage: ChatMessage;
691
- }) => Promise<void>;
491
+ beforeCallTools?: (toolCalls: ToolCall[], context: UseMessageToolActionContext) => Promise<void>;
692
492
  /**
693
493
  * 执行单个工具调用并返回其文本结果的函数。
694
494
  */
695
- callTool: (toolCall: ToolCall, context: BasePluginContext & {
696
- currentMessage: ChatMessage;
697
- }) => Promise<string | Record<string, any>> | AsyncGenerator<string | Record<string, any>>;
495
+ callTool: (toolCall: ToolCall, context: UseMessageCallToolContext) => Promise<string | Record<string, any>> | AsyncGenerator<string | Record<string, any>>;
698
496
  /**
699
497
  * 工具调用开始时的回调函数。
700
498
  * 触发时机:工具消息已创建并追加后,调用 callTool 之前触发。
701
499
  * @param toolCall - 工具调用对象
702
500
  * @param context - 插件上下文,包含当前工具消息
703
501
  */
704
- onToolCallStart?: (toolCall: ToolCall, context: BasePluginContext & {
705
- primaryMessage: ChatMessage;
706
- toolMessage: ChatMessage;
707
- }) => void;
502
+ onToolCallStart?: (toolCall: ToolCall, context: UseMessageToolCallContext) => void;
708
503
  /**
709
504
  * 工具调用结束时的回调函数。
710
505
  * 触发时机:工具调用完成(成功、失败或取消)时触发。
@@ -713,9 +508,7 @@ declare const toolPlugin: (options: UseMessagePlugin & {
713
508
  * @param context.status - 工具调用状态:'success' | 'failed' | 'cancelled'
714
509
  * @param context.error - 当状态为 'failed' 或 'cancelled' 时,可能包含错误信息
715
510
  */
716
- onToolCallEnd?: (toolCall: ToolCall, context: BasePluginContext & {
717
- primaryMessage: ChatMessage;
718
- toolMessage: ChatMessage;
511
+ onToolCallEnd?: (toolCall: ToolCall, context: UseMessageToolCallContext & {
719
512
  status: "success" | "failed" | "cancelled";
720
513
  error?: Error;
721
514
  }) => void;
@@ -728,20 +521,13 @@ declare const toolPlugin: (options: UseMessagePlugin & {
728
521
  */
729
522
  toolCallFailedContent?: string;
730
523
  /**
731
- * 是否在请求被中止时自动补充缺失的 tool 消息。
524
+ * 是否在请求前自动补充缺失的 tool 消息。
732
525
  * 当 assistant 响应了 tool_calls 但未追加对应的 tool 消息时,
733
526
  * 插件将自动补充"工具调用已取消"的 tool 消息。默认:false。
734
527
  */
735
528
  autoFillMissingToolMessages?: boolean;
736
- /**
737
- * 是否在下一轮对话中,排除包含 tool_calls 的 assistant 消息和对应的 tool 消息,只保留结果。
738
- * - 当为 `true` 时,这些消息会被标记为不发送,不会包含在下一次请求的 messages 中。
739
- * - 当为 `'remove'` 时,这些消息会直接从 messages 数组中移除。
740
- * 默认:false。
741
- */
742
- excludeToolMessagesNextTurn?: boolean | typeof EXCLUDE_MODE_REMOVE;
743
529
  }) => UseMessagePlugin;
744
530
 
745
531
  declare const useMessage: (options: UseMessageOptions) => UseMessageReturn;
746
532
 
747
- export { type AIAdapterError, AIClient, type AIModelConfig, type AIProvider, BaseModelProvider, type BasePluginContext, type ChatCompletion, type ChatCompletionOptions, type ChatCompletionRequest, type ChatCompletionResponse, type ChatCompletionResponseChoice, type ChatCompletionResponseMessage, type ChatCompletionResponseUsage, type ChatCompletionStreamResponse, type ChatCompletionStreamResponseChoice, type ChatCompletionStreamResponseDelta, type ChatHistory, type ChatMessage, type Choice, type CompletionChoice, type Conversation, type ConversationInfo, type ConversationStorageStrategy, type DeltaChoice, EXCLUDE_MODE_REMOVE, ErrorType, type IndexedDBConfig, IndexedDBStrategy, type LocalStorageConfig, LocalStorageStrategy, type MaybePromise, type MessageMetadata, type MessageRequestBody, type MessageRole, OpenAIProvider, type RequestProcessingState, type RequestState, StreamEventType, type StreamHandler, type Tool, type ToolCall, type Usage, type UseConversationOptions, type UseConversationReturn, type UseMessageOptions, type UseMessagePlugin, type UseMessageReturn, extractTextFromResponse, fallbackRolePlugin, formatMessages, handleSSEStream, indexedDBStorageStrategyFactory, lengthPlugin, localStorageStrategyFactory, sseStreamToGenerator, thinkingPlugin, toolPlugin, useConversation, useMessage };
533
+ export { AIClient, AIModelConfig, BaseModelProvider, type BasePluginContext, type ChatCompletion, ChatCompletionRequest, ChatCompletionResponse, ChatMessage, type Choice, type CompletionChoice, type Conversation, type ConversationInfo, type ConversationStorageStrategy, type DeltaChoice, type IndexedDBConfig, IndexedDBStrategy, type LocalStorageConfig, LocalStorageStrategy, MaybePromise, type MessageRequestBody, OpenAIProvider, type RequestProcessingState, type RequestState, type ResponseProvider, StreamHandler, type Tool, ToolCall, type Usage, type UseConversationOptions, type UseConversationReturn, type UseMessageCallToolContext, type UseMessageOptions, type UseMessagePlugin, type UseMessageReturn, type UseMessageToolActionContext, type UseMessageToolCallContext, extractTextFromResponse, formatMessages, handleSSEStream, indexedDBStorageStrategyFactory, lengthPlugin, localStorageStrategyFactory, sseStreamToGenerator, thinkingPlugin, toolPlugin, useConversation, useMessage };