This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
I am trying to create an ai chatbot that is linked to my openai api, and the responses work in my cdm, but I cannot see what the issue is in trying to show the ai response on my html page. I used ai to try and fix this, but I couldnt get anywhere. If anyone can help explain what im doing here I would appreciate it. Here is the code below:
# test.py
from flask import Flask, request, jsonify
import openai
app = Flask(__name__)
openai.api_key = 'deletedformyprivacy'
@app.route('/chat', methods=['POST'])
def chat():
  user_message = request.json.get('message')
  if not user_message:
    return jsonify({'error': 'No message provided'}), 400
  try:
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[{"role": "user", "content": user_message}],
      max_tokens=50
    )
    ai_response = response.choices[0].message['content'].strip()
    return jsonify({'response': ai_response})
  except Exception as e:
    return jsonify({'error': str(e)}), 500
@app.route('/', methods=['GET'])
def index():
  return jsonify({'message': 'Welcome to the AI Chatbot API!'})
if __name__ == '__main__':
  app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI Chatbot</title>
</head>
<body>
  <h1>Chat with AI</h1>
  <form id="chatForm">
    <label for="userMessage">Your Message:</label>
    <input type="text" id="userMessage" name="userMessage" required>
    <button type="submit">Send</button>
  </form>
  <!-- Section to display the AI's response -->
  <div id="response">
    <h2>AI Response:</h2>
    <p id="responseMessage"></p>
  </div>
  <script>
    document.getElementById('chatForm').addEventListener('submit', function(event) {
      event.preventDefault();
     Â
      var userMessage = document.getElementById('userMessage').value;
      var responseDiv = document.getElementById('responseMessage');
      fetch('http://127.0.0.1:5000/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ message: userMessage })
      })
      .then(response => response.json())
      .then(data => {
        responseDiv.innerHTML = data.response;
      })
      .catch(error => {
        console.error('Error:', error);
        responseDiv.innerHTML = 'An error occurred.';
      });
    });
  </script>
</body>
</html>
Many thanks in advance
A couple things you can try that might help you get closer to solving the problem:
Figure out if Flask is sending the response correctly. You can try making a
curl
request to the server to see what it’s returning. You can also print the response before sending it to ensure you’re sending the right value.In your browser, open your dev tools/console and go to the Network tab. Here you should be able to search for the fetch to
/chat
and look to see what the client is sending and the server is returning.
This might help you get a better idea of where things are going wrong. Feel free to follow up or send a DM if you need to.
Post Details
- Posted
- 5 months ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/flask/comme...