Lesson 3: Python Structure: app.py and ai_engine.py
Let's start building our chatbot!
We expect our application to answer a question like this:
Do you have any cars newer than 2018?
We expect an answer like this:
Yes, we have three cars that are newer than 2018. Here are their details:
- A 2020 Volkswagen Passat, which is a hatchback with FWD drivetrain.
- A 2023 Volvo S90, which is a sedan with AWD drivetrain.
- A 2023 Mercedes C63 AMG, which is a sedan with RWD drivetrain.
We will begin by creating the base application that communicates with OpenAI and does the following:
- Connects to the database to get the table names and their columns
- Asks ChatGPT to generate a query based on the question and the database structure
- Queries the database to get the results OpenAI chat generated
- Asks ChatGPT to generate a response based on the question, the query, and the query output
Let's start building!
Requirements
For this project, we will be using these libraries:
pip install python-dotenvpip install flaskpip install mysql-connector-pythonpip install openaipip install waitresspip install flask-cors
We will build the following part of the application:
App Structure: Two Main Python Files
Our Python script will consist of three .py
files:
-
app.py
: the main entry point for our application -
ai_engine.py
: the actual AI logic to ask GPT and get responses
For now, let's hardcode the result of the AI call but still build all the structure of these files.
Let's start by creating ai_engine.py
with the generate_response()
function and hardcoded answer, for now:
ai_engine.py
def generate_response(question): return "I'm sorry, I don't know the answer to that question. Please try again."
Finally, let's create the main entry point app.py
file in our root folder that calls our AI engine:
app.py
import ai_engine question = "What cars are available?" print(ai_engine.generate_response(question))
Now, if we run our app.py
file, we should see the response from our AI engine:
"I'm sorry, I don't know the answer to that question. Please try again."
Good, no errors. Now, let's build the actual logic inside those files.
AI Engine: Building SQL Query with OpenAI API
The next step is to generate a MySQL query from the user's question in the chat.
We create a separate method, get_query()
, to form a request to the OpenAI, with a few more methods inside.
ai_engine.py
def get_query(question): prompt = build_prompt(question) query = query_open_ai(prompt) query = query.strip() query_safety_check(query) return query def generate_response(question): query = get_query(question) print(query) return "I'm sorry, I don't know the answer to that question. Please try again."
Now, we need to build our prompt in the build_prompt()
method and query OpenAI in the query_open_ai()
method. These actions will be covered in the next lesson.
- Intro: Structure and Preparation
- AI Engine and Main Python Script
- Front-end JavaScript Widget
- Bonus
No comments or questions yet...