import { Hono } from "npm:hono";
import { cors } from 'npm:hono/cors';
import { stream } from "https://deno.land/x/hono@v4.3.11/helper.ts";
import { OpenAI } from "npm:openai";
const app = new Hono();
const openai = new OpenAI();
app.use('*', cors({
origin: '*',
allowMethods: ['GET'],
allowHeaders: ['Content-Type'],
}))
app.use('/chat, /chat/*', async (c, next) => {
c.header('Content-Type', 'text/event-stream');
c.header('Cache-Control', 'no-cache');
c.header('Connection', 'keep-alive');
await next();
});
const SOURCE_URL = "";
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>OpenAI Streaming Example</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
#output {
white-space: pre-wrap;
border: 1px solid #ccc;
padding: 10px;
min-height: 100px;
}
</style>
</head>
<body>
<h1>OpenAI Streaming Example</h1>
<label for="prompt">Prompt:</label>
<input type="text" id="prompt" value="tell me a joke" />
<button onclick="getResponse()">Submit</button>
<div id="output"></div>
<script>
const outputDiv = document.getElementById('output');
function getResponse() {
const prompt = document.getElementById('prompt').value;
const url = "${SOURCE_URL}/chat?p=" + encodeURIComponent(prompt);
outputDiv.textContent = 'Loading...';
const eventSource = new EventSource(url);
let isFirstChunk = true;
eventSource.onmessage = (event) => {
if (event.data === "[DONE]") {
eventSource.close();
} else {
const data = JSON.parse(event.data);
if (data.error) {
outputDiv.textContent = "Error: " + data.error;
} else {
if (isFirstChunk) {
outputDiv.textContent = data.token;
isFirstChunk = false;
} else {
outputDiv.textContent += data.token;
}
}
}
};
eventSource.onerror = (error) => {
console.error('EventSource error:', error);
outputDiv.textContent = 'Error occurred.';
};
eventSource.addEventListener('close', () => {
console.log('Connection closed.');
});
}
</script>
</body>
</html>
`;
const htmlContent2 = `
<!DOCTYPE html>
<html>