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

import OpenAI from 'openai';

// const OpenAI = require("openai")

/**
 * Example of streaming a response from an assistant
 */

// const openai = new OpenAI();
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
})

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.',
  });

  // 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 = openai.beta.threads.runs
    .createAndStream(threadId, {
      assistant_id: assistantId,
    })
    //Subscribe to streaming events and log them
    .on('event', (event) => console.log(event))
    .on('textDelta', (delta, snapshot) => console.log(snapshot))
    .on('messageDelta', (delta, snapshot) => console.log(snapshot))
    .on('run', (run) => console.log(run))
    .on('messageDelta', (delta, snapshot) => console.log(snapshot))
    .on('connect', () => console.log());
  const result = await run.finalRun();
  console.log('Run Result' + result);
  console.log(JSON.stringify(result.required_action));
}

main();
