OpenAI with SvelteKit: Basic integration

openai-with-sveltekit-basic-integration-560c

Note: This is a basic use of OpenAI in svelteKit which means that this article don't gonna care about security. It's a simple explanation of using OpenAI.

Read if:

  • You are interested in working of OpenAI with SvelteKit.

Introduction

In this blog post, we'll show you how to use OpenAI with SvelteKit. We'll start by creating a new SvelteKit app, and then we'll add OpenAI to it.

OpenAI is an artificial intelligence research and development company. Their goal is to "advance digital intelligence in the way that is most likely to benefit humanity as a whole".

SvelteKit is a new framework for building user interfaces. It's similar to React or Vue, but with some important differences. One of those differences is that SvelteKit uses a new approach to integration with artificial intelligence services like OpenAI.

  • First, let's create a new SvelteKit app. We'll use the create-svelte-app tool to do this:
npx create-svelte-app my-app
Enter fullscreen mode Exit fullscreen mode

Once the app is created, we'll need to install the openai package:

cd my-app && npm install openai
Enter fullscreen mode Exit fullscreen mode

Now that we have OpenAI installed, we can use it in our SvelteKit app. Let's create a new file called openai.js in our src directory:

import { OpenAI } from 'openai';
const openai = new OpenAI('your-api-key');
export default openai;
Enter fullscreen mode Exit fullscreen mode

In this file, we're creating a new OpenAI instance and exporting it. We'll need to provide our OpenAI API key in order to use the service.

Now that we have our OpenAI instance, we can use it in our components. Let's create a new component called MyComponent.svelte:

<script>
import openai from '../openai.js';
const myComponent = async () => { const response = await
openai.get('/v1/agents/default/environments/my-env/observations/action'); console.log(response); 
}; 
</script>
Enter fullscreen mode Exit fullscreen mode

In this component, we're importing our OpenAI instance and using it to make a request to the /v1/agents/default/environments/my-env/observations/action endpoint. This endpoint will return a JSON object with information about the current state of the environment.

We're also logging the response to the console. You can view the response in your browser's Developer Tools.

Now that we have a basic understanding of how to use OpenAI with SvelteKit, let's look at some more advanced features.

Advance Feature

One of the benefits of using OpenAI with SvelteKit is that you can take advantage of OpenAI's reinforcement learning capabilities. To do this, you'll need to create a new environment.

Environments are collections of agents, algorithms, and other resources that are used to train models. In our example, we'll create a new environment called my-env.

  • To create an environment, we'll use the OpenAI CLI. First, we'll need to install the openai-cli package:
npm install -g openai-cli
Enter fullscreen mode Exit fullscreen mode

Once the CLI is installed, we can use it to create our environment:

openai create --name my-env
Enter fullscreen mode Exit fullscreen mode

This command will create a new environment with the name my-env. We can now use this environment to train our models.

  • To train a model in our environment, we'll need to create a new file called train.js:
import { environment } from 'my-env';
const model = environment.createModel();
model.addLayer({ type: 'dense', units: 32, inputShape: [10] });
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
model.fit({ x: trainingData, y: trainingLabels, epochs: 10 });
Enter fullscreen mode Exit fullscreen mode

In this file, we're importing our environment and creating a new model. We're then adding a dense layer with 32 units and an input shape of [10].

We're compiling our model with the mean squared error loss function and the SGD optimizer. Finally, we're training our model on 10 epochs of training data.

Once our model is trained, we can save it to a file:

model.save('my-model.h5');
Enter fullscreen mode Exit fullscreen mode

We can then load our model in our SvelteKit app:

import { OpenAI } from 'openai';
const openai = new OpenAI('your-api-key');
const model = openai.loadModel('my-model.h5');
Enter fullscreen mode Exit fullscreen mode

We can now use ourtrained model to make predictions on new data.

OpenAI provides a wide range of capabilities that can be used to improve your SvelteKit app. In this blog post, we've only scratched the surface of what's possible. To learn more, be sure to check out the OpenAI documentation.

Note: This whole blog is written using OpenAI and below I'm gonna show you a code block that i wrote in sveltekit.

Example

<script>
    let text;
    let output;
    import { Configuration, OpenAIApi } from 'openai';

    const configuration = new Configuration({
        apiKey: 'USE YOUR API TOKEN'
    });
    const openai = new OpenAIApi(configuration);
    const completion = async () => {
        output = await openai.createCompletion({
            model: 'text-davinci-002',
            prompt: text,
            max_tokens: 2000,
            temperature: 0.6
        });
        output = output.data.choices[0].text;
    };
</script>

<input bind:value={text} /> <button on:click={completion}>Dekho</button>

{#if text}
    {text}
{/if}
<br />
{#if output}
    {output}
{/if}

Enter fullscreen mode Exit fullscreen mode
  • Using this code I asked AI to write a blog to integrate TailwindCSS in SvelteKit

-Output:

Output

  • If you're like me, you're probably excited about the potential of SvelteKit. And if you're also like me, you're probably equally excited about the potential of tailwindcss. So what could be better than combining the two? Here's a quick guide to integrating tailwindcss into your SvelteKit project.
  • Install the tailwindcss npm package: npm install --save-dev tailwindcss
  • Create a tailwind.config.js file in the root of your project: module.exports = { purge: [], theme: { extend: {}, }, variants: {}, plugins: [], }
  • Add the following lines to your package.json scripts:"scripts": { "build:css": "tailwind build src/tailwind.css -o public/build/tailwind.css", "watch:css": "tailwind build src/tailwind.css -o public/build/tailwind.css --watch" }
  • Create a src/tailwind.css file and import tailwindcss: @tailwind base; @tailwind components; @tailwind utilities;
  • Include the generated tailwind.css file in your main.svelte file: <style> @import "build/tailwind.css"; </style> And that's it! You should now have tailwindcss working in your SvelteKit project.

Maximum part of the post is written using OpenAI including Title of the post.

This is me writing for you. If you wanna ask or suggest anything please put it in comment.