AI-based Content Generator Python
👤 Sharing: AI
```python
import openai
import os
def generate_content(prompt, api_key, engine="text-davinci-003", max_tokens=200, n=1, stop=None, temperature=0.7):
"""
Generates content using OpenAI's GPT-3 API.
Args:
prompt (str): The prompt to guide the content generation.
api_key (str): Your OpenAI API key.
engine (str): The OpenAI engine to use (e.g., "text-davinci-003", "text-curie-001").
max_tokens (int): The maximum number of tokens to generate.
n (int): The number of completions to generate.
stop (list): A list of stop sequences at which to stop generating.
temperature (float): Controls randomness. Higher values (e.g., 0.7) make the output more random.
Returns:
list: A list of generated content strings. Returns an empty list on error.
"""
openai.api_key = api_key
try:
response = openai.Completion.create(
engine=engine,
prompt=prompt,
max_tokens=max_tokens,
n=n,
stop=stop,
temperature=temperature
)
return [choice['text'].strip() for choice in response['choices']]
except Exception as e:
print(f"Error generating content: {e}")
return []
def main():
"""
Main function to get user input, generate content, and display the results.
"""
api_key = os.environ.get("OPENAI_API_KEY") # Get API key from environment variable
if not api_key:
api_key = input("Enter your OpenAI API key: ") # Or prompt for it
if not api_key:
print("No API key provided. Exiting.")
return
prompt = input("Enter a prompt for content generation: ")
if not prompt:
print("No prompt entered. Exiting.")
return
try:
num_completions = int(input("Enter the number of content completions to generate (1-5): "))
if not 1 <= num_completions <= 5:
print("Invalid number of completions. Using default of 1.")
num_completions = 1
max_tokens = int(input("Enter the maximum number of tokens to generate (e.g., 200): "))
if max_tokens <= 0:
print("Invalid number of tokens. Using default of 200.")
max_tokens = 200
except ValueError:
print("Invalid input for number of completions or tokens. Using defaults.")
num_completions = 1
max_tokens = 200
generated_content = generate_content(prompt, api_key, n=num_completions, max_tokens=max_tokens)
if generated_content:
print("\nGenerated Content:")
for i, content in enumerate(generated_content):
print(f"--- Completion {i+1} ---")
print(content)
else:
print("No content was generated.")
if __name__ == "__main__":
main()
```
👁️ Viewed: 8
Comments