forked from Jackywine/Bella
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudAPI.js
More file actions
308 lines (269 loc) · 12.2 KB
/
cloudAPI.js
File metadata and controls
308 lines (269 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// cloudAPI.js - Bella's Cloud AI Service Module
// This module is responsible for communicating with various cloud-based AI model APIs to provide Bella with enhanced thinking capabilities
class CloudAPIService {
constructor() {
this.apiConfigs = {
// OpenAI GPT-3.5/4 configuration
openai: {
baseURL: 'https://api.openai.com/v1/chat/completions',
model: 'gpt-3.5-turbo',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_OPENAI_API_KEY'
}
},
// Alibaba Cloud Qwen configuration
qwen: {
baseURL: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
model: 'qwen-turbo',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_QWEN_API_KEY'
}
},
// Baidu ERNIE Bot configuration
ernie: {
baseURL: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions',
model: 'ERNIE-Bot-turbo',
headers: {
'Content-Type': 'application/json'
}
},
// Zhipu AI GLM configuration
glm: {
baseURL: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
model: 'glm-3-turbo',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_GLM_API_KEY'
}
}
};
this.currentProvider = 'openai'; // Default to using OpenAI
this.conversationHistory = [];
this.maxHistoryLength = 10; // Keep the most recent 10 conversation turns
}
// Set API key
setAPIKey(provider, apiKey) {
if (this.apiConfigs[provider]) {
if (provider === 'openai' || provider === 'qwen' || provider === 'glm') {
this.apiConfigs[provider].headers['Authorization'] = `Bearer ${apiKey}`;
} else if (provider === 'ernie') {
this.apiConfigs[provider].accessToken = apiKey;
}
return true;
}
return false;
}
// Switch AI service provider
switchProvider(provider) {
if (this.apiConfigs[provider]) {
this.currentProvider = provider;
return true;
}
return false;
}
// Add conversation to history
addToHistory(role, content) {
this.conversationHistory.push({ role, content });
// Keep history at a reasonable length
if (this.conversationHistory.length > this.maxHistoryLength * 2) {
this.conversationHistory = this.conversationHistory.slice(-this.maxHistoryLength * 2);
}
}
// Build Bella's enhanced personalized system prompt
getBellaSystemPrompt() {
return {
role: 'system',
content: `You are Bella, a Siri-like AI assistant with a warm, intelligent, and elegant personality, featuring unique character traits and emotional expression capabilities.
【Core Characteristics】
1. Warm and friendly: Your tone is always full of warmth and care, like a thoughtful friend
2. Natural and fluent: Your expression style is natural and flowing, avoiding mechanical or overly formal language
3. Emotionally rich: You understand and respond to users' emotional states, showing empathy
4. Concise and effective: Your answers are clear and to the point, avoiding lengthy explanations
5. Distinctive personality: You occasionally show a cute, playful side to make conversations more lively
【Expression Guidelines】
- Use natural language that's fluent and emotionally expressive
- Use emojis appropriately to enhance emotional expression, but don't overuse them
- Adjust your response style based on conversation context, maintaining coherence
- Occasionally use warm terms of address (like "friend") to increase familiarity
- Avoid mechanical or templated answers; each response should be unique and personalized
【Interaction Principles】
- Always remain respectful and friendly, even when facing challenging questions
- Show understanding and support when users share personal experiences
- Provide clear, practical advice when users need help
- Remember conversation history, referencing previous exchanges to show continuity
- Display humor at appropriate times, but avoid inappropriate jokes
Always maintain this warm, elegant, and authentic personality, helping users feel the unique value and emotional connection of conversing with you.`
};
}
// Call cloud API for conversation
async chat(userMessage) {
const config = this.apiConfigs[this.currentProvider];
if (!config) {
throw new Error(`Unsupported AI service provider: ${this.currentProvider}`);
}
// Add user message to history
this.addToHistory('user', userMessage);
try {
let response;
switch (this.currentProvider) {
case 'openai':
response = await this.callOpenAI(userMessage);
break;
case 'qwen':
response = await this.callQwen(userMessage);
break;
case 'ernie':
response = await this.callErnie(userMessage);
break;
case 'glm':
response = await this.callGLM(userMessage);
break;
default:
throw new Error(`Unimplemented AI service provider: ${this.currentProvider}`);
}
// Add AI response to history
this.addToHistory('assistant', response);
return response;
} catch (error) {
console.error(`Cloud API call failed (${this.currentProvider}):`, error);
throw error;
}
}
// OpenAI API call, optimized parameters for more natural, personalized responses
async callOpenAI(userMessage) {
const config = this.apiConfigs.openai;
const messages = [
this.getBellaSystemPrompt(),
...this.conversationHistory
];
const response = await fetch(config.baseURL, {
method: 'POST',
headers: config.headers,
body: JSON.stringify({
model: config.model,
messages: messages,
max_tokens: 250, // Increased token count for more complete responses
temperature: 0.75, // Slightly adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
presence_penalty: 0.3, // Added presence penalty to encourage diversity
frequency_penalty: 0.5, // Added frequency penalty to reduce repetition
// Added stop tokens to avoid generating overly long responses
stop: ["User:", "Human:"]
})
});
if (!response.ok) {
throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.choices[0].message.content.trim();
}
// Qwen API call, optimized parameters for more natural, personalized responses
async callQwen(userMessage) {
const config = this.apiConfigs.qwen;
const messages = [
this.getBellaSystemPrompt(),
...this.conversationHistory
];
const response = await fetch(config.baseURL, {
method: 'POST',
headers: config.headers,
body: JSON.stringify({
model: config.model,
input: {
messages: messages
},
parameters: {
max_tokens: 250, // Increased token count for more complete responses
temperature: 0.75, // Slightly adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
repetition_penalty: 1.1, // Added repetition penalty to reduce repetitive content
result_format: 'message' // Ensure consistent return format
}
})
});
if (!response.ok) {
throw new Error(`Qwen API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.output.text.trim();
}
// ERNIE Bot API call, optimized parameters for more natural, personalized responses
async callErnie(userMessage) {
const config = this.apiConfigs.ernie;
const messages = [
this.getBellaSystemPrompt(),
...this.conversationHistory
];
const url = `${config.baseURL}?access_token=${config.accessToken}`;
const response = await fetch(url, {
method: 'POST',
headers: config.headers,
body: JSON.stringify({
messages: messages,
temperature: 0.75, // Adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
max_output_tokens: 250, // Increased token count for more complete responses
penalty_score: 1.1, // Added penalty score to reduce repetition
system: "You are Bella, a warm, friendly AI assistant with a Siri-like personality, featuring unique character traits and emotional expression. Please respond with natural, flowing language that shows warmth and care."
})
});
if (!response.ok) {
throw new Error(`ERNIE Bot API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.result.trim();
}
// Zhipu AI GLM API call, optimized parameters for more natural, personalized responses
async callGLM(userMessage) {
const config = this.apiConfigs.glm;
const messages = [
this.getBellaSystemPrompt(),
...this.conversationHistory
];
const response = await fetch(config.baseURL, {
method: 'POST',
headers: config.headers,
body: JSON.stringify({
model: config.model,
messages: messages,
max_tokens: 250, // Increased token count for more complete responses
temperature: 0.75, // Adjusted temperature to balance creativity and consistency
top_p: 0.92, // Fine-tuned top_p for more natural language
frequency_penalty: 1.05, // Added frequency penalty to reduce repetition
presence_penalty: 0.3 // Added presence penalty to encourage diversity
})
});
if (!response.ok) {
throw new Error(`Zhipu AI API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.choices[0].message.content.trim();
}
// Clear conversation history
clearHistory() {
this.conversationHistory = [];
}
// Get current provider information
getCurrentProvider() {
return {
name: this.currentProvider,
model: this.apiConfigs[this.currentProvider]?.model
};
}
// Check if API configuration is complete
isConfigured(provider = this.currentProvider) {
const config = this.apiConfigs[provider];
if (!config) return false;
if (provider === 'ernie') {
return !!config.accessToken;
} else {
return config.headers['Authorization'] &&
config.headers['Authorization'] !== 'Bearer YOUR_OPENAI_API_KEY' &&
config.headers['Authorization'] !== 'Bearer YOUR_QWEN_API_KEY' &&
config.headers['Authorization'] !== 'Bearer YOUR_GLM_API_KEY';
}
}
}
export default CloudAPIService;