Skip to content

Instantly share code, notes, and snippets.

@marekkowalczyk
Created March 10, 2023 22:11
Show Gist options
  • Save marekkowalczyk/ad6dfd462ad1b96daa408aa6af104238 to your computer and use it in GitHub Desktop.
Save marekkowalczyk/ad6dfd462ad1b96daa408aa6af104238 to your computer and use it in GitHub Desktop.
This Python code uses the OpenAI API to generate keywords from a text file. It prompts the API with the text file's contents and then extracts the generated keywords from the API's response. The text file's name is passed as a command-line argument to the program, and the API key is retrieved from an environment variable.
import os # Import the os module for working with environment variables
import openai # Import the OpenAI module for working with the OpenAI API
import json # Import the json module for working with JSON data
import sys # Import the sys module for working with command-line arguments
openai.api_key = os.getenv("OPENAI_API_KEY") # Set the OpenAI API key from an environment variable
filename = sys.argv[1] # Get the filename from the command-line arguments
with open(filename, "r") as file: # Open the file in read-only mode
file_contents = file.read() # Read the contents of the file into a string variable
prompt_text = "Extract keywords from this text: " + file_contents # Create the prompt text by concatenating a fixed string with the contents of the file
response = openai.Completion.create( # Call the OpenAI API to generate the response
model="text-davinci-003", # Use the Davinci model for text generation
prompt=prompt_text, # Use the prompt text we created earlier
temperature=0.5, # Set the temperature to control the randomness of the generated text
max_tokens=60, # Set the maximum number of tokens to generate
top_p=1, # Set the top p-value to control the diversity of the generated text
frequency_penalty=0.8, # Set the frequency penalty to encourage diversity in the generated text
presence_penalty=0 # Set the presence penalty to encourage relevance in the generated text
)
response_json = json.dumps(response.to_dict()) # Convert the OpenAIObject to a JSON-formatted string
response_dict = json.loads(response_json) # Convert the JSON-formatted string to a Python dictionary
text = response_dict["choices"][0]["text"] # Extract the generated text from the dictionary
print(text) # Print the generated text to the console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment