Python-based chatbot that uses OpenAI’s API and exposes it as a REST API using Flask

Python-based chatbot that uses OpenAI’s API and exposes it as a REST API using Flask

Here’s a step-by-step guide to creating a Python-based chatbot that uses OpenAI’s API and exposes it as a REST API using Flask:

  1. Install the required packages:

a. Install Flask: pip install Flask

b. Install OpenAI's Python package: pip install openai

2. Create a new Python file (e.g., app.py) and import the required libraries:

import os
import openai
from flask import Flask, request, jsonify

3. Configure the OpenAI API key:

openai.api_key = os.environ.get("OPENAI_API_KEY")

Set the OPENAI_API_KEY environment variable in your system or replace os.environ.get("OPENAI_API_KEY") with your API key as a string (e.g., "your_api_key").

4. Initialize Flask and create a route to handle chat requests:

app = Flask(__name__)

@app.route('/chat', methods=['POST'])
def chat():
# Extract user message from the request
user_message = request.json['message']

# Call OpenAI API with user message
response = openai.Completion.create(
engine="davinci-codex",
prompt=f"User: {user_message}\nAI:",
temperature=0.7,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\n"]
)

# Extract the AI's response
ai_message = response.choices[0].text.strip()

# Return the AI's response as JSON
return jsonify({"message": ai_message})

if __name__ == '__main__':
app.run(debug=True)

5. Run the Flask app: python app.py

Now you have a Python-based chatbot that uses OpenAI’s API and exposes it as a REST API using Flask. To connect this chatbot to Azure Bot Service, follow these steps:

  1. Create an Azure Bot . Choose the Node.js SDK language and the “Echo Bot” template.

  2. In the Azure Bot resource, navigate to “Channels” and add the “Web Chat” channel. Make a note of the “Secret keys” for the Web Chat channel; you’ll need them later.

  3. Create a simple HTML page to host the Web Chat control and connect it to your Flask chatbot:

<html>
<head>
<title>Python Chatbot with Azure Bot Service</title>
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
</head>
<body>
<div id="webchat" role="main"></div>
<script> const styleOptions = {
botAvatarInitials: 'Bot',
userAvatarInitials: 'You'
};

const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
// Call the Flask chatbot API
fetch('http://localhost:5000/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: action.payload.activity.text })
})
.then(response => response.json())
.then(data => {
// Create a response activity with the chatbot's message
const responseActivity = {
type: 'message',
text: data.message,
from: {
role: 'bot'
},
channelId: 'webchat'
};

// Send the response activity to the Web Chat control
dispatch({
type: 'DIRECT_LINE/INCOMING_ACTIVITY',
payload: {
activity: responseActivity
}
});
});

return next(action);
} else {
return next(action);
}
});

window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token: 'YOUR_WEB_CHAT_SECRET_KEY' }),
store,
styleOptions
},
document.getElementById('webchat')
); </script>
</body>
</html>

Replace 'YOUR_WEB_CHAT_SECRET_KEY' with one of the secret keys you obtained from the Azure Bot Service Web Chat channel.

Now you have an HTML page that hosts the Web Chat control, which connects to your Flask chatbot. You can serve this HTML page using any web server, such as Python’s http.server or Node.js' http-server.

Please note that this solution is not optimal for production use, as it directly uses the Web Chat secret key in the client-side code, and the Flask server runs in debug mode. For production use, you should consider securing the Flask API with authentication and serve the HTML page using a secure web server. Additionally, you might need to update the Flask server URL in the HTML code if you deploy it to a different location.