Created
August 15, 2023 22:11
-
-
Save dewitt4/aec4ce9b47186e69285d40095a0f2e62 to your computer and use it in GitHub Desktop.
Python function that demonstrates how to read data from a mySQL database and then feed it into the OpenAI Language Model (LLM)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pip install mysql-connector-python openai | |
import mysql.connector | |
import openai | |
def fetch_data_from_mysql(): | |
# MySQL database configuration | |
db_config = { | |
"host": "your_host", | |
"user": "your_username", | |
"password": "your_password", | |
"database": "your_database" | |
} | |
# Connect to the MySQL database | |
connection = mysql.connector.connect(**db_config) | |
cursor = connection.cursor() | |
# Fetch data from MySQL | |
query = "SELECT text_column FROM your_table" | |
cursor.execute(query) | |
data = cursor.fetchall() | |
# Close the database connection | |
cursor.close() | |
connection.close() | |
return [row[0] for row in data] | |
def generate_text_with_llm(prompt): | |
# OpenAI API configuration | |
openai.api_key = "your_openai_api_key" | |
# Generate text using OpenAI's LLM | |
response = openai.Completion.create( | |
engine="davinci", # Choose the appropriate engine | |
prompt=prompt, | |
max_tokens=100 # Adjust the desired length of generated text | |
) | |
return response.choices[0].text.strip() | |
if __name__ == "__main__": | |
data_from_mysql = fetch_data_from_mysql() | |
for item in data_from_mysql: | |
generated_text = generate_text_with_llm(item) | |
print("Original Data:") | |
print(item) | |
print("Generated Text:") | |
print(generated_text) | |
print("=" * 50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment