Skip to content

Commit

Permalink
typescript refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
gannonh committed Jan 2, 2023
1 parent 65f9701 commit 1e0dfba
Show file tree
Hide file tree
Showing 9 changed files with 1,032 additions and 65 deletions.
15 changes: 7 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
{
"name": "openai-gpt3-node-starter",
"name": "astrolabs",
"version": "1.0.0",
"author": "Gannon Hall",
"license": "MIT",
"private": false,
"description": "OpenAI GPT-3 Node Starter Project",

"license": "Commercial",
"private": true,
"description": "OpenAI API stuff",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"highlight.js": "^11.7.0",
"next": "^12.1.6",
"next": "^13.1.1",
"openai": "^3.0.0",
"react": "17.0.2",
"react-dom": "17.0.2"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.11.18",
Expand Down
6 changes: 0 additions & 6 deletions pages/_app.js

This file was deleted.

11 changes: 11 additions & 0 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { AppProps } from 'next/app';
import React from 'react';

import "./styles/globals.css";


function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}

export default MyApp;
4 changes: 2 additions & 2 deletions pages/api/generate.js → pages/api/review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ const openai = new OpenAIApi(configuration);
export default async function (req, res) {
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: generatePrompt(req.body.animal),
prompt: reviewPrompt(req.body.product),
max_tokens: 2000,
temperature: 0.6,
});
res.status(200).json({ result: completion.data.choices[0].text });
}

function generatePrompt(productName) {
function reviewPrompt(productName) {
return `Product name: KRK ROKIT 5 G4 5 inch Powered Studio Monitors
Review:
## KRK ROKIT 5 G4 5 inch Powered Studio Monitors
Expand Down
34 changes: 34 additions & 0 deletions pages/api/short-story.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

export default async function (req, res) {
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: reviewPrompt(req.body.product),
max_tokens: 150,
temperature: 0.8,
top_p: 1.0,
frequency_penalty: 0.5,
presence_penalty: 0.0
});
res.status(200).json({ result: completion.data.choices[0].text });
}

function reviewPrompt(productName) {
return `Topic: Breakfast
Two-Sentence Horror Story: He always stops crying when I pour the milk on his cereal. I just have to remember not to let him see his face on the carton.
Topic: ${productName}
Two-Sentence Horror Story:`;
}







47 changes: 47 additions & 0 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { NextPage } from "next";
import Head from "next/head";
import Link from "next/link";
import React from "react";

const HomePage: NextPage = () => {
return (
<>
<Head>
<title>OpenAI API Starter</title>
<meta name="description" content="" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="flex min-h-screen flex-col items-center justify-center bg-gradient-to-b from-[#2e026d] to-[#15162c]">
<div className="container flex flex-col items-center justify-center gap-12 px-4 py-16 ">
<h1 className="text-5xl font-extrabold tracking-tight text-white sm:text-[5rem]">
Astro <span className="text-[hsl(280,100%,70%)]">AI</span>
</h1>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:gap-8">
<Link
className="flex max-w-xs flex-col gap-4 rounded-xl bg-white/10 p-4 text-white hover:bg-white/20"
href="/review"
>
<h3 className="text-2xl font-bold">Product Reviews →</h3>
<div className="text-lg">
Generate purpose-built product reviews.
</div>
</Link>
<Link
className="flex max-w-xs flex-col gap-4 rounded-xl bg-white/10 p-4 text-white hover:bg-white/20"
href="/short-story"

>
<h3 className="text-2xl font-bold">Short Story →</h3>
<div className="text-lg">
Create a 2-sentence horror story.
</div>
</Link>
</div>

</div>
</main>
</>
);
};

export default HomePage;
149 changes: 149 additions & 0 deletions pages/review.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import Head from "next/head";
import { useState, useRef, useEffect } from "react";
import hljs from "highlight.js";
import React from "react";

export default function Review() {
// Create a ref for the div element
const textDivRef = useRef<HTMLDivElement>(null);
const [productInput, setProductInput] = useState("");
const [result, setResult] = useState(() => "");
const [isLoading, setIsLoading] = useState(false);


// Add a click event listener to the copy icon that copies the text in the div to the clipboard when clicked
useEffect(() => {
const copyIcon = document.querySelector(".copy-icon");
if (!copyIcon) return;
copyIcon.addEventListener("click", () => {
const textDiv = textDivRef.current;

let text;
if (textDivRef.current) {
text = textDivRef.current.textContent;
}

// Create a hidden textarea element
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);

// Select the text in the textarea
textArea.select();

// Copy the text to the clipboard
document.execCommand("copy");

// Remove the textarea element
document.body.removeChild(textArea);
});
}, []); // Run this only once


async function onSubmit(event) {
event.preventDefault();
setIsLoading(true);
const response = await fetch("/api/review", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ product: productInput }),
});
const data = await response.json();
console.log("data", data);
console.log("data.result", data.result);

let rawResult = data.result;

console.log("rawResult");

const hljsResult = hljs.highlightAuto(rawResult).value;

// set result to the highlighted code. Address this error: Argument of type 'string' is not assignable to parameter of type '(prevState: undefined) => undefined'.ts(2345)
setResult(hljsResult);

setProductInput("");
setIsLoading(false);
}

return (
<div>
<Head>
<title>OpenAI API Starter - Review generator</title>
<meta name="description" content="" />
<link rel="icon" href="/favicon.ico" />
</Head>

<main
className="flex flex-col
items-center justify-center m-20"
>
<h3 className="text-slate-900 text-xl mb-3">
Product Review Generator
</h3>
<p className="text-slate-700 text-lg mb-3">
Open AI starter app to generate product reviews
</p>
<form onSubmit={onSubmit}>
<input
className="text-sm text-gray-base w-full
mr-3 py-5 px-4 h-2 border
border-gray-200 rounded mb-2"

type="text"
name="product"
placeholder="Enter a product name"
value={productInput}
onChange={(e) => setProductInput(e.target.value)}
/>

<button
className="text-sm w-full bg-fuchsia-600 h-7 text-white
rounded-2xl mb-10"
type="submit"
>
Generate article
</button>
</form>
{isLoading ? (
<p>Loading... be patient.. may take 30s+</p>
) : result ? (
<div className="relative w-2/4 ">
<div
ref={textDivRef}
className="rounded-md border-spacing-2 border-slate-900 bg-slate-100 break-words max-w-500 overflow-x-auto "
>
<pre className="">
<code
className=""
dangerouslySetInnerHTML={{ __html: result }}
/>
</pre>
</div>
<div className="absolute top-0 right-0 mt-2 mr-2 cursor-pointer copy-icon">
<svg
xmlns="http://www.w3.org/2000/svg"
className="icon icon-tabler icon-tabler-copy"
width="24"
height="24"
viewBox="0 0 24 24"
strokeWidth="2"
stroke="currentColor"
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<rect x="8" y="8" width="12" height="12" rx="2"></rect>
<path d="M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"></path>
</svg>
</div>
</div>
) : null}
</main>
</div>
);
}


Loading

0 comments on commit 1e0dfba

Please sign in to comment.