Creating a comprehensive Python-based prompt library with both prompt injection capabilities and AI selection features involves several components:
- GUI Development: We'll use
PyQt5 for creating a user-friendly interface.
- Browser Automation:
Selenium will handle browser interactions, such as navigating to AI platforms and injecting prompts.
- Configuration Management: Define supported AI platforms with necessary details.
- Error Handling & Validation: Ensure robustness through proper error management and input validations.
Below is a step-by-step guide along with the complete code to create such a library.
Prerequisites
- Python 3.x: Ensure you have Python installed. You can download it from python.org.
- Install Required Packages:
pip install PyQt5 selenium
- WebDriver:
- ChromeDriver: If you're using Google Chrome, download the ChromeDriver from here and ensure it's in your system's PATH.
- Other Browsers: Ensure you have the corresponding WebDriver if you prefer a different browser.
Library Structure
We'll structure the library into several classes for better modularity:
- AIPlatform: Represents each AI platform with necessary details.
- PromptManager: Handles prompt injections and interactions with AI platforms.
- MainWindow: The PyQt5 GUI interface.
Complete Code
import sys
import os
import time
from typing import List
from dataclasses import dataclass, field
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QComboBox,
QLineEdit,
QPushButton,
QVBoxLayout,
QLabel,
QMessageBox,
)
from PyQt5.QtCore import Qt
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import (
NoSuchElementException,
WebDriverException,
TimeoutException,
)
from selenium.webdriver.chrome.options import Options as ChromeOptions
@dataclass
class AIPlatform:
name: str
url: str
input_selector: str # CSS Selector or XPath for the prompt input field
submit_selector: str = "" # Optional: CSS Selector or XPath for the submit button
@dataclass
class PromptManager:
platforms: List[AIPlatform] = field(default_factory=list)
driver_path: str = "chromedriver" # Ensure chromedriver is in PATH
def add_platform(self, platform: AIPlatform):
self.platforms.append(platform)
def get_platform_names(self) -> List[str]:
return [platform.name for platform in self.platforms]
def inject_prompt(self, platform_name: str, prompt: str):
platform = next(
(p for p in self.platforms if p.name == platform_name), None
)
if not platform:
raise ValueError(f"AI Platform '{platform_name}' not found.")
# Set up Selenium WebDriver
options = ChromeOptions()
options.add_argument("--start-maximized")
# options.add_argument('--headless') # Uncomment for headless mode
try:
driver = webdriver.Chrome(executable_path=self.driver_path, options=options)
except WebDriverException as e:
raise RuntimeError(f"WebDriver error: {e}")
try:
driver.get(platform.url)
except TimeoutException:
driver.quit()
raise RuntimeError(f"Page load timed out for {platform.url}")
time.sleep(5) # Wait for the page to load; consider using explicit waits
try:
input_element = driver.find_element(By.CSS_SELECTOR, platform.input_selector)
input_element.clear()
input_element.send_keys(prompt)
except NoSuchElementException:
driver.quit()
raise RuntimeError("Prompt input field not found on the page.")
if platform.submit_selector:
try:
submit_element = driver.find_element(By.CSS_SELECTOR, platform.submit_selector)
submit_element.click()
except NoSuchElementException:
driver.quit()
raise RuntimeError("Submit button not found on the page.")
# Optionally, keep the browser open or close it automatically
# driver.quit()
class MainWindow(QWidget):
def __init__(self, prompt_manager: PromptManager):
super().__init__()
self.prompt_manager = prompt_manager
self.init_ui()
def init_ui(self):
self.setWindowTitle("AI Prompt Library")
self.setGeometry(100, 100, 400, 200)
layout = QVBoxLayout()
# AI Selection
self.ai_label = QLabel("Select AI Platform:")
layout.addWidget(self.ai_label)
self.ai_combo = QComboBox()
self.ai_combo.addItems(self.prompt_manager.get_platform_names())
layout.addWidget(self.ai_combo)
# Prompt Input
self.prompt_label = QLabel("Enter your prompt:")
layout.addWidget(self.prompt_label)
self.prompt_input = QLineEdit()
self.prompt_input.setPlaceholderText("Type your prompt here...")
layout.addWidget(self.prompt_input)
# Submit Button
self.submit_btn = QPushButton("Submit Prompt")
self.submit_btn.clicked.connect(self.handle_submit)
layout.addWidget(self.submit_btn)
self.setLayout(layout)
def handle_submit(self):
ai_name = self.ai_combo.currentText()
prompt = self.prompt_input.text().strip()
if not prompt:
QMessageBox.warning(self, "Input Error", "Please enter a prompt.")
return
try:
self.submit_btn.setEnabled(False)
self.submit_btn.setText("Submitting...")
self.prompt_manager.inject_prompt(ai_name, prompt)
QMessageBox.information(self, "Success", f"Prompt injected into {ai_name}.")
except ValueError as ve:
QMessageBox.critical(self, "Error", str(ve))
except RuntimeError as re:
QMessageBox.critical(self, "Error", str(re))
except Exception as e:
QMessageBox.critical(self, "Unexpected Error", str(e))
finally:
self.submit_btn.setEnabled(True)
self.submit_btn.setText("Submit Prompt")
def main():
# Define supported AI platforms
platform1 = AIPlatform(
name="ChatGPT",
url="https://chat.openai.com/",
input_selector="textarea", # Example selector; may need to be updated
submit_selector="" # If necessary
)
platform2 = AIPlatform(
name="Google Bard",
url="https://bard.google.com/",
input_selector="textarea", # Example selector; may need to be updated
submit_selector="" # If necessary
)
# Initialize PromptManager
prompt_manager = PromptManager()
# Add platforms
prompt_manager.add_platform(platform1)
prompt_manager.add_platform(platform2)
# Create and show the GUI
app = QApplication(sys.argv)
window = MainWindow(prompt_manager)
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Explanation of the Code
-
Data Classes:
AIPlatform: Holds information about each AI platform, including the name, URL, and selectors for input and submission.
PromptManager: Manages AI platforms and handles the injection of prompts using Selenium.
-
Prompt Injection (inject_prompt method):
- Initializes the Selenium WebDriver with Chrome in this example.
- Navigates to the selected AI platform's URL.
- Locates the input field using the provided CSS selector and injects the prompt.
- Optionally clicks the submit button if a
submit_selector is provided.
- Error handling is implemented to manage situations where elements aren't found or WebDriver issues occur.
-
GUI (MainWindow class):
- Provides a dropdown to select the AI platform.
- Provides a text field to input the prompt.
- Includes a submit button that triggers the prompt injection process.
- Displays appropriate messages based on success or failure.
-
Main Function (main):
- Defines supported AI platforms. Note: The
input_selector values are placeholders and may need to be updated based on the actual HTML structure of the AI platforms at the time of use.
- Initializes the
PromptManager and adds the AI platforms.
- Launches the GUI application.
Important Notes
-
Selectors: The CSS selectors (input_selector and submit_selector) used to locate input fields and buttons are based on the current structure of AI platforms like ChatGPT or Google Bard. These platforms frequently update their interfaces, so you might need to inspect the webpage (using browser developer tools) to get the correct selectors.
-
WebDriver Compatibility: Ensure that the version of chromedriver matches the version of your installed Chrome browser. Mismatched versions can lead to WebDriverException errors.
-
Headless Mode: If you prefer the browser to operate in the background without opening a visible window, uncomment the --headless option in the Selenium Chrome options.
-
Delay/Waits: The time.sleep(5) is a simple way to wait for the page to load. For a more robust solution, consider using Selenium's Explicit Waits to wait for specific elements to load.
-
Security Considerations: Be cautious when automating browser interactions, especially with sensitive data. Ensure that your usage complies with the AI platform's terms of service.
-
Enhancements:
- Dynamic Selector Parsing: Implement methods to dynamically find input fields if CSS selectors change.
- Support for Multiple Browsers: Extend
PromptManager to support different browsers like Firefox or Edge.
- Advanced Error Handling: Incorporate more granular error management and logging mechanisms.
- GUI Enhancements: Add features like history of prompts, customizable settings, etc.
Running the Application
- Ensure all prerequisites are met (Python installed, required packages installed, WebDriver set up).
- Save the code to a file named, for example,
ai_prompt_library.py.
- Run the application via the command line:
python ai_prompt_library.py
- Use the GUI:
- Select the desired AI platform from the dropdown.
- Enter your prompt in the text field.
- Click the "Submit Prompt" button to inject the prompt into the selected AI platform.
Conclusion
This Python-based prompt library provides a foundational structure for injecting prompts into various AI platforms with a user-friendly interface. Depending on your specific needs, you can extend and customize this library further to accommodate more AI platforms, enhance the UI/UX, and implement additional features.