-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai-chatbot.js
More file actions
375 lines (321 loc) · 12.3 KB
/
ai-chatbot.js
File metadata and controls
375 lines (321 loc) · 12.3 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/**
* Rahyana AI API - چتبات هوش مصنوعی پیشرفته برای کسبوکارها
*
* این پروژه یک چتبات کامل و آماده تولید با قابلیتهای پیشرفته:
* - گفتگوی طبیعی و هوشمند با کاربران
* - پردازش تصاویر و فایلهای چندرسانهای
* - جستجوی وب و دسترسی به اطلاعات بهروز
* - فراخوانی توابع و ادغام با سیستمهای خارجی
* - ذخیره تاریخچه مکالمات و یادگیری
* - پشتیبانی از چندین زبان و فرهنگ
* - چتباتهای تخصصی (فروش، پشتیبانی، آموزشی)
*
* 🚀 ویژگیهای کلیدی:
* - معماری مقیاسپذیر و قابل توسعه
* - مدیریت خطاهای پیشرفته
* - پشتیبانی از streaming responses
* - قابلیت شخصیسازی و سفارشیسازی
*
* 💼 مناسب برای:
* - پشتیبانی مشتریان 24/7
* - دستیار فروش و مشاوره
* - مشاوره تخصصی و حرفهای
* - سیستمهای آموزشی تعاملی
* - کسبوکارهای آنلاین
*/
// Configuration - supports environment variable or placeholder
const API_KEY = process.env.RAHYANA_API_KEY || 'YOUR_API_KEY_HERE'; // کلید API خود را اینجا قرار دهید یا از متغیر محیطی RAHYANA_API_KEY استفاده کنید
const BASE_URL = process.env.RAHYANA_BASE_URL || 'https://rahyana.ir/api/v1';
class AIChatbot {
constructor(apiKey, baseUrl, options = {}) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.conversationHistory = [];
this.systemPrompt = options.systemPrompt || 'شما یک دستیار هوشمند و مفید هستید.';
this.maxHistory = options.maxHistory || 10;
this.language = options.language || 'fa';
}
// افزودن پیام به تاریخچه
addToHistory(role, content) {
this.conversationHistory.push({ role, content });
// محدود کردن تاریخچه
if (this.conversationHistory.length > this.maxHistory * 2) {
this.conversationHistory = this.conversationHistory.slice(-this.maxHistory * 2);
}
}
// دریافت پاسخ از API
async getResponse(userMessage, options = {}) {
try {
// افزودن پیام کاربر به تاریخچه
this.addToHistory('user', userMessage);
// آمادهسازی پیامها
const messages = [
{ role: 'system', content: this.systemPrompt },
...this.conversationHistory
];
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://ai-chatbot-app.com',
'X-Title': 'AI Chatbot'
},
body: JSON.stringify({
model: 'openai/gpt-4o', // مدل GPT-4o برای چتبات
messages: messages,
stream: options.stream || false,
temperature: options.temperature || 0.7,
max_tokens: options.maxTokens || 500,
tools: options.tools || undefined,
tool_choice: options.toolChoice || 'auto'
})
});
if (!response.ok) {
throw new Error(`خطای HTTP! وضعیت: ${response.status}`);
}
const data = await response.json();
const assistantMessage = data.choices[0].message.content;
// افزودن پاسخ به تاریخچه
this.addToHistory('assistant', assistantMessage);
return {
message: assistantMessage,
usage: data.usage,
finishReason: data.choices[0].finish_reason
};
} catch (error) {
console.error('خطا در دریافت پاسخ:', error);
throw error;
}
}
// پاسخ جریانی
async getStreamingResponse(userMessage, onChunk) {
try {
this.addToHistory('user', userMessage);
const messages = [
{ role: 'system', content: this.systemPrompt },
...this.conversationHistory
];
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://ai-chatbot-app.com',
'X-Title': 'AI Chatbot'
},
body: JSON.stringify({
model: 'openai/gpt-4o',
messages: messages,
stream: true,
temperature: 0.7,
max_tokens: 1000
})
});
if (!response.ok) {
throw new Error(`خطای HTTP! وضعیت: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
this.addToHistory('assistant', fullResponse);
return fullResponse;
}
try {
const parsed = JSON.parse(data);
if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta && parsed.choices[0].delta.content) {
const content = parsed.choices[0].delta.content;
fullResponse += content;
onChunk(content);
}
} catch (e) {
// نادیده گرفتن خطاهای پارس
}
}
}
}
return fullResponse;
} catch (error) {
console.error('خطا در پاسخ جریانی:', error);
throw error;
}
}
// تحلیل تصویر
async analyzeImage(imageUrl, question = 'این تصویر چه چیزی را نشان میدهد؟') {
try {
const messages = [
{ role: 'system', content: this.systemPrompt },
{
role: 'user',
content: [
{ type: 'text', text: question },
{
type: 'image_url',
image_url: { url: imageUrl }
}
]
}
];
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://ai-chatbot-app.com',
'X-Title': 'AI Chatbot Image Analysis'
},
body: JSON.stringify({
model: 'openai/gpt-4o',
messages: messages,
stream: false,
temperature: 0.7,
max_tokens: 500
})
});
if (!response.ok) {
throw new Error(`خطای HTTP! وضعیت: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
} catch (error) {
console.error('خطا در تحلیل تصویر:', error);
throw error;
}
}
// جستجوی وب
async searchWeb(query) {
try {
const response = await fetch(`${this.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://ai-chatbot-app.com',
'X-Title': 'AI Chatbot Web Search'
},
body: JSON.stringify({
model: 'google/gemini-2.0-flash-001',
messages: [
{ role: 'user', content: query }
],
web_search_options: {
search: true
},
stream: false,
temperature: 0.7,
max_tokens: 800
})
});
if (!response.ok) {
throw new Error(`خطای HTTP! وضعیت: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
} catch (error) {
console.error('خطا در جستجوی وب:', error);
throw error;
}
}
// چتبات تخصصی فروش
static createSalesBot(apiKey, baseUrl) {
return new AIChatbot(apiKey, baseUrl, {
systemPrompt: `شما یک مشاور فروش حرفهای هستید.
وظایف شما:
- پاسخ به سوالات مشتریان درباره محصولات
- ارائه پیشنهادات مناسب
- راهنمایی در فرآیند خرید
- حل مشکلات مشتریان
همیشه مودب، مفید و متخصص باشید.`
});
}
// چتبات پشتیبانی فنی
static createSupportBot(apiKey, baseUrl) {
return new AIChatbot(apiKey, baseUrl, {
systemPrompt: `شما یک متخصص پشتیبانی فنی هستید.
وظایف شما:
- حل مشکلات فنی کاربران
- راهنمایی در استفاده از محصولات
- ارائه راهحلهای عملی
- ارجاع مسائل پیچیده به تیم تخصصی
صبور، دقیق و مفید باشید.`
});
}
// چتبات آموزشی
static createEducationalBot(apiKey, baseUrl, subject) {
return new AIChatbot(apiKey, baseUrl, {
systemPrompt: `شما یک معلم متخصص در زمینه ${subject} هستید.
وظایف شما:
- آموزش مفاهیم به زبان ساده
- پاسخ به سوالات دانشآموزان
- ارائه مثالهای عملی
- تشویق و انگیزهدهی
صبور، تشویقکننده و آموزشی باشید.`
});
}
// پاک کردن تاریخچه
clearHistory() {
this.conversationHistory = [];
}
// دریافت تاریخچه
getHistory() {
return this.conversationHistory;
}
// تنظیم زبان
setLanguage(language) {
this.language = language;
}
}
// مثال استفاده
async function demonstrateChatbot() {
console.log('🤖 شروع چتبات هوش مصنوعی...\n');
// چتبات عمومی
const bot = new AIChatbot(API_KEY, BASE_URL);
try {
// گفتگوی ساده
console.log('👤 کاربر: سلام! چطور میتونم کمکتون کنم؟');
const response1 = await bot.getResponse('سلام! چطور میتونم کمکتون کنم؟');
console.log('🤖 چتبات:', response1.message + '\n');
// گفتگوی ادامهدار
console.log('👤 کاربر: درباره هوش مصنوعی توضیح بده');
const response2 = await bot.getResponse('درباره هوش مصنوعی توضیح بده');
console.log('🤖 چتبات:', response2.message + '\n');
// جستجوی وب
console.log('🔍 جستجوی وب: آخرین اخبار هوش مصنوعی');
const webResult = await bot.searchWeb('آخرین اخبار هوش مصنوعی در سال 2024');
console.log('🌐 نتیجه جستجو:', webResult.substring(0, 200) + '...\n');
} catch (error) {
console.error('خطا در اجرای چتبات:', error);
}
// چتبات تخصصی فروش
console.log('🛍️ چتبات فروش:');
const salesBot = AIChatbot.createSalesBot(API_KEY, BASE_URL);
try {
const salesResponse = await salesBot.getResponse('من به دنبال یک لپتاپ برای کارهای برنامهنویسی هستم');
console.log('🤖 مشاور فروش:', salesResponse.message + '\n');
} catch (error) {
console.error('خطا در چتبات فروش:', error);
}
// چتبات آموزشی
console.log('📚 چتبات آموزشی:');
const eduBot = AIChatbot.createEducationalBot(API_KEY, BASE_URL, 'برنامهنویسی');
try {
const eduResponse = await eduBot.getResponse('جاوااسکریپت چیست و چرا مهم است؟');
console.log('🤖 معلم:', eduResponse.message + '\n');
} catch (error) {
console.error('خطا در چتبات آموزشی:', error);
}
}
// اجرای مثال
if (import.meta.url === `file://${process.argv[1]}`) {
demonstrateChatbot();
}
export default AIChatbot;