Skip to content

Instantly share code, notes, and snippets.

@antimatter15
Created December 2, 2022 23:38

Revisions

  1. antimatter15 created this gist Dec 2, 2022.
    102 changes: 102 additions & 0 deletions chatgpt.js
    Original 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();
    4 changes: 4 additions & 0 deletions config.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    {
    "last_message_id": "",
    "token": ""
    }