Skip to content

Instantly share code, notes, and snippets.

@trevorstenson
Created February 20, 2023 22:21
Show Gist options
  • Save trevorstenson/21510b2fcd00ad41188860174c288c61 to your computer and use it in GitHub Desktop.
Save trevorstenson/21510b2fcd00ad41188860174c288c61 to your computer and use it in GitHub Desktop.
A service worker that intercepts fetch events, and generates HTML pages on the fly from GPT-3 to return back to the client application.
const API_KEY = "<OPEN_AI_API_KEY_HERE>";
async function openai_request(prompt) {
let engine = "text-davinci-003";
const response = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + API_KEY,
},
body: JSON.stringify({
model: engine,
prompt: prompt,
temperature: 0,
max_tokens: 1000,
}),
});
if (!response.ok) {
console.error(
"HTTP ERROR: " + response.status + "\n" + response.statusText
);
return "error, not ok";
} else {
const data = await response.json();
if (data.choices && data.choices.length > 0) {
return data.choices[0].text;
}
return data;
}
}
self.addEventListener("install", (event) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener("activate", (event) => {
event.waitUntil(self.clients.claim());
});
const should_intercept = (url) => {
return url.origin === self.location.origin && url.pathname !== "/";
};
const make_prompt = (url) => {
let prompt = url.pathname.replace(/\//, "").split(/-|_/).join(" ");
if (url.search !== "") {
const query_args = new URLSearchParams(url.search).values();
let final_values = [];
for (const value of query_args) {
final_values.push(value);
}
if (final_values.length > 0) {
prompt = `${prompt}:\n${final_values.join(", ")}`;
}
}
prompt = `
Create a well formed webpage using HTML, CSS, and JavaScript that contains the output of the following prompt:\n${prompt}
`;
return prompt;
};
const fetch_interceptor = (event) => {
const url = new URL(event.request.url);
if (!should_intercept(url)) return;
const prompt = make_prompt(url);
const open_ai_req = new Promise((resolve) => {
openai_request(prompt).then((data) => {
resolve(
new Response(data, {
headers: {
"Content-Type": "text/html",
},
})
);
});
});
event.respondWith(open_ai_req);
};
self.addEventListener("fetch", fetch_interceptor);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment