Skip to content

Instantly share code, notes, and snippets.

@antimatter15
Created December 2, 2022 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antimatter15/9ca4136443ec72d004c109f606c8f7f1 to your computer and use it in GitHub Desktop.
Save antimatter15/9ca4136443ec72d004c109f606c8f7f1 to your computer and use it in GitHub Desktop.
ChatGPT CLI Command Line Interface
#!/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();
{
"last_message_id": "",
"token": ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment