Program :
# Install transformers if not already installed
# !pip install transformers
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
# Load pre-trained GPT-2 model and tokenizer
model_name = "gpt2" # small GPT-2
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
# Set padding token to eos_token to avoid warnings
tokenizer.pad_token = tokenizer.eos_token
# Function to generate text
def generate_text(prompt, max_length=100):
# Encode prompt
input_ids = [Link](prompt, return_tensors='pt')
# Generate text with proper padding and attention mask
output = [Link](
input_ids,
max_length=max_length,
num_return_sequences=1,
do_sample=True,
top_k=50,
top_p=0.95,
temperature=0.7,
pad_token_id=tokenizer.eos_token_id, # avoids warning
attention_mask=torch.ones_like(input_ids) # correct attention mask
)
# Decode generated text
generated_text = [Link](output[0], skip_special_tokens=True)
return generated_text
# --- User Interaction ---
print("=== Generative AI Text Generator ===")
user_prompt = input("Enter a prompt: ")
generated = generate_text(user_prompt, max_length=100)
# Display output
print("\nPrompt:", user_prompt)
print("Generated Text:\n", generated)
Output:
=== Generative AI Text Generator ===
Enter a prompt: Artificial Intelligence is transforming
Prompt: Artificial Intelligence is transforming
Generated Text:
Artificial Intelligence is transforming the way we work, and it is doing so with the help of
some of the most promising AI technologies in the business.
This year's conference saw the creation of two new AI technologies, and the world's first 'Real-
Time Machine' to learn from real-time data.
The AI program is called 'Reverse Recursion', which uses a machine learning algorithm to
build a simple algorithm to extract information about a specific event in real time.