Last active
August 15, 2023 23:28
-
-
Save dewitt4/9d33f2ed398e5b3f1df3c163643866a7 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 Cassandra 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
pip install Cassandra-driver openai | |
from cassandra.cluster import Cluster | |
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_cassandra(prompt, generated_text): | |
# Cassandra database configuration | |
cluster = Cluster(["your_cassandra_host"]) | |
session = cluster.connect("your_keyspace") | |
# Store response in Cassandra | |
query = "INSERT INTO generated_responses (prompt, response) VALUES (?, ?)" | |
session.execute(query, (prompt, generated_text)) | |
# Close the Cassandra session | |
session.shutdown() | |
cluster.shutdown() | |
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_cassandra(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