To solve this problem, we will create a Python script that uses the OpenAI API to analyze user input, generate a concise summary, and then craft a poem based on that summary. This solution leverages the gpt-3.5-turbo model for both tasks, balancing factual accuracy (for the summary) and creative expression (for the poem).
Step 1: Prerequisites
- OpenAI API Key: Obtain your key from the OpenAI Platform.
- Install Dependencies: Use
pipto install the OpenAI library:pip install openai
Step 2: Python Script
This script will:
- Take user input.
- Generate a summary using the OpenAI API.
- Generate a poem from the summary.
- Handle common API errors (e.g., invalid key, rate limits).
import os
import openai
from openai.error import (
AuthenticationError,
RateLimitError,
InvalidRequestError,
APIError
)
# Set up OpenAI API key (use environment variable for security, or input manually)
openai.api_key = os.getenv("OPENAI_API_KEY") or input("Enter your OpenAI API key: ").strip()
def generate_summary(input_text: str) -> str:
"""Generate a concise summary of the input text."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "Summarize the following text in 2-3 clear, concise sentences."},
{"role": "user", "content": input_text}
],
temperature=0.3 # Lower temperature for factual accuracy
)
return response.choices[0].message["content"].strip()
except Exception as e:
raise e
def generate_poem(summary: str) -> str:
"""Generate a short poem based on the summary."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "Write a short, evocative poem (4-6 stanzas) using vivid imagery. Focus on the emotion and essence of the summary."},
{"role": "user", "content": f"Summary: {summary}"}
],
temperature=0.7 # Higher temperature for creativity
)
return response.choices[0].message["content"].strip()
except Exception as e:
raise e
if __name__ == "__main__":
# Get user input
user_input = input("Enter the text you want to analyze: ").strip()
if not user_input:
print("Error: Please enter valid text.")
exit()
try:
# Generate summary
print("\nGenerating summary...")
summary = generate_summary(user_input)
print("\nSummary:\n", summary)
# Generate poem
print("\nGenerating poem...")
poem = generate_poem(summary)
print("\nPoem:\n", poem)
except AuthenticationError:
print("Error: Invalid API key. Check your key and try again.")
except RateLimitError:
print("Error: Rate limit exceeded. Try again later or upgrade your plan.")
except InvalidRequestError as e:
print(f"Error: Invalid request. Details: {e}")
except APIError as e:
print(f"API Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Step 3: How to Use
- Set Environment Variable: For security, set your API key as an environment variable:
- Linux/macOS:
export OPENAI_API_KEY="your_key_here" - Windows:
set OPENAI_API_KEY=your_key_here
- Linux/macOS:
- Run the Script: Execute the script and input your text when prompted.
Example Output
Suppose you input:
"The sun dipped below the horizon, painting the sky in hues of orange and pink. A group of children laughed as they chased fireflies in the meadow, their voices echoing through the quiet evening. The air smelled of fresh grass and jasmine, and a gentle breeze carried the sound of crickets chirping."
Summary:
The sun sets, painting the sky orange and pink. Children chase fireflies in a meadow, laughing, while the air smells of grass and jasmine, and crickets chirp in the breeze.
Poem:
Sun dips low, the sky ablaze—
Orange strokes and pink haze.
Children run, their laughter light,
Chasing fireflies through the night.
Grass smells sweet, jasmine’s breath,
Breeze whispers soft, no need for death.
Crickets sing a lullaby,
Underneath the starlit sky.
Each firefly a tiny spark,
Dancing in the growing dark.
Memories woven, warm and bright,
This evening’s magic, pure delight.
This script provides a simple yet powerful way to transform text into a summary and poem using AI. Adjust the prompts or temperature values to customize the output further!


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。