https://www.steamship.com/

OAI moderation is unavoidable now

//////////////

const STEAMSHIP_KEYS = ['YOUR_KEY_HERE']; // Можно вписать несколько ключей
const SYSTEM_PROMPT = ''; // Системный промпт
const TEMP = 0.9; // температура
const MAX_TOKENS = 400; // Максимальное кол-во токенов в ОТВЕТЕ бота

//////////////

const https = require('node:https');
const http = require('node:http');

const options = {
    hostname: 'api.steamship.com',
    port: 443,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
};

const readBody = (res) => new Promise((resolve, reject) => {
    let buffer = '';

    res.on('data', chunk => {
        buffer += chunk;
    });

    res.on('end', () => {
        try {
            resolve(JSON.parse(buffer));
        } catch (e) {
            reject(e);
        }
    });
})

const request = (path, data) =>
    new Promise((resolve, reject) => {
        const req = https.request({ ...options, path }, async (res) => {
            try {
                const body = await readBody(res);
                if (body.status?.state === 'failed') {
                    updateAuth();
                    await createInstance();
                    resolve(await request(path, data));
                } else {
                    resolve(body);
                }
            } catch (e) {
                reject(e);
            }
        });

        req.write(JSON.stringify(data));
        req.end();
    });

const delay = (ms) => new Promise(r => setTimeout(r, ms));

let pluginInstance = undefined;

function updateAuth() {
    if (STEAMSHIP_KEYS.length === 0) {
        console.log('OWARI DA');
        process.exit();
    } else {
        const key = STEAMSHIP_KEYS.shift();
        console.log(`Using key ${key}`);
        options.headers['Authorization'] = `Bearer ${key}`;
    }
}

async function createInstance() {
    const randomHandle = `gpt-4-${Math.random().toString().slice(2)}`;
    const response = await request('/api/v1/plugin/instance/create', {
        "handle": randomHandle,
        "pluginHandle": "gpt-4",
        "pluginVersionHandle": "0.0.2", // used to be *.1-rc.4
        "fetchIfExists": false,
        "config": {
            "moderate_output": false,
            "default_system_prompt": SYSTEM_PROMPT,
            "presence_penalty": 0,
            "request_timeout": 600,
            "frequency_penalty": 0,
            "model": "gpt-4",
            "top_p": 1,
            "max_tokens": MAX_TOKENS,
            "max_retries": 8,
            "default_role": "user",
            "n": 1,
            "temperature": TEMP,
            "openai_api_key": ""
        }
    });

    if (!response?.data?.pluginInstance) {
        console.error(response);
        return;
    }

    pluginInstance = randomHandle;
    options.headers['X-Workspace-Id'] = response.data.pluginInstance.workspaceId;
    console.log(`Created instance ${randomHandle}`);
}

async function generate(text) {
    const response = await request('/api/v1/plugin/instance/generate', {
        appendOutputToFile: false,
        text,
        pluginInstance
    });

    console.log(response);

    const { status } = response;

    if (status) {
        const { taskId } = status;

        while (true) {
            const response = await request('/api/v1/task/status', { taskId });

            console.log(response);

            const { data, status } = response;

            if (data) {
                return data.blocks;
            } else {
                console.log(status);
            }
            await delay(2000);
        }
    }
}


async function main() {
    updateAuth();
    await createInstance();

    const server = http.createServer(async (req, res) => {
        res.setHeader('Content-Type', 'application/json');
        if (req.method.toUpperCase() === 'POST') {
            const body = await readBody(req);

            const { prompt } = body;
            const blocks = await generate(prompt);

            res.write(JSON.stringify({ results: blocks }));
        } else {
            res.write(JSON.stringify({ result: 'gpt-4' }));
        }
        res.end();
    });

    server.listen(5004, '0.0.0.0', () => {
        console.log(`api: 'http://127.0.0.1:5004/api'`);
    });
}

main().catch(console.error);

BACKUP SPERMSHIP CODE

const puppeteer = require("puppeteer");
const fs = require("fs");

/** SETTINGS */
/** The script will salt the email for you, eg. [email protected] */
const BASE_EMAIL = "[email protected]";
const PASSWORD = "spermship123!";
const KEY_FILE_NAME = "keys.txt";

