Created
December 2, 2022 23:38
Revisions
-
antimatter15 created this gist
Dec 2, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,102 @@ #!/usr/bin/env node const fs = require("fs"); function uuid() { return [8, 4, 4, 4, 12] .map((k) => Math.random() .toString(16) .slice(3, 3 + k) ) .join("-"); } async function main() { const prompt = process.argv.slice(2).join(" ").trim(); const configPath = __dirname + "/config.json"; const config = JSON.parse(await fs.promises.readFile(configPath, "utf-8")); if (prompt === "reset") { config.conversation_id = null; console.log('Conversation thread reset') } else { await conversation(prompt, config); } await fs.promises.writeFile( configPath, JSON.stringify(config, null, " "), "utf-8" ); } async function conversation(prompt, config) { const payload = { action: "next", messages: [ { id: uuid(), role: "user", content: { content_type: "text", parts: [prompt] }, }, ], parent_message_id: config.last_message_id, model: "text-davinci-002-render", } if(config.conversation_id){ payload.conversation_id = config.conversation_id } const res = await fetch( "https://chat.openai.com/backend-api/conversation", { method: "POST", headers: { Authorization: "Bearer " + config.token, "Content-Type": "application/json", "X-OpenAI-Assistant-App-Id": "", }, body: JSON.stringify(payload), } ); if(res.status !== 200){ console.log(res.statusText) } let lastOutput = ""; for await (let chunk of getChunks(res)) { if (chunk === "data: [DONE]") { console.log(""); } else if (chunk.startsWith("data: ")) { const msg = JSON.parse(chunk.slice(6)); const text = msg.message.content.parts[0]; if (text) { config.last_message_id = msg.message.id; config.conversation_id = msg.conversation_id; process.stdout.write(text.slice(lastOutput.length)); lastOutput = text; } } } } async function* getChunks(res) { const dec = new TextDecoder(); const reader = res.body.getReader(); let result; let buffer = ""; while (!(result = await reader.read()).done) { buffer += dec.decode(result.value); let index; while ((index = buffer.indexOf("\n")) != -1) { const chunk = buffer.slice(0, index); yield chunk; buffer = buffer.slice(index + 1); } } } main(); This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,4 @@ { "last_message_id": "", "token": "" }