How about using assistant API and turning it into an iframe on your web page. Example code generated with GPT as reference for you. This is not using assistant API, but serves the iframe demo concept.
With this chat widget as part of your base.html and a bit more javascript, one could detect which page it is activated from and could navigate the conversation to that context.
Flask backend:
# backend.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import openai
app = Flask(__name__)
CORS(app) # Enable CORS
openai.api_key = 'your-api-key' # Replace with your OpenAI API key
@app.route('/ask', methods=['POST'])
def ask():
data = request.json
response = openai.Completion.create(
engine="text-davinci-003",
prompt=data['prompt'],
max_tokens=150
)
return jsonify(response)
if __name__ == '__main__':
app.run(port=5000) # Run the Flask app on port 5000
html page:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Assistant</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
iframe {
width: 100%;
height: 500px;
border: none;
}
</style>
</head>
<body>
<iframe id="ai_frame" sandbox="allow-scripts allow-same-origin"></iframe>
<form onsubmit="sendMessageToAI(); return false;">
<input type="text" id="prompt" name="prompt" required>
<input type="submit" value="Ask AI">
</form>
<script>
function sendMessageToAI() {
var prompt = document.getElementById('prompt').value;
$.ajax({
url: 'http://localhost:5000/ask', // Point to the backend endpoint
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ prompt: prompt }),
success: function(response) {
// Write the AI's response to the iframe
var iframeDocument = document.getElementById('ai_frame').contentDocument;
iframeDocument.open();
iframeDocument.write('<p>' + response.choices[0].text + '</p>');
iframeDocument.close();
},
error: function(xhr, status, error) {
// Handle error
console.error("Error: " + status + " - " + error);
}
});
}
</script>
</body>
</html>