/** Don't fuck with this */
const COOLDOWN = 10000;

async function createAccount(page, email, password) {
  await page.goto("https://www.steamship.com/api/auth/login?returnTo=/");

  await page.$$eval("a", (anchors) => {
    const signUpLink = anchors.find((a) =>
      a.getAttribute("href").startsWith("/u/signup")
    );
    if (signUpLink) {
      signUpLink.click();
    } else {
      console.log("No 'Sign up' link found");
    }
  });

  await page.waitForSelector("input#email");
  await page.type("input#email", email);
  await page.waitForSelector("input#password");
  await page.type("input#password", password);

  await page.click('button[type="submit"]');

  await page.waitForNavigation();
}

async function login(page, email, password) {
  await page.goto("https://www.steamship.com/api/auth/login?returnTo=/");

  await page.waitForSelector("input#username");
  await page.type("input#username", email);
  await page.waitForSelector("input#password");
  await page.type("input#password", password);

  await page.click('button[type="submit"]');

  await page.waitForNavigation();
}

async function getApiKey(page) {
  await page.goto("https://www.steamship.com/account");

  const apiKey = await page.evaluate(async () => {
    const scriptElement = document.getElementById("__NEXT_DATA__");
    if (scriptElement) {
      const nextData = JSON.parse(scriptElement.textContent);
      return nextData.props.pageProps.user.apiKey;
    } else {
      return null;
    }
  });

  return apiKey;
}

(async () => {
  if (!fs.existsSync(KEY_FILE_NAME)) {
    console.log("Creating empty key list.");
    fs.writeFileSync(KEY_FILE_NAME, "");
  } else {
    const fileContent = fs.readFileSync(KEY_FILE_NAME, "utf-8");
    const lines = fileContent.split("\n").filter((line) => line.trim() !== "");
    console.log(`Found ${lines.length} existing keys.`);
  }

  const keysToCreate = getKeysToCreate();
  const browser = await puppeteer.launch({ headless: false });
  let retries = 0;

  try {
    for (let i = 0; i < keysToCreate; i++) {
      console.log("Creating key", i + 1);
      const email =
        BASE_EMAIL.substring(0, BASE_EMAIL.indexOf("@")) +
        `+${Math.random().toString(36).slice(2, 10)}` +
        BASE_EMAIL.substring(BASE_EMAIL.indexOf("@"));

      const browserContext = await browser.createIncognitoBrowserContext();
      const page = await browserContext.newPage();

      // await login(page, BASE_EMAIL, PASSWORD);
      await createAccount(page, email, PASSWORD);
      console.log("\tCreated account with email", email);

      const apiKey = await getApiKey(page);
      if (apiKey) {
        console.log("\tGrabbed API key:", apiKey);
        fs.appendFileSync(KEY_FILE_NAME, apiKey + "\n");
        console.log("\tSaved to disk. Waiting for cooldown...");
      } else {
        console.log("Couldn't find API key, possible issue creating account.");
        if (retries > 5) {
          throw new Error("Retry limit exceeded");
        }
        console.log("Retrying...");
        await page.waitForTimeout(COOLDOWN);
        await page.close();
        await browserContext.close();
        i--;
        continue;
      }

      await page.waitForTimeout(COOLDOWN);
      await page.close();
      await browserContext.close();
    }
  } catch (e) {
    console.error("An error occurred.", e);
  }

  console.log("Use Ctrl+C to exit.");
  // await browser.close();
})();

function getKeysToCreate() {
  const arg = process.argv.find(
    (arg) => arg.startsWith("--keysToCreate") || arg.startsWith("--keys")
  );
  if (arg) {
    const [_, value] = arg.split("=");
    if (value) {
      return value;
    }
  }
  console.log("No --keysToCreate specified.  Creating 3 keys.");
  return 3;
}

async function debugPage(page) {
  await page.screenshot({ path: "debug_screenshot.png" });
  const dom = await page.content();
  fs.writeFileSync("debug_dom.html", dom);
}
Edit Report
Pub: 24 Mar 2023 22:50 UTC
Views: 1754