@opentiny/tiny-robot-kit 0.2.0-alpha.1 → 0.2.0-alpha.3
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/index.js +2 -761
- package/dist/index.mjs +2 -722
- package/package.json +7 -3
- package/src/client.ts +0 -101
- package/src/error.ts +0 -100
- package/src/index.ts +0 -10
- package/src/providers/base.ts +0 -62
- package/src/providers/openai.ts +0 -139
- package/src/types.ts +0 -163
- package/src/utils.ts +0 -125
- package/src/vue/conversation/useConversation.ts +0 -365
- package/src/vue/index.ts +0 -2
- package/src/vue/message/useMessage.ts +0 -227
- package/tsconfig.json +0 -21
package/dist/index.js
CHANGED
|
@@ -1,762 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
1
|
+
"use strict";var b=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var $=(s,e)=>{for(var t in e)b(s,t,{get:e[t],enumerable:!0})},L=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let d of B(e))!j.call(s,d)&&d!==t&&b(s,d,{get:()=>e[d],enumerable:!(a=H(e,d))||a.enumerable});return s};var F=s=>L(b({},"__esModule",{value:!0}),s);var z={};$(z,{AIClient:()=>y,BaseModelProvider:()=>S,ErrorType:()=>P,FinalStatus:()=>G,GeneratingStatus:()=>q,LocalStorageStrategy:()=>A,OpenAIProvider:()=>R,STATUS:()=>K,StreamEventType:()=>U,extractTextFromResponse:()=>k,formatMessages:()=>_,useConversation:()=>J,useMessage:()=>O});module.exports=F(z);var S=class{constructor(e){this.config=e}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}validateRequest(e){if(!e.messages||!Array.isArray(e.messages)||e.messages.length===0)throw new Error("\u8BF7\u6C42\u5FC5\u987B\u5305\u542B\u81F3\u5C11\u4E00\u6761\u6D88\u606F");for(let t of e.messages)if(!t.role||!t.content)throw new Error("\u6BCF\u6761\u6D88\u606F\u5FC5\u987B\u5305\u542B\u89D2\u8272\u548C\u5185\u5BB9")}};var P=(p=>(p.NETWORK_ERROR="network_error",p.AUTHENTICATION_ERROR="authentication_error",p.RATE_LIMIT_ERROR="rate_limit_error",p.SERVER_ERROR="server_error",p.MODEL_ERROR="model_error",p.TIMEOUT_ERROR="timeout_error",p.UNKNOWN_ERROR="unknown_error",p))(P||{}),U=(a=>(a.DATA="data",a.ERROR="error",a.DONE="done",a))(U||{});function v(s){return{type:s.type||"unknown_error",message:s.message||"\u672A\u77E5\u9519\u8BEF",statusCode:s.statusCode,originalError:s.originalError}}function x(s){if(!s.response)return v({type:"network_error",message:"\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u8FDE\u63A5",originalError:s});if(s.response){let{status:e,data:t}=s.response;return e===401||e===403?v({type:"authentication_error",message:"\u8EAB\u4EFD\u9A8C\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684API\u5BC6\u94A5",statusCode:e,originalError:s}):e===429?v({type:"rate_limit_error",message:"\u8D85\u51FAAPI\u8C03\u7528\u9650\u5236\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",statusCode:e,originalError:s}):e>=500?v({type:"server_error",message:"\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",statusCode:e,originalError:s}):v({type:"unknown_error",message:t?.error?.message||`\u8BF7\u6C42\u5931\u8D25\uFF0C\u72B6\u6001\u7801: ${e}`,statusCode:e,originalError:s})}return s.code==="ECONNABORTED"?v({type:"timeout_error",message:"\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",originalError:s}):v({type:"unknown_error",message:s.message||"\u53D1\u751F\u672A\u77E5\u9519\u8BEF",originalError:s})}async function D(s,e,t){let a=s.body?.getReader();if(!a)throw new Error("Response body is null");let d=new TextDecoder,i="";t&&t.addEventListener("abort",()=>{a.cancel().catch(o=>console.error("Error cancelling reader:",o))},{once:!0});try{for(;;){if(t?.aborted){await a.cancel();break}let{done:o,value:p}=await a.read();if(o)break;let u=d.decode(p,{stream:!0});i+=u;let c=i.split(`
|
|
19
2
|
|
|
20
|
-
|
|
21
|
-
var index_exports = {};
|
|
22
|
-
__export(index_exports, {
|
|
23
|
-
AIClient: () => AIClient,
|
|
24
|
-
BaseModelProvider: () => BaseModelProvider,
|
|
25
|
-
ErrorType: () => ErrorType,
|
|
26
|
-
FinalStatus: () => FinalStatus,
|
|
27
|
-
GeneratingStatus: () => GeneratingStatus,
|
|
28
|
-
LocalStorageStrategy: () => LocalStorageStrategy,
|
|
29
|
-
OpenAIProvider: () => OpenAIProvider,
|
|
30
|
-
STATUS: () => STATUS,
|
|
31
|
-
StreamEventType: () => StreamEventType,
|
|
32
|
-
extractTextFromResponse: () => extractTextFromResponse,
|
|
33
|
-
formatMessages: () => formatMessages,
|
|
34
|
-
useConversation: () => useConversation,
|
|
35
|
-
useMessage: () => useMessage
|
|
36
|
-
});
|
|
37
|
-
module.exports = __toCommonJS(index_exports);
|
|
38
|
-
|
|
39
|
-
// src/providers/base.ts
|
|
40
|
-
var BaseModelProvider = class {
|
|
41
|
-
/**
|
|
42
|
-
* @param config AI模型配置
|
|
43
|
-
*/
|
|
44
|
-
constructor(config) {
|
|
45
|
-
this.config = config;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* 更新配置
|
|
49
|
-
* @param config 新的AI模型配置
|
|
50
|
-
*/
|
|
51
|
-
updateConfig(config) {
|
|
52
|
-
this.config = { ...this.config, ...config };
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* 获取当前配置
|
|
56
|
-
* @returns AI模型配置
|
|
57
|
-
*/
|
|
58
|
-
getConfig() {
|
|
59
|
-
return { ...this.config };
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* 验证请求参数
|
|
63
|
-
* @param request 聊天请求参数
|
|
64
|
-
*/
|
|
65
|
-
validateRequest(request) {
|
|
66
|
-
if (!request.messages || !Array.isArray(request.messages) || request.messages.length === 0) {
|
|
67
|
-
throw new Error("\u8BF7\u6C42\u5FC5\u987B\u5305\u542B\u81F3\u5C11\u4E00\u6761\u6D88\u606F");
|
|
68
|
-
}
|
|
69
|
-
for (const message of request.messages) {
|
|
70
|
-
if (!message.role || !message.content) {
|
|
71
|
-
throw new Error("\u6BCF\u6761\u6D88\u606F\u5FC5\u987B\u5305\u542B\u89D2\u8272\u548C\u5185\u5BB9");
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
// src/types.ts
|
|
78
|
-
var ErrorType = /* @__PURE__ */ ((ErrorType2) => {
|
|
79
|
-
ErrorType2["NETWORK_ERROR"] = "network_error";
|
|
80
|
-
ErrorType2["AUTHENTICATION_ERROR"] = "authentication_error";
|
|
81
|
-
ErrorType2["RATE_LIMIT_ERROR"] = "rate_limit_error";
|
|
82
|
-
ErrorType2["SERVER_ERROR"] = "server_error";
|
|
83
|
-
ErrorType2["MODEL_ERROR"] = "model_error";
|
|
84
|
-
ErrorType2["TIMEOUT_ERROR"] = "timeout_error";
|
|
85
|
-
ErrorType2["UNKNOWN_ERROR"] = "unknown_error";
|
|
86
|
-
return ErrorType2;
|
|
87
|
-
})(ErrorType || {});
|
|
88
|
-
var StreamEventType = /* @__PURE__ */ ((StreamEventType2) => {
|
|
89
|
-
StreamEventType2["DATA"] = "data";
|
|
90
|
-
StreamEventType2["ERROR"] = "error";
|
|
91
|
-
StreamEventType2["DONE"] = "done";
|
|
92
|
-
return StreamEventType2;
|
|
93
|
-
})(StreamEventType || {});
|
|
94
|
-
|
|
95
|
-
// src/error.ts
|
|
96
|
-
function createError(error) {
|
|
97
|
-
return {
|
|
98
|
-
type: error.type || "unknown_error" /* UNKNOWN_ERROR */,
|
|
99
|
-
message: error.message || "\u672A\u77E5\u9519\u8BEF",
|
|
100
|
-
statusCode: error.statusCode,
|
|
101
|
-
originalError: error.originalError
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
function handleRequestError(error) {
|
|
105
|
-
if (!error.response) {
|
|
106
|
-
return createError({
|
|
107
|
-
type: "network_error" /* NETWORK_ERROR */,
|
|
108
|
-
message: "\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u8FDE\u63A5",
|
|
109
|
-
originalError: error
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
if (error.response) {
|
|
113
|
-
const { status, data } = error.response;
|
|
114
|
-
if (status === 401 || status === 403) {
|
|
115
|
-
return createError({
|
|
116
|
-
type: "authentication_error" /* AUTHENTICATION_ERROR */,
|
|
117
|
-
message: "\u8EAB\u4EFD\u9A8C\u8BC1\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684API\u5BC6\u94A5",
|
|
118
|
-
statusCode: status,
|
|
119
|
-
originalError: error
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
if (status === 429) {
|
|
123
|
-
return createError({
|
|
124
|
-
type: "rate_limit_error" /* RATE_LIMIT_ERROR */,
|
|
125
|
-
message: "\u8D85\u51FAAPI\u8C03\u7528\u9650\u5236\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",
|
|
126
|
-
statusCode: status,
|
|
127
|
-
originalError: error
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
if (status >= 500) {
|
|
131
|
-
return createError({
|
|
132
|
-
type: "server_error" /* SERVER_ERROR */,
|
|
133
|
-
message: "\u670D\u52A1\u5668\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",
|
|
134
|
-
statusCode: status,
|
|
135
|
-
originalError: error
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
return createError({
|
|
139
|
-
type: "unknown_error" /* UNKNOWN_ERROR */,
|
|
140
|
-
message: data?.error?.message || `\u8BF7\u6C42\u5931\u8D25\uFF0C\u72B6\u6001\u7801: ${status}`,
|
|
141
|
-
statusCode: status,
|
|
142
|
-
originalError: error
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
if (error.code === "ECONNABORTED") {
|
|
146
|
-
return createError({
|
|
147
|
-
type: "timeout_error" /* TIMEOUT_ERROR */,
|
|
148
|
-
message: "\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",
|
|
149
|
-
originalError: error
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
return createError({
|
|
153
|
-
type: "unknown_error" /* UNKNOWN_ERROR */,
|
|
154
|
-
message: error.message || "\u53D1\u751F\u672A\u77E5\u9519\u8BEF",
|
|
155
|
-
originalError: error
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// src/utils.ts
|
|
160
|
-
async function handleSSEStream(response, handler, signal) {
|
|
161
|
-
const reader = response.body?.getReader();
|
|
162
|
-
if (!reader) {
|
|
163
|
-
throw new Error("Response body is null");
|
|
164
|
-
}
|
|
165
|
-
const decoder = new TextDecoder();
|
|
166
|
-
let buffer = "";
|
|
167
|
-
if (signal) {
|
|
168
|
-
signal.addEventListener(
|
|
169
|
-
"abort",
|
|
170
|
-
() => {
|
|
171
|
-
reader.cancel().catch((err) => console.error("Error cancelling reader:", err));
|
|
172
|
-
},
|
|
173
|
-
{ once: true }
|
|
174
|
-
);
|
|
175
|
-
}
|
|
176
|
-
try {
|
|
177
|
-
while (true) {
|
|
178
|
-
if (signal?.aborted) {
|
|
179
|
-
await reader.cancel();
|
|
180
|
-
break;
|
|
181
|
-
}
|
|
182
|
-
const { done, value } = await reader.read();
|
|
183
|
-
if (done) break;
|
|
184
|
-
const chunk = decoder.decode(value, { stream: true });
|
|
185
|
-
buffer += chunk;
|
|
186
|
-
const lines = buffer.split("\n\n");
|
|
187
|
-
buffer = lines.pop() || "";
|
|
188
|
-
for (const line of lines) {
|
|
189
|
-
if (line.trim() === "") continue;
|
|
190
|
-
if (line.trim() === "data: [DONE]") {
|
|
191
|
-
handler.onDone();
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
try {
|
|
195
|
-
const dataMatch = line.match(/^data: (.+)$/m);
|
|
196
|
-
if (!dataMatch) continue;
|
|
197
|
-
const data = JSON.parse(dataMatch[1]);
|
|
198
|
-
handler.onData(data);
|
|
199
|
-
} catch (error) {
|
|
200
|
-
console.error("Error parsing SSE message:", error);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
if (buffer.trim() === "data: [DONE]" || signal?.aborted) {
|
|
205
|
-
handler.onDone();
|
|
206
|
-
}
|
|
207
|
-
} catch (error) {
|
|
208
|
-
if (signal?.aborted) return;
|
|
209
|
-
throw error;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
function formatMessages(messages) {
|
|
213
|
-
return messages.map((msg) => {
|
|
214
|
-
if (typeof msg === "object" && "role" in msg && "content" in msg) {
|
|
215
|
-
return {
|
|
216
|
-
role: msg.role,
|
|
217
|
-
content: String(msg.content),
|
|
218
|
-
...msg.name ? { name: msg.name } : {}
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
if (typeof msg === "string") {
|
|
222
|
-
return {
|
|
223
|
-
role: "user",
|
|
224
|
-
content: msg
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
return {
|
|
228
|
-
role: "user",
|
|
229
|
-
content: String(msg)
|
|
230
|
-
};
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
function extractTextFromResponse(response) {
|
|
234
|
-
if (!response.choices || !response.choices.length) {
|
|
235
|
-
return "";
|
|
236
|
-
}
|
|
237
|
-
return response.choices[0].message?.content || "";
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// src/providers/openai.ts
|
|
241
|
-
var OpenAIProvider = class extends BaseModelProvider {
|
|
242
|
-
/**
|
|
243
|
-
* @param config AI模型配置
|
|
244
|
-
*/
|
|
245
|
-
constructor(config) {
|
|
246
|
-
super(config);
|
|
247
|
-
this.defaultModel = "gpt-3.5-turbo";
|
|
248
|
-
this.baseURL = config.apiUrl || "https://api.openai.com/v1";
|
|
249
|
-
this.apiKey = config.apiKey || "";
|
|
250
|
-
if (config.defaultModel) {
|
|
251
|
-
this.defaultModel = config.defaultModel;
|
|
252
|
-
}
|
|
253
|
-
if (!this.apiKey) {
|
|
254
|
-
console.warn("API key is not provided. Authentication will likely fail.");
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
/**
|
|
258
|
-
* 发送聊天请求并获取响应
|
|
259
|
-
* @param request 聊天请求参数
|
|
260
|
-
* @returns 聊天响应
|
|
261
|
-
*/
|
|
262
|
-
async chat(request) {
|
|
263
|
-
try {
|
|
264
|
-
this.validateRequest(request);
|
|
265
|
-
const requestData = {
|
|
266
|
-
model: request.options?.model || this.config.defaultModel || this.defaultModel,
|
|
267
|
-
messages: request.messages,
|
|
268
|
-
...request.options,
|
|
269
|
-
stream: false
|
|
270
|
-
};
|
|
271
|
-
const options = {
|
|
272
|
-
method: "POST",
|
|
273
|
-
headers: { "Content-Type": "application/json" },
|
|
274
|
-
body: JSON.stringify(requestData)
|
|
275
|
-
};
|
|
276
|
-
if (this.apiKey) {
|
|
277
|
-
Object.assign(options.headers, { Authorization: `Bearer ${this.apiKey}` });
|
|
278
|
-
}
|
|
279
|
-
const response = await fetch(`${this.baseURL}/chat/completions`, options);
|
|
280
|
-
if (!response.ok) {
|
|
281
|
-
const errorText = await response.text();
|
|
282
|
-
throw new Error(`HTTP error! status: ${response.status}, details: ${errorText}`);
|
|
283
|
-
}
|
|
284
|
-
return await response.json();
|
|
285
|
-
} catch (error) {
|
|
286
|
-
throw handleRequestError(error);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* 发送流式聊天请求并通过处理器处理响应
|
|
291
|
-
* @param request 聊天请求参数
|
|
292
|
-
* @param handler 流式响应处理器
|
|
293
|
-
*/
|
|
294
|
-
async chatStream(request, handler) {
|
|
295
|
-
const { signal, ...options } = request.options || {};
|
|
296
|
-
try {
|
|
297
|
-
this.validateRequest(request);
|
|
298
|
-
const requestData = {
|
|
299
|
-
model: request.options?.model || this.config.defaultModel || this.defaultModel,
|
|
300
|
-
messages: request.messages,
|
|
301
|
-
...options,
|
|
302
|
-
stream: true
|
|
303
|
-
};
|
|
304
|
-
const requestOptions = {
|
|
305
|
-
method: "POST",
|
|
306
|
-
headers: {
|
|
307
|
-
"Content-Type": "application/json",
|
|
308
|
-
Authorization: `Bearer ${this.apiKey}`,
|
|
309
|
-
Accept: "text/event-stream"
|
|
310
|
-
},
|
|
311
|
-
body: JSON.stringify(requestData),
|
|
312
|
-
signal
|
|
313
|
-
};
|
|
314
|
-
if (this.apiKey) {
|
|
315
|
-
Object.assign(requestOptions.headers, { Authorization: `Bearer ${this.apiKey}` });
|
|
316
|
-
}
|
|
317
|
-
const response = await fetch(`${this.baseURL}/chat/completions`, requestOptions);
|
|
318
|
-
if (!response.ok) {
|
|
319
|
-
const errorText = await response.text();
|
|
320
|
-
throw new Error(`HTTP error! status: ${response.status}, details: ${errorText}`);
|
|
321
|
-
}
|
|
322
|
-
await handleSSEStream(response, handler, signal);
|
|
323
|
-
} catch (error) {
|
|
324
|
-
if (signal?.aborted) return;
|
|
325
|
-
handler.onError(handleRequestError(error));
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
/**
|
|
329
|
-
* 更新配置
|
|
330
|
-
* @param config 新的AI模型配置
|
|
331
|
-
*/
|
|
332
|
-
updateConfig(config) {
|
|
333
|
-
super.updateConfig(config);
|
|
334
|
-
if (config.apiUrl) {
|
|
335
|
-
this.baseURL = config.apiUrl;
|
|
336
|
-
}
|
|
337
|
-
if (config.apiKey) {
|
|
338
|
-
this.apiKey = config.apiKey;
|
|
339
|
-
}
|
|
340
|
-
if (config.defaultModel) {
|
|
341
|
-
this.defaultModel = config.defaultModel;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
};
|
|
345
|
-
|
|
346
|
-
// src/client.ts
|
|
347
|
-
var AIClient = class {
|
|
348
|
-
/**
|
|
349
|
-
* 构造函数
|
|
350
|
-
* @param config AI模型配置
|
|
351
|
-
*/
|
|
352
|
-
constructor(config) {
|
|
353
|
-
this.config = config;
|
|
354
|
-
this.provider = this.createProvider(config);
|
|
355
|
-
}
|
|
356
|
-
/**
|
|
357
|
-
* 创建提供商实例
|
|
358
|
-
* @param config AI模型配置
|
|
359
|
-
* @returns 提供商实例
|
|
360
|
-
*/
|
|
361
|
-
createProvider(config) {
|
|
362
|
-
if (config.provider === "custom" && "providerImplementation" in config) {
|
|
363
|
-
return config.providerImplementation;
|
|
364
|
-
}
|
|
365
|
-
switch (config.provider) {
|
|
366
|
-
case "deepseek":
|
|
367
|
-
const defaultConfig = {
|
|
368
|
-
defaultModel: "deepseek-chat",
|
|
369
|
-
apiUrl: "https://api.deepseek.com/v1"
|
|
370
|
-
};
|
|
371
|
-
return new OpenAIProvider({ ...defaultConfig, ...config });
|
|
372
|
-
case "openai":
|
|
373
|
-
default:
|
|
374
|
-
return new OpenAIProvider(config);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
/**
|
|
378
|
-
* 发送聊天请求并获取响应
|
|
379
|
-
* @param request 聊天请求参数
|
|
380
|
-
* @returns 聊天响应
|
|
381
|
-
*/
|
|
382
|
-
async chat(request) {
|
|
383
|
-
return this.provider.chat(request);
|
|
384
|
-
}
|
|
385
|
-
/**
|
|
386
|
-
* 发送流式聊天请求并通过处理器处理响应
|
|
387
|
-
* @param request 聊天请求参数
|
|
388
|
-
* @param handler 流式响应处理器
|
|
389
|
-
*/
|
|
390
|
-
async chatStream(request, handler) {
|
|
391
|
-
const streamRequest = {
|
|
392
|
-
...request,
|
|
393
|
-
options: {
|
|
394
|
-
...request.options,
|
|
395
|
-
stream: true
|
|
396
|
-
}
|
|
397
|
-
};
|
|
398
|
-
return this.provider.chatStream(streamRequest, handler);
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* 获取当前配置
|
|
402
|
-
* @returns AI模型配置
|
|
403
|
-
*/
|
|
404
|
-
getConfig() {
|
|
405
|
-
return { ...this.config };
|
|
406
|
-
}
|
|
407
|
-
/**
|
|
408
|
-
* 更新配置
|
|
409
|
-
* @param config 新的AI模型配置
|
|
410
|
-
*/
|
|
411
|
-
updateConfig(config) {
|
|
412
|
-
this.config = { ...this.config, ...config };
|
|
413
|
-
if (config.provider && config.provider !== this.config.provider) {
|
|
414
|
-
this.provider = this.createProvider(this.config);
|
|
415
|
-
} else {
|
|
416
|
-
this.provider.updateConfig(this.config);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
};
|
|
420
|
-
|
|
421
|
-
// src/vue/message/useMessage.ts
|
|
422
|
-
var import_vue = require("vue");
|
|
423
|
-
var STATUS = /* @__PURE__ */ ((STATUS2) => {
|
|
424
|
-
STATUS2["INIT"] = "init";
|
|
425
|
-
STATUS2["PROCESSING"] = "processing";
|
|
426
|
-
STATUS2["STREAMING"] = "streaming";
|
|
427
|
-
STATUS2["FINISHED"] = "finished";
|
|
428
|
-
STATUS2["ABORTED"] = "aborted";
|
|
429
|
-
STATUS2["ERROR"] = "error";
|
|
430
|
-
return STATUS2;
|
|
431
|
-
})(STATUS || {});
|
|
432
|
-
var GeneratingStatus = ["processing" /* PROCESSING */, "streaming" /* STREAMING */];
|
|
433
|
-
var FinalStatus = ["finished" /* FINISHED */, "aborted" /* ABORTED */, "error" /* ERROR */];
|
|
434
|
-
function useMessage(options) {
|
|
435
|
-
const { client, useStreamByDefault = true, errorMessage = "\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5", initialMessages = [] } = options;
|
|
436
|
-
const messages = (0, import_vue.ref)([...initialMessages]);
|
|
437
|
-
const inputMessage = (0, import_vue.ref)("");
|
|
438
|
-
const useStream = (0, import_vue.ref)(useStreamByDefault);
|
|
439
|
-
let abortController = null;
|
|
440
|
-
const messageState = (0, import_vue.reactive)({
|
|
441
|
-
status: "init" /* INIT */,
|
|
442
|
-
errorMsg: null
|
|
443
|
-
});
|
|
444
|
-
const chat = async (abortController2) => {
|
|
445
|
-
const response = await client.chat({
|
|
446
|
-
messages: (0, import_vue.toRaw)(messages.value),
|
|
447
|
-
options: {
|
|
448
|
-
stream: false,
|
|
449
|
-
signal: abortController2.signal
|
|
450
|
-
}
|
|
451
|
-
});
|
|
452
|
-
const assistantMessage = {
|
|
453
|
-
role: "assistant",
|
|
454
|
-
content: response.choices[0].message.content
|
|
455
|
-
};
|
|
456
|
-
messages.value.push(assistantMessage);
|
|
457
|
-
};
|
|
458
|
-
const streamChat = async (abortController2) => {
|
|
459
|
-
await client.chatStream(
|
|
460
|
-
{
|
|
461
|
-
messages: (0, import_vue.toRaw)(messages.value),
|
|
462
|
-
options: {
|
|
463
|
-
stream: true,
|
|
464
|
-
signal: abortController2.signal
|
|
465
|
-
}
|
|
466
|
-
},
|
|
467
|
-
{
|
|
468
|
-
onData: (data) => {
|
|
469
|
-
messageState.status = "streaming" /* STREAMING */;
|
|
470
|
-
if (messages.value[messages.value.length - 1].role === "user") {
|
|
471
|
-
messages.value.push({ role: "assistant", content: "" });
|
|
472
|
-
}
|
|
473
|
-
const choice = data.choices?.[0];
|
|
474
|
-
if (choice && choice.delta.content) {
|
|
475
|
-
messages.value[messages.value.length - 1].content += choice.delta.content;
|
|
476
|
-
}
|
|
477
|
-
},
|
|
478
|
-
onError: (error) => {
|
|
479
|
-
messageState.status = "error" /* ERROR */;
|
|
480
|
-
messageState.errorMsg = errorMessage;
|
|
481
|
-
console.error("Stream request error:", error);
|
|
482
|
-
},
|
|
483
|
-
onDone: () => {
|
|
484
|
-
messageState.status = "finished" /* FINISHED */;
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
);
|
|
488
|
-
};
|
|
489
|
-
const chatRequest = async () => {
|
|
490
|
-
messageState.status = "processing" /* PROCESSING */;
|
|
491
|
-
messageState.errorMsg = null;
|
|
492
|
-
abortController = new AbortController();
|
|
493
|
-
try {
|
|
494
|
-
if (useStream.value) {
|
|
495
|
-
await streamChat(abortController);
|
|
496
|
-
} else {
|
|
497
|
-
await chat(abortController);
|
|
498
|
-
}
|
|
499
|
-
messageState.status = "finished" /* FINISHED */;
|
|
500
|
-
} catch (error) {
|
|
501
|
-
messageState.errorMsg = errorMessage;
|
|
502
|
-
messageState.status = "error" /* ERROR */;
|
|
503
|
-
console.error("Send message error:", error);
|
|
504
|
-
} finally {
|
|
505
|
-
abortController = null;
|
|
506
|
-
}
|
|
507
|
-
};
|
|
508
|
-
const sendMessage = async (content = inputMessage.value, clearInput = true) => {
|
|
509
|
-
if (!content?.trim() || GeneratingStatus.includes(messageState.status)) {
|
|
510
|
-
return;
|
|
511
|
-
}
|
|
512
|
-
const userMessage = {
|
|
513
|
-
role: "user",
|
|
514
|
-
content
|
|
515
|
-
};
|
|
516
|
-
messages.value.push(userMessage);
|
|
517
|
-
if (clearInput) {
|
|
518
|
-
inputMessage.value = "";
|
|
519
|
-
}
|
|
520
|
-
await chatRequest();
|
|
521
|
-
};
|
|
522
|
-
const abortRequest = () => {
|
|
523
|
-
if (abortController) {
|
|
524
|
-
abortController.abort();
|
|
525
|
-
abortController = null;
|
|
526
|
-
messageState.status = "aborted" /* ABORTED */;
|
|
527
|
-
}
|
|
528
|
-
};
|
|
529
|
-
const retryRequest = async (msgIndex) => {
|
|
530
|
-
if (msgIndex === 0 || !messages.value[msgIndex] || messages.value[msgIndex].role === "user") {
|
|
531
|
-
return;
|
|
532
|
-
}
|
|
533
|
-
messages.value.splice(msgIndex);
|
|
534
|
-
await chatRequest();
|
|
535
|
-
};
|
|
536
|
-
const clearMessages = () => {
|
|
537
|
-
messages.value = [];
|
|
538
|
-
messageState.errorMsg = null;
|
|
539
|
-
};
|
|
540
|
-
const addMessage = (message) => {
|
|
541
|
-
messages.value.push(message);
|
|
542
|
-
};
|
|
543
|
-
return {
|
|
544
|
-
messages,
|
|
545
|
-
messageState,
|
|
546
|
-
inputMessage,
|
|
547
|
-
useStream,
|
|
548
|
-
sendMessage,
|
|
549
|
-
clearMessages,
|
|
550
|
-
addMessage,
|
|
551
|
-
abortRequest,
|
|
552
|
-
retryRequest
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
// src/vue/conversation/useConversation.ts
|
|
557
|
-
var import_vue2 = require("vue");
|
|
558
|
-
var LocalStorageStrategy = class {
|
|
559
|
-
constructor(storageKey = "tiny-robot-ai-conversations") {
|
|
560
|
-
this.storageKey = storageKey;
|
|
561
|
-
}
|
|
562
|
-
saveConversations(conversations) {
|
|
563
|
-
try {
|
|
564
|
-
localStorage.setItem(this.storageKey, JSON.stringify(conversations));
|
|
565
|
-
} catch (error) {
|
|
566
|
-
console.error("\u4FDD\u5B58\u4F1A\u8BDD\u5931\u8D25:", error);
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
loadConversations() {
|
|
570
|
-
try {
|
|
571
|
-
const data = localStorage.getItem(this.storageKey);
|
|
572
|
-
return data ? JSON.parse(data) : [];
|
|
573
|
-
} catch (error) {
|
|
574
|
-
console.error("\u52A0\u8F7D\u4F1A\u8BDD\u5931\u8D25:", error);
|
|
575
|
-
return [];
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
};
|
|
579
|
-
function generateId() {
|
|
580
|
-
return Date.now().toString(36) + Math.random().toString(36).substring(2, 9);
|
|
581
|
-
}
|
|
582
|
-
function useConversation(options) {
|
|
583
|
-
const {
|
|
584
|
-
client,
|
|
585
|
-
storage = new LocalStorageStrategy(),
|
|
586
|
-
autoSave = true,
|
|
587
|
-
useStreamByDefault = true,
|
|
588
|
-
errorMessage = "\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"
|
|
589
|
-
} = options;
|
|
590
|
-
const state = (0, import_vue2.reactive)({
|
|
591
|
-
conversations: [],
|
|
592
|
-
currentId: null,
|
|
593
|
-
loading: false
|
|
594
|
-
});
|
|
595
|
-
const messageManager = useMessage({
|
|
596
|
-
client,
|
|
597
|
-
useStreamByDefault,
|
|
598
|
-
errorMessage,
|
|
599
|
-
initialMessages: []
|
|
600
|
-
});
|
|
601
|
-
(0, import_vue2.watch)(
|
|
602
|
-
() => messageManager.messages.value,
|
|
603
|
-
(messages) => {
|
|
604
|
-
if (state.currentId && messages.length > 0) {
|
|
605
|
-
const index = state.conversations.findIndex((row) => row.id === state.currentId);
|
|
606
|
-
if (index !== -1) {
|
|
607
|
-
state.conversations[index].messages = [...messages];
|
|
608
|
-
state.conversations[index].updatedAt = Date.now();
|
|
609
|
-
if (autoSave) {
|
|
610
|
-
saveConversations();
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
},
|
|
615
|
-
{ deep: true }
|
|
616
|
-
);
|
|
617
|
-
const createConversation = (title = "\u65B0\u4F1A\u8BDD", metadata = {}) => {
|
|
618
|
-
const id = generateId();
|
|
619
|
-
const newConversation = {
|
|
620
|
-
id,
|
|
621
|
-
title,
|
|
622
|
-
createdAt: Date.now(),
|
|
623
|
-
updatedAt: Date.now(),
|
|
624
|
-
messages: [],
|
|
625
|
-
metadata
|
|
626
|
-
};
|
|
627
|
-
state.conversations.unshift(newConversation);
|
|
628
|
-
switchConversation(id);
|
|
629
|
-
if (autoSave) {
|
|
630
|
-
saveConversations();
|
|
631
|
-
}
|
|
632
|
-
return id;
|
|
633
|
-
};
|
|
634
|
-
const switchConversation = (id) => {
|
|
635
|
-
const conversation = state.conversations.find((conv) => conv.id === id);
|
|
636
|
-
if (conversation) {
|
|
637
|
-
state.currentId = id;
|
|
638
|
-
messageManager.clearMessages();
|
|
639
|
-
if (conversation.messages.length > 0) {
|
|
640
|
-
conversation.messages.forEach((msg) => messageManager.addMessage(msg));
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
};
|
|
644
|
-
const deleteConversation = (id) => {
|
|
645
|
-
const index = state.conversations.findIndex((conv) => conv.id === id);
|
|
646
|
-
if (index !== -1) {
|
|
647
|
-
state.conversations.splice(index, 1);
|
|
648
|
-
if (state.currentId === id) {
|
|
649
|
-
if (state.conversations.length > 0) {
|
|
650
|
-
switchConversation(state.conversations[0].id);
|
|
651
|
-
} else {
|
|
652
|
-
state.currentId = null;
|
|
653
|
-
messageManager.clearMessages();
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
if (autoSave) {
|
|
657
|
-
saveConversations();
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
};
|
|
661
|
-
const updateTitle = (id, title) => {
|
|
662
|
-
const conversation = state.conversations.find((conv) => conv.id === id);
|
|
663
|
-
if (conversation) {
|
|
664
|
-
conversation.title = title;
|
|
665
|
-
conversation.updatedAt = Date.now();
|
|
666
|
-
if (autoSave) {
|
|
667
|
-
saveConversations();
|
|
668
|
-
}
|
|
669
|
-
}
|
|
670
|
-
};
|
|
671
|
-
const updateMetadata = (id, metadata) => {
|
|
672
|
-
const conversation = state.conversations.find((conv) => conv.id === id);
|
|
673
|
-
if (conversation) {
|
|
674
|
-
conversation.metadata = { ...conversation.metadata, ...metadata };
|
|
675
|
-
conversation.updatedAt = Date.now();
|
|
676
|
-
if (autoSave) {
|
|
677
|
-
saveConversations();
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
};
|
|
681
|
-
const saveConversations = async () => {
|
|
682
|
-
try {
|
|
683
|
-
await storage.saveConversations(state.conversations);
|
|
684
|
-
} catch (error) {
|
|
685
|
-
console.error("\u4FDD\u5B58\u4F1A\u8BDD\u5931\u8D25:", error);
|
|
686
|
-
}
|
|
687
|
-
};
|
|
688
|
-
const loadConversations = async () => {
|
|
689
|
-
state.loading = true;
|
|
690
|
-
try {
|
|
691
|
-
const conversations = await storage.loadConversations();
|
|
692
|
-
state.conversations = conversations;
|
|
693
|
-
if (conversations.length > 0 && !state.currentId) {
|
|
694
|
-
switchConversation(conversations[0].id);
|
|
695
|
-
}
|
|
696
|
-
} catch (error) {
|
|
697
|
-
console.error("\u52A0\u8F7D\u4F1A\u8BDD\u5931\u8D25:", error);
|
|
698
|
-
} finally {
|
|
699
|
-
state.loading = false;
|
|
700
|
-
}
|
|
701
|
-
};
|
|
702
|
-
const generateTitle = async (id) => {
|
|
703
|
-
const conversation = state.conversations.find((conv) => conv.id === id);
|
|
704
|
-
if (!conversation || conversation.messages.length < 2) {
|
|
705
|
-
return conversation?.title || "\u65B0\u4F1A\u8BDD";
|
|
706
|
-
}
|
|
707
|
-
try {
|
|
708
|
-
const prompt = {
|
|
709
|
-
role: "system",
|
|
710
|
-
content: "\u8BF7\u6839\u636E\u4EE5\u4E0B\u5BF9\u8BDD\u5185\u5BB9\uFF0C\u751F\u6210\u4E00\u4E2A\u7B80\u77ED\u7684\u6807\u9898\uFF08\u4E0D\u8D85\u8FC720\u4E2A\u5B57\u7B26\uFF09\u3002\u53EA\u9700\u8981\u8FD4\u56DE\u6807\u9898\u6587\u672C\uFF0C\u4E0D\u9700\u8981\u4EFB\u4F55\u89E3\u91CA\u6216\u989D\u5916\u5185\u5BB9\u3002"
|
|
711
|
-
};
|
|
712
|
-
const contextMessages = conversation.messages.slice(0, Math.min(4, conversation.messages.length));
|
|
713
|
-
const response = await client.chat({
|
|
714
|
-
messages: [prompt, ...contextMessages],
|
|
715
|
-
options: {
|
|
716
|
-
stream: false,
|
|
717
|
-
max_tokens: 30
|
|
718
|
-
}
|
|
719
|
-
});
|
|
720
|
-
const title = response.choices[0].message.content.trim();
|
|
721
|
-
updateTitle(id, title);
|
|
722
|
-
return title;
|
|
723
|
-
} catch (error) {
|
|
724
|
-
console.error("\u751F\u6210\u6807\u9898\u5931\u8D25:", error);
|
|
725
|
-
return conversation.title;
|
|
726
|
-
}
|
|
727
|
-
};
|
|
728
|
-
const getCurrentConversation = () => {
|
|
729
|
-
if (!state.currentId) return null;
|
|
730
|
-
return state.conversations.find((conv) => conv.id === state.currentId) || null;
|
|
731
|
-
};
|
|
732
|
-
loadConversations();
|
|
733
|
-
return {
|
|
734
|
-
state,
|
|
735
|
-
messageManager,
|
|
736
|
-
createConversation,
|
|
737
|
-
switchConversation,
|
|
738
|
-
deleteConversation,
|
|
739
|
-
updateTitle,
|
|
740
|
-
updateMetadata,
|
|
741
|
-
saveConversations,
|
|
742
|
-
loadConversations,
|
|
743
|
-
generateTitle,
|
|
744
|
-
getCurrentConversation
|
|
745
|
-
};
|
|
746
|
-
}
|
|
747
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
748
|
-
0 && (module.exports = {
|
|
749
|
-
AIClient,
|
|
750
|
-
BaseModelProvider,
|
|
751
|
-
ErrorType,
|
|
752
|
-
FinalStatus,
|
|
753
|
-
GeneratingStatus,
|
|
754
|
-
LocalStorageStrategy,
|
|
755
|
-
OpenAIProvider,
|
|
756
|
-
STATUS,
|
|
757
|
-
StreamEventType,
|
|
758
|
-
extractTextFromResponse,
|
|
759
|
-
formatMessages,
|
|
760
|
-
useConversation,
|
|
761
|
-
useMessage
|
|
762
|
-
});
|
|
3
|
+
`);i=c.pop()||"";for(let h of c)if(h.trim()!==""){if(h.trim()==="data: [DONE]"){e.onDone();continue}try{let m=h.match(/^data: (.+)$/m);if(!m)continue;let M=JSON.parse(m[1]);e.onData(M)}catch(m){console.error("Error parsing SSE message:",m)}}}(i.trim()==="data: [DONE]"||t?.aborted)&&e.onDone()}catch(o){if(t?.aborted)return;throw o}}function _(s){return s.map(e=>typeof e=="object"&&"role"in e&&"content"in e?{role:e.role,content:String(e.content),...e.name?{name:e.name}:{}}:typeof e=="string"?{role:"user",content:e}:{role:"user",content:String(e)})}function k(s){return!s.choices||!s.choices.length?"":s.choices[0].message?.content||""}var R=class extends S{constructor(t){super(t);this.defaultModel="gpt-3.5-turbo";this.baseURL=t.apiUrl||"https://api.openai.com/v1",this.apiKey=t.apiKey||"",t.defaultModel&&(this.defaultModel=t.defaultModel),this.apiKey||console.warn("API key is not provided. Authentication will likely fail.")}async chat(t){try{this.validateRequest(t);let a={model:t.options?.model||this.config.defaultModel||this.defaultModel,messages:t.messages,...t.options,stream:!1},d={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)};this.apiKey&&Object.assign(d.headers,{Authorization:`Bearer ${this.apiKey}`});let i=await fetch(`${this.baseURL}/chat/completions`,d);if(!i.ok){let o=await i.text();throw new Error(`HTTP error! status: ${i.status}, details: ${o}`)}return await i.json()}catch(a){throw x(a)}}async chatStream(t,a){let{signal:d,...i}=t.options||{};try{this.validateRequest(t);let o={model:t.options?.model||this.config.defaultModel||this.defaultModel,messages:t.messages,...i,stream:!0},p={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Accept:"text/event-stream"},body:JSON.stringify(o),signal:d};this.apiKey&&Object.assign(p.headers,{Authorization:`Bearer ${this.apiKey}`});let u=await fetch(`${this.baseURL}/chat/completions`,p);if(!u.ok){let c=await u.text();throw new Error(`HTTP error! status: ${u.status}, details: ${c}`)}await D(u,a,d)}catch(o){if(d?.aborted)return;a.onError(x(o))}}updateConfig(t){super.updateConfig(t),t.apiUrl&&(this.baseURL=t.apiUrl),t.apiKey&&(this.apiKey=t.apiKey),t.defaultModel&&(this.defaultModel=t.defaultModel)}};var y=class{constructor(e){this.config=e,this.provider=this.createProvider(e)}createProvider(e){if(e.provider==="custom"&&"providerImplementation"in e)return e.providerImplementation;switch(e.provider){case"deepseek":let t={defaultModel:"deepseek-chat",apiUrl:"https://api.deepseek.com/v1"};return new R({...t,...e});case"openai":default:return new R(e)}}async chat(e){return this.provider.chat(e)}async chatStream(e,t){let a={...e,options:{...e.options,stream:!0}};return this.provider.chatStream(a,t)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.provider&&e.provider!==this.config.provider?this.provider=this.createProvider(this.config):this.provider.updateConfig(this.config)}};var C=require("vue"),K=(o=>(o.INIT="init",o.PROCESSING="processing",o.STREAMING="streaming",o.FINISHED="finished",o.ABORTED="aborted",o.ERROR="error",o))(K||{}),q=["processing","streaming"],G=["finished","aborted","error"];function O(s){let{client:e,useStreamByDefault:t=!0,errorMessage:a="\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",initialMessages:d=[]}=s,i=(0,C.ref)([...d]),o=(0,C.ref)(""),p=(0,C.ref)(t),u=null,c=(0,C.reactive)({status:"init",errorMsg:null}),h=async r=>{let g={role:"assistant",content:(await e.chat({messages:(0,C.toRaw)(i.value),options:{stream:!1,signal:r.signal}})).choices[0].message.content};i.value.push(g)},m=async r=>{await e.chatStream({messages:(0,C.toRaw)(i.value),options:{stream:!0,signal:r.signal}},{onData:n=>{c.status="streaming",i.value[i.value.length-1].role==="user"&&i.value.push({role:"assistant",content:""});let g=n.choices?.[0];g&&g.delta.content&&(i.value[i.value.length-1].content+=g.delta.content)},onError:n=>{c.status="error",c.errorMsg=a,console.error("Stream request error:",n)},onDone:()=>{c.status="finished"}})},M=async()=>{c.status="processing",c.errorMsg=null,u=new AbortController;try{p.value?await m(u):await h(u),c.status="finished"}catch(r){c.errorMsg=a,c.status="error",console.error("Send message error:",r)}finally{u=null}};return{messages:i,messageState:c,inputMessage:o,useStream:p,sendMessage:async(r=o.value,n=!0)=>{if(!r?.trim()||q.includes(c.status))return;let g={role:"user",content:r};i.value.push(g),n&&(o.value=""),await M()},clearMessages:()=>{i.value=[],c.errorMsg=null},addMessage:r=>{i.value.push(r)},abortRequest:()=>{u&&(u.abort(),u=null,c.status="aborted")},retryRequest:async r=>{r===0||!i.value[r]||i.value[r].role==="user"||(i.value.splice(r),await M())}}}var E=require("vue");var A=class{constructor(e="tiny-robot-ai-conversations"){this.storageKey=e}saveConversations(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(t){console.error("\u4FDD\u5B58\u4F1A\u8BDD\u5931\u8D25:",t)}}loadConversations(){try{let e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return console.error("\u52A0\u8F7D\u4F1A\u8BDD\u5931\u8D25:",e),[]}}};function W(){return Date.now().toString(36)+Math.random().toString(36).substring(2,9)}function J(s){let{client:e,storage:t=new A,autoSave:a=!0,useStreamByDefault:d=!0,errorMessage:i="\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}=s,o=(0,E.reactive)({conversations:[],currentId:null,loading:!1}),p=O({client:e,useStreamByDefault:d,errorMessage:i,initialMessages:[]});(0,E.watch)(()=>p.messages.value,l=>{if(o.currentId&&l.length>0){let r=o.conversations.findIndex(n=>n.id===o.currentId);r!==-1&&(o.conversations[r].messages=[...l],o.conversations[r].updatedAt=Date.now(),a&&f())}},{deep:!0});let u=(l="\u65B0\u4F1A\u8BDD",r={})=>{let n=W(),g={id:n,title:l,createdAt:Date.now(),updatedAt:Date.now(),messages:[],metadata:r};return o.conversations.unshift(g),c(n),a&&f(),n},c=l=>{let r=o.conversations.find(n=>n.id===l);r&&(o.currentId=l,p.clearMessages(),r.messages.length>0&&r.messages.forEach(n=>p.addMessage(n)))},h=l=>{let r=o.conversations.findIndex(n=>n.id===l);r!==-1&&(o.conversations.splice(r,1),o.currentId===l&&(o.conversations.length>0?c(o.conversations[0].id):(o.currentId=null,p.clearMessages())),a&&f())},m=(l,r)=>{let n=o.conversations.find(g=>g.id===l);n&&(n.title=r,n.updatedAt=Date.now(),a&&f())},M=(l,r)=>{let n=o.conversations.find(g=>g.id===l);n&&(n.metadata={...n.metadata,...r},n.updatedAt=Date.now(),a&&f())},f=async()=>{try{await t.saveConversations(o.conversations)}catch(l){console.error("\u4FDD\u5B58\u4F1A\u8BDD\u5931\u8D25:",l)}},I=async()=>{o.loading=!0;try{let l=await t.loadConversations();o.conversations=l,l.length>0&&!o.currentId&&c(l[0].id)}catch(l){console.error("\u52A0\u8F7D\u4F1A\u8BDD\u5931\u8D25:",l)}finally{o.loading=!1}},w=async l=>{let r=o.conversations.find(n=>n.id===l);if(!r||r.messages.length<2)return r?.title||"\u65B0\u4F1A\u8BDD";try{let n={role:"system",content:"\u8BF7\u6839\u636E\u4EE5\u4E0B\u5BF9\u8BDD\u5185\u5BB9\uFF0C\u751F\u6210\u4E00\u4E2A\u7B80\u77ED\u7684\u6807\u9898\uFF08\u4E0D\u8D85\u8FC720\u4E2A\u5B57\u7B26\uFF09\u3002\u53EA\u9700\u8981\u8FD4\u56DE\u6807\u9898\u6587\u672C\uFF0C\u4E0D\u9700\u8981\u4EFB\u4F55\u89E3\u91CA\u6216\u989D\u5916\u5185\u5BB9\u3002"},g=r.messages.slice(0,Math.min(4,r.messages.length)),N=(await e.chat({messages:[n,...g],options:{stream:!1,max_tokens:30}})).choices[0].message.content.trim();return m(l,N),N}catch(n){return console.error("\u751F\u6210\u6807\u9898\u5931\u8D25:",n),r.title}},T=()=>o.currentId&&o.conversations.find(l=>l.id===o.currentId)||null;return I(),{state:o,messageManager:p,createConversation:u,switchConversation:c,deleteConversation:h,updateTitle:m,updateMetadata:M,saveConversations:f,loadConversations:I,generateTitle:w,getCurrentConversation:T}}0&&(module.exports={AIClient,BaseModelProvider,ErrorType,FinalStatus,GeneratingStatus,LocalStorageStrategy,OpenAIProvider,STATUS,StreamEventType,extractTextFromResponse,formatMessages,useConversation,useMessage});
|