Creating a Sample Python App to Generate Perfect Prompts with GPT-4 API
In this article, we will create a Python app that helps users generate perfect prompts using the GPT-4 API. The app will take user input, process it, and suggest an optimized prompt to get the best response from the GPT-4 model. By following this guide, you will learn how to interact with the OpenAI API, refine user inputs, and provide valuable prompt suggestions.
Prerequisites
Before you start, ensure you have the following:
- Python installed on your machine (preferably Python 3.7+).
- An OpenAI API key. You can get it by signing up at OpenAI.
- Basic knowledge of Python programming.
Step 1: Setting Up the Environment
First, you need to install the necessary libraries. Create a new directory for your project and navigate into it. Then, create a virtual environment and install the OpenAI library.
bashmkdir gpt4_prompt_app
cd gpt4_prompt_app
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
pip install openai
Step 2: Writing the App
Create a new file called app.py
in your project directory and open it in your favorite text editor. Let's start by importing the required libraries and setting up the basic structure.
pythonimport openai
import os
# Load your OpenAI API key from an environment variable or directly set it
openai.api_key = os.getenv("OPENAI_API_KEY", "your-openai-api-key-here")
def generate_prompt_suggestions(user_input):
# Define the prompt
prompt = f"User input: {user_input}\n\nSuggest an optimized prompt for GPT-4 to get the best response:"
# Call the OpenAI API to generate a suggestion
response = openai.Completion.create(
engine="text-davinci-004", # Use GPT-4 engine
prompt=prompt,
max_tokens=50,
n=1,
stop=None,
temperature=0.7,
)
# Extract the suggested prompt from the API response
suggestion = response.choices[0].text.strip()
return suggestion
def main():
print("Welcome to the GPT-4 Prompt Optimization App!")
user_input = input("Enter your initial prompt or question: ")
optimized_prompt = generate_prompt_suggestions(user_input)
print("\nSuggested optimized prompt:")
print(optimized_prompt)
if __name__ == "__main__":
main()
Step 3: Running the App
To run the app, simply execute the app.py
file in your terminal.
bashpython app.py
You will be prompted to enter your initial input. The app will then call the GPT-4 API to generate an optimized prompt suggestion and display it.
Step 4: Enhancing the App
To make the app more user-friendly, you can add error handling and further refine the prompt generation process. Here’s an enhanced version of the generate_prompt_suggestions
function with added error handling:
pythondef generate_prompt_suggestions(user_input):
try:
# Define the prompt
prompt = f"User input: {user_input}\n\nSuggest an optimized prompt for GPT-4 to get the best response:"
# Call the OpenAI API to generate a suggestion
response = openai.Completion.create(
engine="text-davinci-004", # Use GPT-4 engine
prompt=prompt,
max_tokens=50,
n=1,
stop=None,
temperature=0.7,
)
# Extract the suggested prompt from the API response
suggestion = response.choices[0].text.strip()
return suggestion
except Exception as e:
return f"An error occurred: {e}"
You can also enhance the main
function to allow for multiple inputs in a loop:
pythondef main():
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
optimized_prompt = generate_prompt_suggestions(user_input)
print("\nSuggested optimized prompt:")
print(optimized_prompt)
print()
if __name__ == "__main__":
main()
In this article, we walked through creating a simple Python app that helps users generate optimized prompts for the GPT-4 API. By leveraging the power of OpenAI's GPT-4, you can improve the quality of responses to your queries. Feel free to enhance and expand this app to suit your needs. Happy coding!
Further Enhancements
Here are some enhancements we can make:
- Input Validation: Ensure the user input is valid before making the API call.
- Logging: Add logging to track usage and errors.
- Command-line Arguments: Allow users to provide their OpenAI API key and other configurations via command-line arguments.
- Configuration File: Allow the app to read configurations from a file.
- Multiple Prompt Suggestions: Generate multiple suggestions for each input.
- Saving Results: Save the input and suggestions to a file for future reference.
Step-by-Step Enhancements
1. Input Validation
Let's add input validation to ensure the user provides a non-empty string.
pythondef validate_input(user_input):
if not user_input.strip():
raise ValueError("Input cannot be empty.")
return user_input.strip()
Update the main
function to use this validation:
pythondef main():
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
try:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
validated_input = validate_input(user_input)
optimized_prompt = generate_prompt_suggestions(validated_input)
print("\nSuggested optimized prompt:")
print(optimized_prompt)
print()
except ValueError as e:
print(f"Error: {e}")
2. Logging
Add logging to track errors and usage.
pythonimport logging
# Configure logging
logging.basicConfig(level=logging.INFO, filename='app.log', filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s')
def generate_prompt_suggestions(user_input):
try:
prompt = f"User input: {user_input}\n\nSuggest an optimized prompt for GPT-4 to get the best response:"
response = openai.Completion.create(
engine="text-davinci-004",
prompt=prompt,
max_tokens=50,
n=1,
stop=None,
temperature=0.7,
)
suggestion = response.choices[0].text.strip()
logging.info(f"Generated prompt suggestion for input: {user_input}")
return suggestion
except Exception as e:
logging.error(f"Error generating prompt suggestion: {e}")
return f"An error occurred: {e}"
3. Command-line Arguments
Use the argparse
module to handle command-line arguments.
pythonimport argparse
def parse_arguments():
parser = argparse.ArgumentParser(description="GPT-4 Prompt Optimization App")
parser.add_argument("--api_key", type=str, help="OpenAI API key")
return parser.parse_args()
def main():
args = parse_arguments()
if args.api_key:
openai.api_key = args.api_key
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
try:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
validated_input = validate_input(user_input)
optimized_prompt = generate_prompt_suggestions(validated_input)
print("\nSuggested optimized prompt:")
print(optimized_prompt)
print()
except ValueError as e:
print(f"Error: {e}")
4. Configuration File
Allow the app to read configurations from a file using configparser
.
pythonimport configparser
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config['DEFAULT']['api_key']
def main():
config_api_key = read_config()
args = parse_arguments()
openai.api_key = args.api_key or config_api_key
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
try:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
validated_input = validate_input(user_input)
optimized_prompt = generate_prompt_suggestions(validated_input)
print("\nSuggested optimized prompt:")
print(optimized_prompt)
print()
except ValueError as e:
print(f"Error: {e}")
5. Multiple Prompt Suggestions
Generate multiple suggestions for each input.
pythondef generate_prompt_suggestions(user_input, num_suggestions=3):
try:
prompt = f"User input: {user_input}\n\nSuggest optimized prompts for GPT-4 to get the best response:"
response = openai.Completion.create(
engine="text-davinci-004",
prompt=prompt,
max_tokens=50,
n=num_suggestions,
stop=None,
temperature=0.7,
)
suggestions = [choice.text.strip() for choice in response.choices]
logging.info(f"Generated prompt suggestions for input: {user_input}")
return suggestions
except Exception as e:
logging.error(f"Error generating prompt suggestions: {e}")
return [f"An error occurred: {e}"]
def main():
config_api_key = read_config()
args = parse_arguments()
openai.api_key = args.api_key or config_api_key
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
try:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
validated_input = validate_input(user_input)
optimized_prompts = generate_prompt_suggestions(validated_input)
print("\nSuggested optimized prompts:")
for prompt in optimized_prompts:
print(prompt)
print()
except ValueError as e:
print(f"Error: {e}")
6. Saving Results
Save the input and suggestions to a file for future reference.
pythonimport json
def save_results(user_input, suggestions):
with open('results.json', 'a') as f:
result = {"input": user_input, "suggestions": suggestions}
json.dump(result, f)
f.write('\n')
def main():
config_api_key = read_config()
args = parse_arguments()
openai.api_key = args.api_key or config_api_key
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
try:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
validated_input = validate_input(user_input)
optimized_prompts = generate_prompt_suggestions(validated_input)
print("\nSuggested optimized prompts:")
for prompt in optimized_prompts:
print(prompt)
save_results(validated_input, optimized_prompts)
print()
except ValueError as e:
print(f"Error: {e}")
Complete Enhanced Code
Here's the complete enhanced version of app.py
:
pythonimport openai
import os
import argparse
import configparser
import logging
import json
# Configure logging
logging.basicConfig(level=logging.INFO, filename='app.log', filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s')
# Load your OpenAI API key from an environment variable or directly set it
openai.api_key = os.getenv("OPENAI_API_KEY", "your-openai-api-key-here")
def parse_arguments():
parser = argparse.ArgumentParser(description="GPT-4 Prompt Optimization App")
parser.add_argument("--api_key", type=str, help="OpenAI API key")
return parser.parse_args()
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config['DEFAULT']['api_key']
def validate_input(user_input):
if not user_input.strip():
raise ValueError("Input cannot be empty.")
return user_input.strip()
def generate_prompt_suggestions(user_input, num_suggestions=3):
try:
prompt = f"User input: {user_input}\n\nSuggest optimized prompts for GPT-4 to get the best response:"
response = openai.Completion.create(
engine="text-davinci-004",
prompt=prompt,
max_tokens=50,
n=num_suggestions,
stop=None,
temperature=0.7,
)
suggestions = [choice.text.strip() for choice in response.choices]
logging.info(f"Generated prompt suggestions for input: {user_input}")
return suggestions
except Exception as e:
logging.error(f"Error generating prompt suggestions: {e}")
return [f"An error occurred: {e}"]
def save_results(user_input, suggestions):
with open('results.json', 'a') as f:
result = {"input": user_input, "suggestions": suggestions}
json.dump(result, f)
f.write('\n')
def main():
config_api_key = read_config()
args = parse_arguments()
openai.api_key = args.api_key or config_api_key
print("Welcome to the GPT-4 Prompt Optimization App!")
while True:
try:
user_input = input("Enter your initial prompt or question (or type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
validated_input = validate_input(user_input)
optimized_prompts = generate_prompt_suggestions(validated_input)
print("\nSuggested optimized prompts:")
for prompt in optimized_prompts:
print(prompt)
save_results(validated_input, optimized_prompts)
print()
except ValueError as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Conclusion
With these enhancements, our app is now more robust, user-friendly, and feature-rich. It validates user input, logs activities, accepts command-line arguments, reads configurations from a file, generates multiple prompt suggestions, and saves the results for future reference. Feel free to further expand and customize this app to suit your specific needs.