1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/** @jsx jsx */
import { Hono } from "npm:hono@3";
import { jsx } from "npm:hono@3/jsx";
import { cors } from 'npm:hono/cors';
import { OpenAI } from "npm:openai";
const app = new Hono();
const openai = new OpenAI();
app.use('*', cors({
origin: '*',
allowMethods: ['GET', 'POST'],
allowHeaders: ['Content-Type'],
}));
// Server-side rendering
app.get("/", async (c) => {
const html = (
<html>
<head>
<title>OpenAI Prompt Example</title>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="container mx-auto py-8">
<h1 class="text-4xl font-bold mb-4">OpenAI Prompt Example</h1>
<form action="/prompt" method="GET">
<label for="prompt" class="block mb-2 font-bold">Prompt:</label>
<input type="text" id="prompt" name="prompt" value="Say hello in a creative way" class="border border-gray-300 rounded px-4 py-2 mb-4 w-full" />
<button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
Submit
</button>
</form>
<div class="mt-4">
<h2 class="text-xl font-bold mb-2">Response:</h2>
<div id="output" class="border border-gray-300 rounded p-4">
{c.req.query('response') || ''}
</div>
</div>
</div>
</body>
</html>
);
return c.html(html);
});
app.get('/prompt', async (c) => {
const prompt = c.req.query('prompt');
try {
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: prompt }],
max_tokens: 100,
});
const generatedResponse = response.choices[0].message.content;
return c.redirect(`/?response=${encodeURIComponent(generatedResponse)}`);
} catch (error) {
console.error('OpenAI API error:', error);
return c.redirect('/?response=Error%20occurred.');
}
});
export default app.fetch;
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.