Skip to content

Commit

Permalink
Upload code
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyentuansi committed Feb 8, 2023
1 parent 3b54fbf commit 35c57d5
Show file tree
Hide file tree
Showing 9 changed files with 309 additions and 5 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
OPENAI_API_KEY=
43 changes: 41 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,41 @@
# openai-quickstart-sveltekit

# OpenAI API Quickstart - SvelteKit example

This is an example pet name generator app used in the OpenAI API. It uses the [SvelteKit](https://kit.svelte.dev/) framework with [Pico](https://picocss.com/). Check out the tutorial or follow the instructions below to get set up.

## Setup

1. If you don’t have Node.js installed, [install it from here](https://nodejs.org/en/) (Node.js version >= 14.6.0 required)

2. Clone this repository

3. Navigate into the project directory

```bash
$ cd openai-quickstart-sveltekit
```

4. Install the requirements

```bash
$ npm install
```

5. Make a copy of the example environment variables file

On Linux systems:
```bash
$ cp .env.example .env
```
On Windows:
```powershell
$ copy .env.example .env
```
6. Add your [API key](https://beta.openai.com/account/api-keys) to the newly created `.env` file

7. Run the app

```bash
$ npm run dev
```

You should now be able to access the app at [http://127.0.0.1:5173](http://127.0.0.1:5173)! For the full context for other examples, check out the [tutorial](https://beta.openai.com/docs/quickstart).
101 changes: 101 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,9 @@
"vite": "^4.0.0",
"vitest": "^0.25.3"
},
"type": "module"
"type": "module",
"dependencies": {
"@picocss/pico": "^1.5.7",
"openai": "^3.1.0"
}
}
3 changes: 3 additions & 0 deletions src/app.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:root {
--primary: aqua;
}
7 changes: 7 additions & 0 deletions src/app.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* custom version */

// theme
@import '@picocss/pico/scss/themes/default';
// import components you need
@import '@picocss/pico/scss/content/button';
@import '@picocss/pico/scss/content/form';
5 changes: 5 additions & 0 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script lang="ts">
import '@picocss/pico';
</script>

<slot />
75 changes: 73 additions & 2 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,2 +1,73 @@
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
<script lang="ts">
let promptInput: any;
let temperatureInput = 0.6;
let result = '';
let loading = false;
async function onSubmit(event) {
event.preventDefault();
loading = true;
try {
const response = await fetch('/api/prompt', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: promptInput, temperature: temperatureInput })
});
const data = await response.json();
if (response.status !== 200) {
throw data.error || new Error(`Request failed with status ${response.status}`);
} else {
loading = false;
}
result = data.result;
} catch (error) {
// Consider implementing your own error handling logic here
console.error(error);
}
}
</script>

<body>
<main class="container">
<article>
<h1>Askme</h1>
<form on:submit={onSubmit}>
<input
type="search"
name="prompt"
bind:value={promptInput}
placeholder="What is Mixcore CMS?"
required
/>
<small>Or you can ask anything you want!</small>
<!-- Range slider -->
<label for="range">
Temperature : <em data-tooltip="Lower = more accurate; higher = more diverse."
>{temperatureInput}</em
>
<input
type="range"
min="0"
max="1"
step="0.1"
name="temperature"
bind:value={temperatureInput}
/>
</label>
<!-- Button -->
<button type="submit" aria-busy={loading}>Submit</button>
</form>
<article class="result">{result}</article>
</article>
</main>
</body>

<style>
main,
result {
padding-top: 0;
padding-bottom: 0;
}
</style>
73 changes: 73 additions & 0 deletions src/routes/api/prompt/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { env } from '$env/dynamic/private';
import { Configuration, OpenAIApi } from 'openai';
import { error } from '@sveltejs/kit';

const configuration = new Configuration({
apiKey: env.OPENAI_API_KEY
});

const openai = new OpenAIApi(configuration);
// console.log(openai);

/** @type {import('./$types').RequestHandler} */
// export function GET({ url }) {
// const min = Number(url.searchParams.get('min') ?? '0');
// const max = Number(url.searchParams.get('max') ?? '1');

// const d = max - min;

// if (isNaN(d) || d < 0) {
// throw error(400, 'min and max must be numbers, and min must be less than max');
// }

// const random = min + Math.random() * d;

// return new Response(String(random));
// }

import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';

export const POST = (async ({ request }) => {
if (!configuration.apiKey) {
return json({
error: {
status: 500,
message: 'OpenAI API key not configured, please follow instructions in README.md'
}
});
}
const response = await request.json();
if (!response) {
return json({
error: {
status: 400,
message: 'Please enter a valid prompt'
}
});
}

try {
const completion = await openai.createCompletion({
model: 'text-davinci-003',
prompt: response.prompt,
temperature: response.temperature,
max_tokens: 100
});

return json({ code: 200, result: completion.data.choices[0].text });
} catch (error) {
// Consider adjusting the error handling logic for your use case
if (error.response) {
console.error(error.response.status, error.response.data);
} else {
console.error(`Error with OpenAI API request: ${error.message}`);
return json({
error: {
code: 500,
message: 'An error occurred during your request.'
}
});
}
}
}) satisfies RequestHandler;

0 comments on commit 35c57d5

Please sign in to comment.