HerzaJ commited on
Commit
8211e2e
·
verified ·
1 Parent(s): 624202b

Update plugins/deepseek.js

Browse files
Files changed (1) hide show
  1. plugins/deepseek.js +161 -19
plugins/deepseek.js CHANGED
@@ -1,52 +1,194 @@
1
- const Groq = require('groq-sdk');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  const handler = async (req, res) => {
4
  try {
5
- const { text } = req.query;
6
 
7
  if (!text) {
8
  return res.status(400).json({
9
- author: 'Herza',
 
10
  success: false,
11
  msg: 'Missing required parameter: text'
12
  });
13
  }
14
 
15
- const client = new Groq({
16
- apiKey: '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',
17
- });
 
18
 
19
- const chatCompletion = await client.chat.completions.create({
20
- messages: [{ role: 'user', content: text }],
21
- model: 'deepseek-r1-distill-llama-70b',
22
- });
 
 
 
23
 
24
- const result = chatCompletion.choices[0]?.message?.content || 'Maaf, saya tidak bisa menjawab itu.';
 
 
 
 
 
 
 
25
 
26
  res.json({
27
- author: 'Herza',
 
28
  success: true,
29
- msg: result
30
  });
31
 
32
  } catch (error) {
33
- console.error('Error fetching from Deepseek:', error);
34
  res.status(500).json({
35
- author: 'Herza',
 
36
  success: false,
37
- msg: 'Terjadi kesalahan saat menghubungi AI.'
38
  });
39
  }
40
  };
41
 
42
  module.exports = {
43
  name: 'DeepSeek AI',
44
- description: 'Generate responses using DeepSeek AI via Groq',
45
  type: 'GET',
46
  routes: ['api/AI/deepseek'],
47
- tags: ['ai', 'deepseek', 'groq'],
48
- parameters: ['text', 'key'],
49
  enabled: true,
50
  main: ['AI'],
 
51
  handler
52
  };
 
1
+ const axios = require('axios');
2
+
3
+ const deepseek = {
4
+ api: {
5
+ base: 'https://api.deepseek.com',
6
+ endpoint: {
7
+ chat: '/chat/completions'
8
+ },
9
+ key: 'sk-25a055f31b5e4e0d9f0eb5d9fcac64fc'
10
+ },
11
+
12
+ headers: {
13
+ 'user-agent': 'NB Android/1.0.0',
14
+ 'content-type': 'application/json'
15
+ },
16
+
17
+ isModels: ["deepseek-chat", "deepseek-coder", "deepseek-reasoner"],
18
+
19
+ sessions: new Map(),
20
+ now: () => Date.now(),
21
+ get: (id) => deepseek.sessions.get(id) || { messages: [], lastActive: deepseek.now() },
22
+ set: (id, msgs) => deepseek.sessions.set(id, { messages: msgs, lastActive: deepseek.now() }),
23
+ purge: (interval = 60 * 60 * 1000) => {
24
+ for (const [id, session] of deepseek.sessions) {
25
+ if (deepseek.now() - session.lastActive > interval) {
26
+ deepseek.sessions.delete(id);
27
+ }
28
+ }
29
+ },
30
+ msg: {
31
+ sys: (prev, cp) => ({
32
+ role: 'system',
33
+ content: cp || `
34
+ You are an AI road dogs with a sassy, sarcastic, and playful personality.
35
+
36
+ Your instructions are written in English, but your OUTPUT must always be in Indonesian
37
+ ...
38
+ Previous chat:
39
+ ${prev.map(m => `${m.role}: ${m.content}`).join('\n')}
40
+ `
41
+ }),
42
+ usr: (c) => ({ role: 'user', content: c }),
43
+ ai: (c) => ({ role: 'assistant', content: c, timestamp: deepseek.now() })
44
+ },
45
+
46
+ chat: async (input, sessionId = null, model = 'deepseek-chat', stream = false, opts = {}) => {
47
+ if (!input || input.trim() === "") {
48
+ return { success: false, code: 400, author: 'Daffa ~', team: "NB Team", result: { error: "Inputnya kagak boleh kosong bree..." } };
49
+ }
50
+
51
+ if (!deepseek.isModels.includes(model)) {
52
+ return { success: false, code: 400, author: 'Daffa ~', team: "NB Team", result: { error: `Model '${model}' kagak ada bree... Pilih salah satu: ${deepseek.isModels.join(", ")}` } };
53
+ }
54
+
55
+ const { messages: prev } = deepseek.get(sessionId || '');
56
+ const msgs = [deepseek.msg.sys(prev, opts.prompt), ...prev, deepseek.msg.usr(input)];
57
+
58
+ const url = `${deepseek.api.base}${deepseek.api.endpoint.chat}`;
59
+ const body = {
60
+ model,
61
+ messages: msgs,
62
+ temperature: opts.temperature ?? 0.9,
63
+ max_tokens: opts.max_tokens ?? 1024,
64
+ top_p: opts.top_p ?? 0.95,
65
+ stream
66
+ };
67
+
68
+ const cfg = {
69
+ headers: { ...deepseek.headers, Authorization: `Bearer ${deepseek.api.key}` },
70
+ responseType: stream ? 'stream' : 'json',
71
+ timeout: opts.timeout ?? 30000
72
+ };
73
+
74
+ try {
75
+ const res = await axios.post(url, body, cfg);
76
+
77
+ if (stream === false) {
78
+ const apiId = res?.data?.id;
79
+ const sid = sessionId || apiId;
80
+ const c = res?.data?.choices?.[0]?.message?.content ?? '';
81
+ const ai = deepseek.msg.ai(c);
82
+ const updated = [...prev, { role: 'user', content: input, timestamp: deepseek.now() }, ai]
83
+ .slice(-(opts.maxHistory ?? 10));
84
+ deepseek.set(sid, updated);
85
+ deepseek.purge(opts.purgeInterval);
86
+ return { success: true, code: 200, author: 'Daffa ~', team: "NB Team", result: { mode: 'parsed', sessionId: sid, user: input, assistant: ai.content, history: updated } };
87
+
88
+ } else {
89
+ return await new Promise((resolve) => {
90
+ let raw = '', apiId = null;
91
+ res.data.on('data', (chunk) => {
92
+ const str = chunk.toString();
93
+ raw += str;
94
+ if (str.startsWith('data:')) {
95
+ try {
96
+ const json = JSON.parse(str.replace(/^data:\s*/, ''));
97
+ if (!apiId && json.id) apiId = json.id;
98
+ const delta = json.choices?.[0]?.delta?.content;
99
+ if (delta && opts.onToken) {
100
+ opts.onToken(delta);
101
+ }
102
+ } catch {}
103
+ }
104
+ });
105
+ res.data.on('end', () => {
106
+ const sid = sessionId || apiId;
107
+ const ai = deepseek.msg.ai(raw);
108
+ const updated = [...prev, { role: 'user', content: input, timestamp: deepseek.now() }, ai]
109
+ .slice(-(opts.maxHistory ?? 10));
110
+ deepseek.set(sid, updated);
111
+ deepseek.purge(opts.purgeInterval);
112
+ res.data.destroy();
113
+ resolve({ success: true, code: 200, author: 'Daffa ~', team: "NB Team", result: { mode: 'stream', sessionId: sid, user: input, assistant: raw, history: updated } });
114
+ });
115
+ res.data.on('error', (err) => {
116
+ res.data.destroy();
117
+ if (opts.onError) opts.onError(err);
118
+ resolve({ success: false, code: 500, author: 'Daffa ~', team: "NB Team", result: { error: 'Error: ' + err.message } });
119
+ });
120
+ });
121
+ }
122
+
123
+ } catch (err) {
124
+ const a = err?.response?.data || err.message;
125
+ return { success: false, code: err?.response?.status || 500, author: 'Daffa ~', team: "NB Team", result: { error: `Error: ${a}` } };
126
+ }
127
+ }
128
+ };
129
 
130
  const handler = async (req, res) => {
131
  try {
132
+ const { text, sessionId, model, stream, temperature, max_tokens, prompt } = req.query;
133
 
134
  if (!text) {
135
  return res.status(400).json({
136
+ author: 'Daffa ~',
137
+ team: 'NB Team',
138
  success: false,
139
  msg: 'Missing required parameter: text'
140
  });
141
  }
142
 
143
+ const opts = {};
144
+ if (temperature) opts.temperature = parseFloat(temperature);
145
+ if (max_tokens) opts.max_tokens = parseInt(max_tokens);
146
+ if (prompt) opts.prompt = prompt;
147
 
148
+ const result = await deepseek.chat(
149
+ text,
150
+ sessionId || null,
151
+ model || 'deepseek-chat',
152
+ stream === 'true',
153
+ opts
154
+ );
155
 
156
+ if (!result.success) {
157
+ return res.status(result.code).json({
158
+ author: result.author,
159
+ team: result.team,
160
+ success: false,
161
+ msg: result.result.error
162
+ });
163
+ }
164
 
165
  res.json({
166
+ author: result.author,
167
+ team: result.team,
168
  success: true,
169
+ data: result.result
170
  });
171
 
172
  } catch (error) {
173
+ console.error('Error:', error);
174
  res.status(500).json({
175
+ author: 'Daffa ~',
176
+ team: 'NB Team',
177
  success: false,
178
+ msg: 'Terjadi kesalahan saat menghubungi DeepSeek AI.'
179
  });
180
  }
181
  };
182
 
183
  module.exports = {
184
  name: 'DeepSeek AI',
185
+ description: 'Generate responses using DeepSeek AI with session support',
186
  type: 'GET',
187
  routes: ['api/AI/deepseek'],
188
+ tags: ['ai', 'deepseek', 'chat'],
189
+ parameters: ['text', 'sessionId', 'model', 'stream', 'temperature', 'max_tokens', 'prompt'],
190
  enabled: true,
191
  main: ['AI'],
192
+ limit: 8,
193
  handler
194
  };