Useful Links:
ℹ️: OpenAI API Reference Documentation
ℹ️: OpenAI API Playground Examples
ℹ️: OpenAI API Waitlist Link
ℹ️: Find Project Code Here!
Table of Contents
- Introduction
- Prerequisites
- Overview of the Project
- Setting Up the Project Environment
- Analyzing the Code
- Testing Our Finished Project
- Wrapping Up
Introduction
Have you ever wanted to create a new application, but you didn’t know where to start? Or maybe you wanted to add a new feature to an existing application, but you didn’t have the time or the skills to write the code. If so, then you’re in luck! In this tutorial, we’re going to show you how to build a web application that can transform English tasks into Python code.
With recent advancements in artificial intelligence and natural language processing, this dream is becoming a reality. In this tutorial, we will explore the exciting prospect of building a web application that harnesses the power of OpenAI’s GPT-3.5-Turbo language model and Flask, a popular Python web framework, to achieve the transformation of English tasks into Python code.
Prerequisites
Before we begin, make sure you have the following set up:
OpenAI API access and API key (OpenAI API Waitlist Link)
Python installed on your machine
Flask installed in your Python environment
Overview of the Project
The project we are building is a web application that allows users to input English tasks and receive the corresponding Python code as output. The application utilizes the OpenAI Chat API with the GPT-3.5-Turbo model for language translation. Flask is used as the web framework to handle user requests and render the output.
Here’s how the project works:
- The user accesses the application through a web browser.
- The application presents a form where the user can enter an OpenAI API key and a list of tasks in English, separated by commas.
- When the user submits the form, the Flask application handles the POST request and retrieves the API key and tasks from the form data.
- The application sets the OpenAI API key and formats the tasks into a prompt for the language model.
- The OpenAI Chat API is called with the prompt and other parameters to generate the Python code.
- The generated code is extracted from the API response and passed to the HTML template for rendering.
- The HTML template displays the generated code to the user.
Now, let’s dive into the code and analyze its important parts to understand how everything works together.
Setting Up the Project Environment
Install Conda if you haven’t already.
Open a terminal or command prompt.
Create a new Conda environment and activate it:
bash
conda create --name my_project_envconda activate my_project_env
Create a root folder for your project.
Inside the root folder, create a template folder that will contain the HTML template file home.html.
Place the main Python file (text2python.py in our example) in the root folder.
Installing Required Modules
Install the necessary modules by running the following command in the terminal:
bash
pip install openai flask markdown
openai
: This module allows the app to interact with the OpenAI API. It is used to set the OpenAI API key, make requests to the Chat API, and receive responses containing the generated Python code.flask
: This module is a web framework used for handling user requests and rendering output in the app. It provides functionalities for routing, request handling, and rendering HTML templates.markdown
: This module is used to convert the generated Python code into Markdown format. It enables proper formatting and syntax highlighting of the code when rendering it in the HTML template.
Ensure that the modules are installed within the previously created Conda environment.
By following these steps and organizing your project structure as mentioned, you’ll have everything set up to run the project successfully.
Analyzing the Code
Flask Application
The Flask application is the core component of our project. It handles the routing and request handling logic. Here’s an overview of the relevant parts of the code:
python
import openaifrom flask import Flask, request, render_templatefrom markdown import markdownapp = Flask(__name__)@app.route('/', methods=['GET', 'POST'])def home():if request.method == 'POST':# Handle POST requestelse:# Render the template for GET request
- we import the necessary modules:
openai
,flask
, andmarkdown
. - The Flask application is created using the Flask(
__name__
) constructor. - The / route is defined with the @app.route(’/’, methods=[‘GET’, ‘POST’]) decorator, indicating that this route can handle both GET and POST requests.
- Inside the home function, the request method is checked using request.method to determine if it’s a GET or POST request.
- If it’s a POST request, the code handles the form data submitted by the user.
- If it’s a GET request, the template is rendered and displayed to the user.
POST Request Handling
When the user submits the form with the API key and tasks, the Flask application handles the POST request and proceeds with generating the Python code. Here’s the relevant part of the code:
python
api_key = request.form.get('api_key')tasks = request.form.get('tasks').split(',')openai.api_key = api_keytask_str = "\n".join([f"{idx+1}. {task.strip()}" for idx, task in enumerate(tasks)])prompt = f""""\nYour task is to write Python code to: \n{task_str}\n""""completion = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role": "system", "content": "You are a helpful assistant that translates plain English into Python code."},{"role": "user", "content": prompt}],temperature=0,max_tokens=300,top_p=1,frequency_penalty=0,presence_penalty=0)result = completion.choices[0].message['content']return render_template('home.html', result=result)
Retrieve the API key and tasks from the form data using
request.form.get('api_key')
andrequest.form.get('tasks').split(',')
, respectively.Set the OpenAI API key using
openai.api_key = api_key
.Format the tasks into a string called
task_str
which will be used as a prompt for the language model. Enumerate each task and format it with its index and a bullet point.Construct the prompt by wrapping
task_str
with triple double-quotes, allowing multi-line strings.Call the OpenAI Chat API using
openai.ChatCompletion.create()
to generate the Python code. Set themessages
parameter to a list of two messages: a system message introducing the assistant’s role and a user message containing the prompt.Set various parameters such as
temperature
,max_tokens
,top_p
,frequency_penalty
, andpresence_penalty
to control the behavior of the language model.Extract the generated code from the API response using
completion.choices[0].message['content']
.
Rendering the Result
Once the Python code is generated, it is passed to the HTML template for rendering. Here’s the relevant part of the code:
python
return render_template('home.html', result=result)
- The render_template function is called with the HTML template file name (home.html) and the result variable containing the generated Python code.
- This function renders the template and replaces placeholders with the provided values.
- The rendered HTML is returned as the response to the user.
HTML Template
The HTML template, home.html, plays a crucial role in the project as it provides a basic way to render the output from the API in the user’s browser. The template is used to display the generated Python code to the user after submitting the form.
html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><metaname="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>Code Generator</title><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" /><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/styles/default.min.css" /><script src="https://cdn.jsdelivr.net/npm/showdown@1.9.1/dist/showdown.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/highlight.min.js"></script><style>/* Dark mode styles */body.dark-mode {background-color: #333;color: #fff;}.dark-mode #output {background-color: #222;color: #fff;}.dark-mode #output code {color: #fff;}</style></head><body><div class="container"><form method="POST" class="my-4"><div class="form-group"><label for="api_key">API Key:</label><input type="text" id="api_key" name="api_key" class="form-control" /></div><div class="form-group"><label for="tasks">Tasks (comma-separated):</label><input type="text" id="tasks" name="tasks" class="form-control" /></div><input type="submit" value="Submit" class="btn btn-primary" /></form>{% if result %}<h2 class="my-4">Result:</h2><div id="output" class="border p-3"><!-- Render result in Markdown --><div id="markdown-output">{{ result }}</div></div>{% endif %}</div><script>hljs.highlightAll()// Markdown renderingvar converter = new showdown.Converter()var outputElement = document.getElementById('output')var resultElement = document.getElementById('markdown-output')var resultText = resultElement.innerHTML.trim()var resultHtml = converter.makeHtml(resultText)resultElement.innerHTML = resultHtml// Dark mode toggle (added this to show how to improve functionality of project)var bodyElement = document.bodyvar darkModeToggle = document.createElement('button')darkModeToggle.innerText = 'Toggle Dark Mode'darkModeToggle.addEventListener('click', function () {bodyElement.classList.toggle('dark-mode')})// Append dark mode toggle button to containervar containerElement = document.querySelector('.container')containerElement.insertBefore(darkModeToggle, containerElement.firstChild)</script></body></html>
The current implementation includes a simple form where users can input their API key and a list of tasks. Upon submission, the Flask application sends the data to the OpenAI Chat API, retrieves the generated code, and passes it as a variable to the template.
You can enhance and customize the HTML template according to your preferences and requirements. Consider adding additional styling, dynamic elements, or interactive features to improve the style and functionality of the rendered output. The template acts as a starting point, and you have the freedom to enhance it to create a more engaging user experience.
Feel free to modify and extend the HTML template to suit your project’s specific needs, such as incorporating CSS frameworks, integrating JavaScript libraries, or adding user-friendly features like syntax highlighting, code formatting, or a responsive design.
Testing Our Finished Project
Now that we’ve analyzed the code, let’s test our project in the browser. To do this, we need to run the Flask application. In the terminal, run the following command:
powershell
(text2py_2) PS C:BASH Scripting\text2py_webui> python .\text2py_webui.py* Serving Flask app 'text2py_webui'* Debug mode: onWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on http://127.0.0.1:5000Press CTRL+C to quit* Restarting with stat* Debugger is active!* Debugger PIN: 132-157-944
This launches a development server for us @ http://127.0.0.1:5000.
Next, we need to enter the API key and tasks in the form and submit it. The generated Python code will be displayed in the browser.
Success! In this example, we supplied the following tasks in plain english:
take user input, supply welcome message to user using input, then reverse the users input back as a string.
Result:
Here’s the Python code to accomplish the task:
python
# take user inputuser_input = input("Please enter your name: ")# supply welcome message to user using inputprint("Welcome, " + user_input + "!")# reverse the user's input back as a stringreversed_input = user_input[::-1]print("Your name spelled backwards is: " + reversed_input)
Wrapping Up
This working project serves as a testament to the incredible potential of AI technology and its seamless integration with web development. By combining the power of OpenAI’s GPT-3.5-Turbo language model and the versatility of Flask, we have created a tool that effortlessly translates English tasks into executable Python code.
This project showcases how easily we can harness the capabilities of AI to automate complex tasks, empowering developers to save time and effort in the process of code generation. By simply providing a set of English tasks, users can obtain Python code tailored to their requirements, all through a user-friendly web interface.