import "@johnlindquist/kit";
let { ChatOpenAI } = await import("langchain/chat_models");
let { HumanChatMessage, SystemChatMessage } = await import("langchain/schema");
let openAIApiKey = await env("OPENAI_API_KEY", {
  hint: `Grab a key from <a href="https://platform.openai.com/account/api-keys">here</a>`,
});
let { CallbackManager } = await import("langchain/callbacks");
let prompt = `#####
You are ChatGPT, a large language model trained by OpenAI. Follow the user's
instructions carefully. Respond using markdown.
########
`;
let currentMessage = "";
const chat = new ChatOpenAI({
  temperature: 0.3,
  openAIApiKey: openAIApiKey,
  streaming: true,
  callbackManager: CallbackManager.fromHandlers({
    handleLLMStart: async (token) => {
      let widget = await widget(`
<div class="bg-black text-white h-screen p-5">
    Loading...
<div>
`);
      log(`handleLLMStart`);
      currentMessage += token;
      let html = md(token);
      await div(html);
    },
    handleLLMNewToken: async (token, runId) => {
      log(`handleLLMNewToken`);
      currentMessage += token;
      let html = md(currentMessage);
      await div(html);
    },
    handleLLMError: async (err) => {
      warn(`error`, JSON.stringify(err));
      await setSelectedText(JSON.stringify(err));
    },
    handleLLMEnd: async () => {
      widget = null;
      log(`handleLLMEnd`);
      let html = md(currentMessage);
      await div(html);
    },
  }),
});
let textFromUser = await arg("How can I help you?");
await chat.call([new SystemChatMessage(prompt), new HumanChatMessage(textFromUser)]);