To build a website that can ask questions and answer them using OpenAI, we need to follow these steps:

  1. Install OpenAI API: Follow the instructions on the OpenAI website to install the OpenAI API.

  2. Create an HTML file: Create an HTML file named 'index.html' to serve as the front-end of our website.

  3. Create a Python script: Create a Python script named 'app.py' to handle requests from the front-end, send them to the OpenAI API, and return the response.

  4. Create a CSS file: Create a CSS file named 'style.css' to style the HTML page.

  5. Set up the Apache server: Set up the Apache server on your machine to host the website.

Here's a simple beginner code to get started:

index.html:

<!DOCTYPE html>
<html>
<head>
	<title>OpenAI Q&A</title>
	<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
	<h1>OpenAI Q&A</h1>
	<form>
		<label for='question'>Question:</label>
		<input type='text' id='question' name='question'><br><br>
		<label for='answer'>Answer:</label>
		<input type='text' id='answer' name='answer' readonly><br><br>
		<input type='button' value='Ask' onclick='askQuestion()'>
	</form>
	<script src='app.js'></script>
</body>
</html>

style.css:

body {
	background-color: #f2f2f2;
	font-family: Arial, sans-serif;
}

h1 {
	text-align: center;
}

form {
	margin: 0 auto;
	width: 50%;
}

label {
	display: block;
	margin-top: 20px;
}

input[type='text'] {
	width: 100%;
	padding: 12px 20px;
	margin: 8px 0;
	box-sizing: border-box;
	border: none;
	border-radius: 4px;
	background-color: #fff;
}

input[type='button'] {
	background-color: #4CAF50;
	color: white;
	padding: 14px 20px;
	margin: 8px 0;
	border: none;
	border-radius: 4px;
	cursor: pointer;
	width: 100%;
}

input[type='button']:hover {
	background-color: #45a049;
}

app.py:

import openai

openai.api_key = 'YOUR_API_KEY'

def get_answer(question):
    response = openai.Completion.create(
        engine='davinci',
        prompt=f'Q: {question}
A:',
        temperature=0.5,
        max_tokens=1024,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    answer = response.choices[0].text.strip()
    return answer

from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs
import json

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            with open('index.html', 'rb') as f:
                self.wfile.write(f.read())
        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'404 Not Found')

    def do_POST(self):
        if self.path == '/ask':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = parse_qs(post_data.decode('utf-8'))
            question = data['question'][0]
            answer = get_answer(question)
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({'answer': answer}).encode('utf-8'))
        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'404 Not Found')

if __name__ == '__main__':
    from http.server import HTTPServer
    server = HTTPServer(('localhost', 8080), Handler)
    print('Starting server...')
    server.serve_forever()

This Python script creates a simple HTTP server that listens for GET and POST requests. When the user submits a question, the script sends it to the OpenAI API and returns the answer.

app.js:

function askQuestion() {
	var question = document.getElementById('question').value;
	if (question) {
		var xhr = new XMLHttpRequest();
		xhr.open('POST', '/ask', true);
		xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4 && xhr.status === 200) {
				var data = JSON.parse(xhr.responseText);
				document.getElementById('answer').value = data.answer;
			}
		};
		xhr.send('question=' + question);
	}
}

This JavaScript code handles the form submission and sends an AJAX request to our Python script to get the answer.

To install OpenAI API, follow the instructions on the OpenAI website: https://beta.openai.com/docs/api-reference/authentication#authentication

To set up the Apache server, follow the instructions on the Apache website: https://httpd.apache.org/docs/2.4/install.html

To run the Python script, open the terminal in the directory where the script is saved and run the command python app.py. This will start the HTTP server and you can access the website by going to http://localhost:8080 in your web browser.

Build a Question Answering Website with OpenAI, HTML, Python, and Apache Server

原文地址: https://www.cveoy.top/t/topic/lBQv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录