Search code examples
javascriptnpmmodulesvelteopenai-api

How does importing module functions work when using npm in Svelte?


i don't understand how i properly use imports when working with Svelte and npm. This is a svelte component, which i can't get to work. Uncommenting "//import { Configuration, OpenAIApi } from "openai";" results in the [!] (plugin commonjs--resolver) RollupError: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)

Not uncommenting it results in Uncaught ReferenceError: Configuration is not defined in browser console.

<script>
//import { Configuration, OpenAIApi } from "openai";
const OpenAiConfiguration = new Configuration({
  organization: "my-org-key", 
  apiKey: "my-api-key",
});
$: gptRespons = "";
const questionQuery = "Do you agree with the sentiment and conclusion of the following article? "


async function FetchNews(link) {
  try {
    let brukSak = await AiSummarize(link);
    gptRespons = brukSak["data"]["choices"][0]["message"]["content"]
    console.log("Ferdig å hente og oppsummere nyheter");
  } catch (error) {
    alert("Error");
    console.error(error);
  }
  return;
}
async function AiSummarize(newsStoryUrl) {

  const openai = new OpenAIApi(OpenAiConfiguration);

  try {
    const result = await openai.createChatCompletion({
      model: "gpt-3.5-turbo",
      messages: [{role:"user", "content":`Skriv en oppsummering av ${newsStoryUrl} Oppsumeringen skal være morsom og glad`}]
    
    });

    return result;
  } catch (error) {
    alert("Error summarizing news story");
    console.error(error);
    throw error;
  }
}
FetchNews(insertlink")

</script>

<h2>
    GPT:Respons
</h2>
<p>
    {gptRespons}
</p>

How can i fix this? Is there in particular any parts or concepts of Svelte and mpm that I have misunderstood?

I expected the code to properly have access the Configuration class. Tried using openai.Configuration. Tried running npm install openai again. and tried running npm install @rollup/plugin-json --save-dev in the terminal.

Thank you so much for your time and attention<3

Here is my rollup.config file

import { spawn } from 'child_process';
import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

function serve() {
    let server;

    function toExit() {
        if (server) server.kill(0);
    }

    return {
        writeBundle() {
            if (server) return;
            server = spawn('npm', ['run', 'start', '--', '--dev'], {
                stdio: ['ignore', 'inherit', 'inherit'],
                shell: true
            });

            process.on('SIGTERM', toExit);
            process.on('exit', toExit);
        }
    };
}

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            compilerOptions: {
                // enable run-time checks when not in production
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),

        // If you have external dependencies installed from
        // npm, you'll most likely need these plugins. In
        // some cases you'll need additional configuration -
        // consult the documentation for details:
        // https://github.com/rollup/plugins/tree/master/packages/commonjs
        resolve({
            browser: true,
            dedupe: ['svelte'],
            exportConditions: ['svelte']
        }),
        commonjs(),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

Solution

  • so you need to add the JSON plugin in the configuration like so:

    import json from '@rollup/plugin-json';
    
    plugins: [
        // add JSON plugin
        json(),
    
        // other plugins
      ]
    

    However, if you are creating a new project I would advice you to create the project with Vite, it is a lot easier to develop with Vite.