Created
August 15, 2023 22:59
-
-
Save dewitt4/de94c86b7dae94406d4b71209fc4cc90 to your computer and use it in GitHub Desktop.
Python function that demonstrates how to use the openai package to generate responses from the OpenAI Language Model and then store those responses in a MySQL database
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
import mysql.connector | |
import openai | |
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() | |
def store_response_in_mysql(prompt, generated_text): | |
# 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() | |
# Store response in MySQL | |
query = "INSERT INTO generated_responses (prompt, response) VALUES (%s, %s)" | |
values = (prompt, generated_text) | |
cursor.execute(query, values) | |
# Commit changes and close the database connection | |
connection.commit() | |
cursor.close() | |
connection.close() | |
if __name__ == "__main__": | |
prompts = [ | |
"Once upon a time in a galaxy far, far away...", | |
"In a world where magic is real and technology is ancient...", | |
"The year is 2077, and humanity has colonized Mars..." | |
] | |
for prompt in prompts: | |
generated_text = generate_text_with_llm(prompt) | |
store_response_in_mysql(prompt, generated_text) | |
print("Stored response for prompt:", prompt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment