We soft launched a AI-heavy website. It takes a user's prompt and returns pre-written content that most closely matches the user's prompt. The AI is the router. The AI also responds with something short to introduce the user to the content.
As AI becomes more and more ubiquitous, you will likely find use cases where you want to include AI. Unfortunately, this is not as simple as sending a fetch request to the OpenAI API. But, with a bit of help from a Cloudflare worker, you can add AI to your website. Let's walk through how we accomplished this.
Prerequisites
- OpenAI API Key: Sign up for an OpenAI account and get an API key from OpenAI.
- Cloudflare Account: Sign up for a Cloudflare account and set up Workers if you haven't already.
Step 1: Set Up Cloudflare Worker
- Create a new Worker
- Go to the Cloudflare dashboard.
- Navigate to the Workers section.
- Click on Create a Worker.
- Configure the Worker
- Replace the default script with the following code:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const { prompt } = await request.json()
const response = await fetch('https://api.openai.com/v1/completions
', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
},
body: JSON.stringify({
model: 'text-davinci-003', // or your preferred model
prompt: prompt,
max_tokens: 150
})
})
const data = await response.json()
const aiResponse = data.choices[0].text.trim()
return new Response(JSON.stringify({ response: aiResponse }), {
headers: { 'Content-Type': 'application/json' }
})
}
- Replace
OPENAI_API_KEY
with your actual OpenAI API key. - Save and deploy your Worker.
Step 2: Create the Webpage
- HTML Structure: Create a simple HTML page with an input for the user prompt and a display area for the AI response.
- JavaScript Code:
- Add the following code to your Slater file:
function getAIResponse() {
const prompt = document.getElementById('prompt').value;
fetch('https://your-worker-url.workers.dev
', { // Replace with your Worker URL
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt })
})
.then(response => response.json())
.then(data => {
document.getElementById('response').innerText = data.response;
})
.catch(error => {
console.error('Error:', error);
document.getElementById('response').innerText = 'There was an error processing your request.';
});
}
- Replace
'
https://your-worker-url.workers.dev'
with the URL of your deployed Cloudflare Worker.
This is a quick summary of how we are using a Cloudflare worker to allow us to communicate with the OpenAI API. I'm providing minimal code to make it easy to integrate AI functionality into your projects. If you have any questions, I'd be happy to answer them.
Please share any AI-enabled experiences that your create.