Python code to write poetry using artificial intelligence

Artificial Intelligence (AI) can write poetry for us. Following a sample code to demonstrate this ability. You would need to get an API key from openai.com

import openai

def generate_poetry():
    openai.api_key = "YOUR_API_KEY"  # replace with your own API key

    prompt = "Write a poem about love"

    completions = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )

    message = completions.choices[0].text
    return message

poem = generate_poetry()
print(poem)

In this code, you need to replace YOUR_API_KEY with your own API key, which you can obtain by signing up for a free account on the OpenAI website. The openai.Completion.create function generates text based on the given prompt, in this case “Write a poem about love”. The generated text is returned as a string.

Note that the generated text is not guaranteed to be grammatically correct or even make sense. However, with the advanced language model of OpenAI’s GPT-3, the generated text can often be quite poetic and creative.