Advertisement
Amiminoru

Spermflow 3

Aug 11th, 2023 (edited)
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const axios = require('axios');
  2. const http = require('http');
  3.  
  4. // View our quick start guide to get your API key:
  5. // https://www.voiceflow.com/api/dialog-manager#section/Quick-Start
  6. const apiKey = '';
  7.  
  8. const userID = ''; // Unique ID used to track conversation state
  9.  
  10. const readBody = (res, json, onData) => new Promise((resolve, reject) => {
  11.     let buffer = '';
  12.  
  13.     res.on('data', chunk => {
  14.         onData?.(chunk.toString());
  15.         buffer += chunk;
  16.     });
  17.  
  18.     res.on('end', () => {
  19.         try {
  20.             if (json) buffer = JSON.parse(buffer);
  21.             resolve(buffer);
  22.         } catch (e) {
  23.             console.error(buffer);
  24.             reject(e);
  25.         }
  26.     });
  27. })
  28.  
  29. function isObject (value) {  
  30.     return Object.prototype.toString.call(value) === '[object Object]'
  31. }
  32.  
  33. async function startInteract(messages) {
  34.     return new Promise(async (resolve, reject) => {
  35.         const body = {
  36.             action: {
  37.             type: 'text',
  38.             payload: messages,
  39.             },
  40.         };
  41.     try {
  42.         // Start a conversation
  43.         const response = await axios({
  44.             method: 'POST',
  45.             baseURL: 'https://general-runtime.voiceflow.com',
  46.             url: `/state/user/${userID}/interact`,
  47.             headers: {
  48.             Authorization: apiKey,
  49.             },
  50.             data: body,
  51.         });
  52.         // Log the response
  53.         if(!response.data[1]?.payload?.message)
  54.             console.log(response.data)
  55.         resolve(response.data[1]?.payload?.message)
  56.     }
  57.     catch(e) {
  58.         reject(e)
  59.     }
  60.     })
  61. }
  62.  
  63. function preparePrompt(messages) {
  64.     return messages.filter(m => m.content?.trim()).map(m => {
  65.         let author = '';
  66.         switch (m.role) {
  67.             case 'user': author = 'Human'; break;
  68.             case 'assistant': author = 'Assistant'; break;
  69.             case 'system': author = 'System Note'; break;
  70.             default: author = m.role; break;
  71.         }
  72.  
  73.         return `${author}: ${m.content.trim()}`;
  74.     }).join('\n') + `\nAssistant: `;
  75. }
  76.  
  77. async function main() {
  78.     const server = http.createServer(async (req, res) => {
  79.         if (req.method.toUpperCase() === 'POST') {
  80.             if(!apiKey) {
  81.                 console.log("Нет API ключа.")
  82.                 res.end()
  83.                 return
  84.             }
  85.             const body = await readBody(req, true);
  86.             const [, modelName] = req.url.split('/');
  87.             let {
  88.                 messages,
  89.             } = body;
  90.             res.setHeader('Content-Type', 'application/json');
  91.             const id = `chatcmpl-${(Math.random().toString(36).slice(2))}`;
  92.             const created = Math.floor(Date.now() / 1000);
  93.             if(modelName == "anthropic") {
  94.  
  95.                 messages = preparePrompt(messages)
  96.             }
  97.             else messages = JSON.stringify(messages)
  98.             let result = ""
  99.             console.log("Ожидаем ответа...")
  100.             while(!result) {
  101.                 try {
  102.                     result = await startInteract(messages);
  103.                     console.log("Ответ Voiceflow:\n\n", result)
  104.                 } catch (error) {
  105.                     result = error
  106.                 }
  107.             }
  108.             if(isObject(result)) {
  109.                 result = JSON.stringify(result)
  110.             }
  111.             else if(result.startsWith("{")) {
  112.                 try {
  113.                     result = JSON.parse(result)            
  114.                     if(result.content) result = result.content
  115.                     else if(result.assistant) result = result.assistant
  116.                 }
  117.                 catch(e) {console.log(e)}
  118.             }
  119.  
  120.             else { result = result.replace(/\\n/g, ' \n').replace(/\\"/g, '"') }
  121.             res.write(JSON.stringify({
  122.                 id, created,
  123.                 object: 'chat.completion',
  124.                 model: "GPT-4",
  125.                 choices: [{
  126.                     message: {
  127.                         role: 'assistant',
  128.                         content: result,
  129.                     },
  130.                     finish_reason: 'stop',
  131.                     index: 0,
  132.                 }]
  133.             }))
  134.             res.end();
  135.         } else {
  136.             res.setHeader('Content-Type', 'application/json');
  137.             res.write(JSON.stringify({
  138.                 object: 'list',
  139.                 data: [
  140.                     { id: 'GPT-4', object: 'model', created: Date.now(), owned_by: 'OpenAI', permission: [], root: 'GPT-4', parent: null },
  141.                     { id: 'Claude', object: 'model', created: Date.now(), owned_by: 'Anthropic', permission: [], root: 'Claude', parent: null },
  142.                 ]
  143.             }));
  144.         }
  145.         res.end();
  146.     });
  147.  
  148.     server.listen(5006, '0.0.0.0', () => {
  149.         console.log('Voiceflow с промптами в формате GPT-4: http://127.0.0.1:5006/\n' +
  150.                     'Промпты в формате Claude (human/assistant): http://127.0.0.1:5006/anthropic');
  151.     });
  152. }
  153.  
  154. main().catch(console.error);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement