#!/usr/bin/env -S npm run tsn -T

import OpenAI from 'openai';
import { sleep } from 'openai/core';

// const OpenAI = require("openai")
// const { sleep } = require("openai/core")

/**
 * Example of polling for a complete response from an assistant
 */

const API_KEY = "sk-"
// GPT_MODEL = "gpt-4-turbo-preview"
// OPENAI_BASE_URL = "https://filefast.io/chatgpt/v1"

const openai = new OpenAI({
  // baseURL: "https://api.openai.com/v1",
  // baseURL: "https://filefast.io/chatgpt/v1",
  apiKey: API_KEY
})



// asst_MuYhmDVKKSu1FnmcorA1yFWs

async function main() {
  const assistant = await openai.beta.assistants.create({
    model: 'gpt-4-turbo-preview',
    name: 'Math Tutor',
    instructions: 'You are a personal math tutor. Write and run code to answer math questions.',
    // tools = [],
  });

  // let assistantId = assistant.id;
  let assistantId = "asst_MuYhmDVKKSu1FnmcorA1yFWs";
  console.log('Created Assistant with Id: ' + assistantId);

  const thread = await openai.beta.threads.create({
    messages: [
      {
        role: 'user',
        content: '"给我创建比特币钱包"',
      },
    ],
  });

  let threadId = thread.id;
  console.log('Created thread with Id: ' + threadId);

  const run = await openai.beta.threads.runs.create(thread.id, {
    assistant_id: assistantId,
    additional_instructions: 'Please address the user as Jane Doe. The user has a premium account.',
  });

  console.log('Created run with Id: ' + run.id);

  while (true) {
    const result = await openai.beta.threads.runs.retrieve(thread.id, run.id);
    if (result.status == 'completed') {
      const messages = await openai.beta.threads.messages.list(thread.id);
      for (const message of messages.getPaginatedItems()) {
        console.log(message, message.content);
      }
      break;
    } else {
      console.log('Waiting for completion. Current status: ' + result.status);
      await sleep(5000);
    }
  }
}

main();
