| 76 | const n_keep = await tokenize(instruction).length |
| 77 | |
| 78 | async function chat_completion(question) { |
| 79 | const result = await fetch(`${API_URL}/completion`, { |
| 80 | method: 'POST', |
| 81 | body: JSON.stringify({ |
| 82 | prompt: format_prompt(question), |
| 83 | temperature: 0.2, |
| 84 | top_k: 40, |
| 85 | top_p: 0.9, |
| 86 | n_keep: n_keep, |
| 87 | n_predict: 256, |
| 88 | cache_prompt: no_cached_prompt === "false", |
| 89 | slot_id: slot_id, |
| 90 | stop: ["\n### Human:"], // stop completion after generating this |
| 91 | grammar, |
| 92 | stream: true, |
| 93 | }) |
| 94 | }) |
| 95 | |
| 96 | if (!result.ok) { |
| 97 | return |
| 98 | } |
| 99 | |
| 100 | let answer = '' |
| 101 | |
| 102 | for await (var chunk of result.body) { |
| 103 | const t = Buffer.from(chunk).toString('utf8') |
| 104 | if (t.startsWith('data: ')) { |
| 105 | const message = JSON.parse(t.substring(6)) |
| 106 | slot_id = message.slot_id |
| 107 | answer += message.content |
| 108 | process.stdout.write(message.content) |
| 109 | if (message.stop) { |
| 110 | if (message.truncated) { |
| 111 | chat.shift() |
| 112 | } |
| 113 | break |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | process.stdout.write('\n') |
| 119 | chat.push({ human: question, assistant: answer.trimStart() }) |
| 120 | } |
| 121 | |
| 122 | const rl = readline.createInterface({ input: stdin, output: stdout }); |
| 123 | |