|
1 | 1 | import OpenAI from 'openai';
|
| 2 | +import Redis from 'ioredis'; |
| 3 | +import crypto from 'crypto'; |
2 | 4 |
|
3 | 5 | /**
|
4 | 6 | * @param {string} something - thing that will get a random of it
|
| 7 | + * @param {string} lastAnswers - last answers to generate new thing |
5 | 8 | * @returns {string} the prompt for gpt
|
6 | 9 | */
|
7 |
| -function generatePrompt(something) { |
8 |
| - return `Please give me a random ${something}`; |
| 10 | +function getSomethingToAsk(something, lastAnswers) { |
| 11 | + if (lastAnswers) { |
| 12 | + return `${something} (last answer: ${lastAnswers})`; |
| 13 | + } |
| 14 | + return `${something}`; |
9 | 15 | }
|
10 | 16 |
|
11 | 17 | // eslint-disable-next-line require-jsdoc
|
12 | 18 | export async function getRandomFromGpt(something) {
|
| 19 | + const somethingMd5 = crypto.createHash('md5').update(something).digest('hex'); |
| 20 | + const client = new Redis(process.env.REDIS_URL); |
| 21 | + const lastAnswers = await client.get(somethingMd5); |
13 | 22 | const openai = new OpenAI({
|
14 | 23 | apiKey: process.env?.OPENAI_API_KEY,
|
15 | 24 | });
|
| 25 | + console.log('lastAnswers', lastAnswers); |
16 | 26 |
|
17 | 27 | const completion = await openai.chat.completions.create({
|
18 | 28 | model: 'gpt-4o-mini',
|
19 |
| - messages: [{role: 'user', content: generatePrompt(something)}], |
20 |
| - temperature: 0.6, |
21 |
| - max_tokens: 65, |
| 29 | + messages: [ |
| 30 | + { |
| 31 | + role: 'system', content: 'You are a system that generate randomly thing from user input. ' + |
| 32 | + 'If user dont ask how many thing to generate, just give 1 result' + |
| 33 | + 'don\'t use common answer.' + |
| 34 | + 'if user says animals, you list 1000 animals from the database and pick at random,' + |
| 35 | + 'to the point, no say \'sure\'' + |
| 36 | + '', |
| 37 | + }, |
| 38 | + {role: 'user', content: getSomethingToAsk(something, lastAnswers)}, |
| 39 | + ], |
| 40 | + temperature: 1, |
| 41 | + max_tokens: 75, |
22 | 42 | });
|
| 43 | + |
23 | 44 | let answer = 'Sorry I don\'t know what you mean';
|
24 | 45 | if (completion?.choices.length > 0) {
|
25 | 46 | answer = completion.choices.map((a) => a.message.content.replace(/(\r\n|\n|\r)/gm, '')).join('\n');
|
26 | 47 | }
|
| 48 | + await client.set(somethingMd5, lastAnswers ? lastAnswers + ', ' + answer : answer); |
27 | 49 | return answer;
|
28 | 50 | }
|
| 51 | + |
0 commit comments