Generative AI using Python - Basic
Interview Questions with Answers

Explore Our Courses
1. What is Generative AI?
Answer:
Generative AI is a subfield of artificial intelligence that focuses on creating new content — such as text, images, audio, video, or code — that mimics the patterns of real-world data.
It uses machine learning models, particularly deep generative models like GANs, VAEs, and Transformers, to learn the underlying structure of data and generate new, realistic outputs.
In simple terms, Generative AI learns from existing data to generate new data that looks or sounds similar.
2. Name a few popular applications of Generative AI.
Answer:
Some widely used applications of Generative AI include:
- Text Generation: Chatbots, writing assistants (e.g., ChatGPT)
- Image Generation: AI art (e.g., DALL·E, Midjourney)
- Voice Cloning & Music Creation: AI singers, podcasts
- Code Generation: GitHub Copilot, CodeWhisperer
- Video Generation: Deepfakes, synthetic actors
- Data Augmentation: For training models with limited data
- Product Design: Generating product prototypes or fashion designs
Lorem Ispum
3. How is Generative AI different from Traditional AI?
Answer:
Traditional AI is focused on analyzing or predicting; Generative AI is focused on creating.
4. What are examples of tools using Generative AI?
Answer:
Some tools and platforms built with Generative AI are:
- ChatGPT (OpenAI) – Text-based conversation and writing
- DALL·E 2 (OpenAI) – Image generation from text prompts
- Midjourney – Artistic image generation
- Stable Diffusion – Open-source image generator
- GitHub Copilot – AI code completion
- RunwayML – AI for creative professionals (video/image editing)
- Bard (Google) – Conversational AI
- Suno AI / Udio – Music generation
- Jasper AI – AI copywriting tool
These tools rely on deep learning models trained on large datasets to generate high-quality outputs.
5. What is the main purpose of Generative AI models?
Answer:
The primary purpose of Generative AI models is to learn the distribution and structure of training data and use it to create new, realistic data samples.
This includes generating content that did not exist before, such as:
- New paragraphs of text
- Artificially generated images
- Synthesized speech or music
- Augmented datasets for model training
In essence, Generative AI models aim to replicate or extend the training data in novel ways.
6. What are the two types of models used in AI?
Answer:
In AI, the two primary types of models are:
- Discriminative Models
- Purpose: Classify input data into predefined categories.
- Examples: Logistic Regression, SVM, Decision Trees, BERT (for classification)
- Learn: The boundary between classes (P(Y|X))
- Generative Models
- Purpose: Learn the data distribution and generate new data.
- Examples: GANs, VAEs, LLMs like GPT
- Learn: The full data distribution (P(X), or P(X, Y))
These types serve different goals but are both essential in modern AI.
7. What is a Generative Model in Machine Learning?
Answer:
A Generative Model in machine learning is a model that learns the joint probability distribution P(X) or P(X, Y) and is capable of generating new data instances similar to the training set.
These models aim to answer:
- “What could a realistic data sample look like?”
- “How can I create new data points that resemble training data?”
Examples of generative models:
- GANs (Generative Adversarial Networks)
- VAEs (Variational Autoencoders)
- Autoregressive models (like GPT)
- Diffusion models
8. What kind of data can Generative AI work with?
Answer:
Generative AI can work with a wide range of data types, including:
- Text: Articles, poems, stories, code
- Images: Faces, landscapes, art, designs
- Audio: Music, speech, sound effects
- Video: Synthetic faces, animated scenes
- Code: Programming scripts, functions
- Tabular Data: Synthetic datasets for analytics
- 3D Models: For gaming, AR/VR applications
Generative AI models are designed to process structured, semi-structured, or unstructured data, depending on their architecture.
9. Can Generative AI generate images?
Answer:
Yes, Generative AI can generate highly realistic or artistic images.
Popular models for image generation include:
- GANs – Deep Convolutional GANs (DCGAN), StyleGAN
- Diffusion Models – Stable Diffusion, DALL·E
- VAEs – For simple and interpretable image generation
In Python, you can use:
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
image = pipe("A beautiful mountain landscape").images[0]
image.show()
10. Can Generative AI generate text?
Answer:
Absolutely, yes. Generative AI is widely used for generating text using language models.
Popular text generation models:
- GPT-2 / GPT-3 / GPT-4
- T5
- BLOOM
- LLaMA
Basic Python example using Hugging Face:
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
output = generator("Once upon a time", max_length=30)
print(output[0]["generated_text"])
These models learn from large text corpora and generate coherent, context-aware text outputs.
11. Which Python libraries are used for Generative AI?
Answer:
The most commonly used Python libraries for Generative AI include:
- TensorFlow – Deep learning framework by Google, supports GANs, VAEs, Transformers.
- PyTorch – Deep learning library by Facebook, used for building and training models like GPT, VAE, etc.
- Transformers – By Hugging Face, provides pre-trained LLMs like GPT, BERT, T5.
- Diffusers – For diffusion-based models like Stable Diffusion (text-to-image).
- Keras – High-level API for TensorFlow, simplifies model building.
- NumPy – Used for numerical operations and tensor manipulation.
- Matplotlib / Seaborn – Visualization tools for plotting training loss, images, etc.
- Gradio / Streamlit – For building web-based demos of AI applications.
- OpenCV / PIL – For handling and manipulating image data.
12. How do you install TensorFlow in Python?
Answer:
You can install TensorFlow using pip:
pip install tensorflow
To install a specific version (e.g., 2.14.0):
pip install tensorflow==2.14.0
Make sure Python ≥ 3.7 and pip are installed. For GPU support, use tensorflow-gpu.
13. How do you import PyTorch in Python?
Answer:
You must first install it based on your system configuration from https://pytorch.org/.
Then, import the main modules in Python:
import torch # Core PyTorch
import torch.nn as nn # Neural network modules
import torch.optim as optim # Optimizers
Example
x = torch.tensor([1.0, 2.0, 3.0])
print(x)
14. What is the use of NumPy in AI?
Answer:
NumPy is essential for AI/ML because:
- It provides support for n-dimensional arrays (ndarray) for data representation.
- It allows fast mathematical operations, essential for processing large datasets.
- Many AI libraries (like TensorFlow, PyTorch) are built on top of NumPy structures.
- It is used for data preprocessing, vector/matrix math, and custom loss functions.
Example:
import numpy as np
a = np.array([1, 2, 3])
print(np.mean(a)) # Output: 2.0
15. What is the use of Matplotlib in AI projects?
Answer:
Matplotlib is used in AI projects for:
- Visualizing training loss, accuracy, or other metrics.
- Plotting generated images in image-based AI projects.
- Comparing actual vs predicted results graphically.
- Tracking performance trends during model training.
Example
import matplotlib.pyplot as plt
loss = [0.9, 0.6, 0.3, 0.2]
plt.plot(loss)
plt.title("Training Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.show()
16. How can you generate random numbers in Python?
Answer:
You can use:
1. random module (for basic random numbers):
import random
print(random.randint(1, 100)) # Random integer
print(random.random()) # Random float (0 to 1)
2.numpy.random (for scientific applications):
import numpy as np
print(np.random.randint(0, 10, size=(3, 3))) # Random 3x3 matrix
print(np.random.randn(5)) # Random normal distribution
17. How do you install HuggingFace Transformers in Python?
Answer:
Use the following pip command:
pip install transformers
Optional (for PyTorch & TensorFlow support):
pip install transformers[torch] # For PyTorch users
pip install transformers[tf-cpu] # For TensorFlow (CPU only)
You can also install datasets and tokenizers if you're building pipelines:
pip install datasets tokenizers
18. What is the use of the fit() function in TensorFlow?
Answer:
The fit() function is used to train a model in TensorFlow using the provided data.
Syntax:
model.fit(x_train, y_train, epochs=10, batch_size=32)
Key Functions:
- Passes input/output data through the model.
- Adjusts weights using backpropagation.
- Trains over multiple ‘epochs’ and ‘batches’.
- Displays loss/accuracy metrics.
Equivalent to a full training loop internally.
19. What is the purpose of model.predict() in Python AI code?
Answer:
The model.predict() function is used to generate predictions using the trained model on new/unseen data.
Example:
predictions = model.predict(x_test)
Use Cases:
- To evaluate model performance.
- For inference in production.
- For generating output (e.g., text/image).
In generative models, it may return logits, tokens, or even complete images/text.
20. How do you load datasets using Python?
Answer:
There are multiple ways to load datasets:
Using scikit-learn:
from sklearn.datasets import load_iris
data = load_iris()
print(data.data.shape)
Using TensorFlow/Keras:
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
Using PyTorch:
from torchvision import datasets, transforms
mnist_data = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.ToTensor())
Using HuggingFace Datasets:
from datasets import load_dataset
dataset = load_dataset("imdb")
print(dataset["train"][0])
Lorem Ispum
21. What is text generation in AI?
Answer:
Text generation in AI is the process of producing coherent, context-aware textual content using language models. These models are trained on large corpora and can continue a given prompt or create new text from scratch.
Examples of text generation tasks
- Chatbots
- Article/essay generation
- Code generation
- Email composition
Popular models for text generation
- GPT-2, GPT-3, GPT-4 (by OpenAI)
- T5, BART (by Google/Facebook)
22. What is GPT in Generative AI?
Answer:
GPT stands for Generative Pre-trained Transformer, a family of autoregressive language models developed by OpenAI.
Key features:
- Pre-trained on large text data (like books, websites).
- Uses Transformer architecture with self-attention.
- Can perform a variety of NLP tasks: summarization, translation, question answering, etc.
Example in Python using HuggingFace
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
result = generator("Once upon a time", max_length=30)
print(result[0]['generated_text'])
23. What is the use of HuggingFace Transformers in Python?
Answer:
HuggingFace transformers is a Python library that provides:
- Pre-trained models like GPT, BERT, T5, RoBERTa
- Easy-to-use pipelines for text generation, translation, summarization
- Tokenizers and configuration tools
Benefits:
- Reduces coding complexity
- Enables fine-tuning and inference with minimal setup
- Supports PyTorch and TensorFlow
Install:
pip install transformers
24. How do you load a pre-trained GPT model in Python?
Answer:
Using HuggingFace’s Transformers library:
from transformers import GPT2Tokenizer, GPT2LMHeadModel
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
For text generation:
input_ids = tokenizer.encode("Once upon a time", return_tensors="pt")
output = model.generate(input_ids, max_length=50, num_return_sequences=1)
print(tokenizer.decode(output[0], skip_special_tokens=True))
GPT2LMHeadModel is used for text generation tasks.
25. What is pipeline() function in HuggingFace?
Answer:
The pipeline() function in HuggingFace is a high-level abstraction for performing common NLP tasks without needing to handle model/tokenizer setup manually.
Examples:
from transformers import pipeline
# Text generation
text_gen = pipeline("text-generation", model="gpt2")
print(text_gen("Hello world", max_length=20))
# Sentiment analysis
sentiment = pipeline("sentiment-analysis")
print(sentiment("I love AI!"))
Tasks supported: text-generation, translation, summarization, question-answering, etc.
26. What is a prompt in Generative AI?
Answer:
A prompt is the input text or instruction given to a generative model to produce an output.
Example:
- Prompt: “Write a poem about the ocean”
- Model output: “The waves dance under moonlit skies…”
Prompt quality strongly influences output quality. This is known as Prompt Engineering.
Prompt in code:
generator("Tell me a joke about developers", max_length=30)
27. What does a language model learn from data?
Answer:
A language model learns:
- Grammar and structure of a language
- Word associations and context
- Statistical relationships between words/tokens
- Ability to predict the next word/token given previous words
Advanced models also learn:
- Semantic meaning
- Intent detection
- Task-specific knowledge (like summarization or classification)
28. What is the simplest way to generate text using Python?
Answer:
Using the HuggingFace pipeline for text generation:
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
output = generator("AI is transforming the world", max_length=30)
print(output[0]['generated_text'])
This automatically downloads the model and tokenizer, handles encoding/decoding, and performs generation.
29. What is a tokenizer?
Answer:
A tokenizer is a tool that:
- Converts raw text into tokens (numbers) that a model can understand.
- Encodes input text into token IDs before passing to the model.
- Decodes output token IDs back to readable text.
Types of tokenizers:
- Word-level (older)
- Subword/BPE (used in GPT, BERT)
- SentencePiece
Example:
from transformers import GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
tokens = tokenizer.encode("Hello AI")
print(tokens) # [15496, 32, 50256]
30. Can we fine-tune GPT models using Python?
Answer:
Yes, GPT models like GPT-2 can be fine-tuned using HuggingFace with PyTorch or TensorFlow.
Steps:
- Prepare a custom dataset (text format).
- Use Trainer API or custom training loop.
- Load pre-trained GPT model and tokenizer.
- Fine-tune on your dataset.
Example snippet:
from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments
# Load model and tokenizer
model = GPT2LMHeadModel.from_pretrained("gpt2")
# Tokenize your dataset and use Trainer to fine-tune
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
Fine-tuning requires GPU and careful configuration of learning rate, batch size, etc.
31. Can AI generate human faces?
Answer:
Yes, Generative AI can generate highly realistic human faces using models like:
- StyleGAN (by NVIDIA): Generates photorealistic human faces.
- Progressive GANs: Trains on increasing image resolutions.
- Diffusion Models (like Stable Diffusion): Can generate face images from text prompts.
Example (using diffusers for face generation):
from diffusers import StableDiffusionPipeline
import torch
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4",
torch_dtype=torch.float16)
pipe = pipe.to("cuda")
image = pipe("a photo of a young woman").images[0]
image.show()
Ethical use is crucial when generating synthetic faces.
32. What is a VAE (Variational Autoencoder)?
Answer:
A Variational Autoencoder (VAE) is a type of generative model that:
- Encodes input data into a latent space.
- Samples from this latent space.
- Decodes the sample back to generate new data.
Structure:
- Encoder: Compresses data into mean and variance.
- Decoder: Reconstructs the input or creates new data from latent space.
Use cases:
- Image generation
- Denoising
- Anomaly detection
33. What is DCGAN?
Answer:
DCGAN (Deep Convolutional GAN) is a type of GAN architecture that uses convolutional layers instead of fully connected layers.
- Generator: Uses ConvTranspose2D to generate images.
- Discriminator: Uses Conv2D to distinguish real vs. fake images.
DCGANs are stable and effective for generating high-quality images like:
- Handwritten digits (MNIST)
- Faces (CelebA dataset)
- Art or anime
34. What dataset is used to generate handwritten digits?
Answer:
The most common dataset for generating handwritten digits is the MNIST dataset.
Details:
- 70,000 grayscale images of digits (0–9)
- Image size: 28×28 pixels
- Used to train and evaluate VAEs, GANs, and classifiers
Load in Python:
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
35. How do you use MNIST dataset in Python?
Answer:
You can load and use the MNIST dataset using TensorFlow or PyTorch.
TensorFlow Example:
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape) # (60000, 28, 28)
PyTorch Example
from torchvision import datasets, transforms
mnist_data = datasets.MNIST(root="./data", train=True, download=True,
transform=transforms.ToTensor())
You can then use it for training GANs or VAEs.
36. What is the role of plt.imshow() in image generation?
Answer:
plt.imshow() (from matplotlib.pyplot) is used to display image data in a notebook or GUI.
Use in AI:
- Visualize generated images from GANs or VAEs
- Display samples during training
Example:
import matplotlib.pyplot as plt
plt.imshow(generated_image.squeeze(), cmap='gray')
plt.axis('off')
plt.title("Generated Image")
plt.show()
Supports color maps like gray, viridis, or hot.
37. What is torchvision.datasets.MNIST used for?
Answer:
torchvision.datasets.MNIST is a PyTorch utility that:
- Downloads and loads the MNIST dataset.
- Applies image transformations (e.g., ToTensor()).
- Prepares the dataset for use in training GANs, CNNs, etc.
Example:
from torchvision import datasets, transforms
mnist = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
Returns image-label pairs wrapped in a DataLoader.
38. What Python library is used to view generated images?
Answer:
Common libraries used to view generated images in Python are:
- Matplotlib (plt.imshow())
- PIL (Pillow) (Image.show())
- OpenCV (cv2.imshow())
- Gradio / Streamlit (for web interface)
Example using Pillow:
from PIL import Image
image = Image.fromarray(generated_array, 'L')
image.show()
For notebook-based work, Matplotlib is most common.
39. What is latent space in image generation?
Answer:
Latent space is a compressed, abstract representation of input data, typically produced by the encoder in VAEs or input noise in GANs.
- It is a vector of real numbers that encodes high-level features (e.g., pose, style, color).
- Generative models sample from this space to generate new outputs.
Example in GAN:
noise = torch.randn(batch_size, latent_dim)
generated_images = generator(noise)
Navigating the latent space enables style transfer, interpolation, and controlled generation.
40. Can we control image style using Generative AI?
Answer:
Yes, image styles can be controlled using:
- Conditional GANs (cGANs): Add class labels as input to control generation.
- StyleGANs: Modify specific latent vectors to change facial expressions, age, etc.
- Text-to-image models (e.g., Stable Diffusion): Style can be guided via prompts.
Example (Stable Diffusion):
pipe("a painting of a mountain in Van Gogh style").images[0].show()
This is called controlled or conditional generation.
Lorem Ispum
41. What are the key evaluation metrics for generative models (FID, IS, BLEU, ROUGE)?
Answer:
Example to calculate BLEU:
from nltk.translate.bleu_score import sentence_bleu
reference = [["this", "is", "a", "test"]]
candidate = ["this", "is", "test"]
score = sentence_bleu(reference, candidate)
print(score)
42. How do you handle overfitting in generative models?
Answer:
To handle overfitting in generative models:
- Early Stopping – Stop training when validation loss increases.
- Regularization – Use dropout or weight decay.
- Data Augmentation – Increase training variety.
- Latent Noise Injection – Adds variation in GANs.
- Reduce Model Complexity – Use fewer layers or parameters.
- Train with More Data – Improves generalization.
Example: Early stopping in Keras:
from tensorflow.keras.callbacks import EarlyStopping
callback = EarlyStopping(monitor='val_loss', patience=5)
model.fit(X_train, y_train, validation_split=0.2, callbacks=[callback])
43. What are the best practices to tune hyperparameters in GAN training?
Answer:
Best practices include:
- Use separate learning rates for Generator and Discriminator (e.g., 1e-4 for G, 4e-4 for D).
- Use Batch Normalization in Generator.
- Avoid Batch Norm in Discriminator.
- Use LeakyReLU in Discriminator.
- Label smoothing (e.g., real = 0.9) for stability.
- Avoid training D too well (it may overpower G).
Example: (PyTorch Optimizers)
optimizer_G = torch.optim.Adam(generator.parameters(), lr=0.0001)
optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=0.0004)
44. Implement early stopping for a GAN using custom training loops.
Answer:
Early stopping can be manually tracked in GANs since custom loops are common.
best_loss = float("inf")
epochs_no_improve = 0
patience = 5
for epoch in range(num_epochs):
train_gan() # Custom GAN training per epoch
if validation_loss < best_loss:
best_loss = validation_loss
epochs_no_improve = 0
else:
epochs_no_improve += 1
if epochs_no_improve == patience:
print("Early stopping triggered")
break
Use a validation metric like discriminator loss on real images.
45. How do you use TensorBoard to track GAN training progress in Python?
Answer:
TensorBoard helps visualize losses and images.
Steps:
- Create a TensorBoard log directory.
- Use tf.summary.scalar() and tf.summary.image() for logging.
- Launch TensorBoard with tensorboard –logdir logs/.
Example:
import tensorflow as tf
writer = tf.summary.create_file_writer("logs/gan")
with writer.as_default():
tf.summary.scalar("generator_loss", gen_loss, step=epoch)
tf.summary.scalar("discriminator_loss", disc_loss, step=epoch)
46. How do you perform data augmentation to improve generative model performance?
Answer:
Data augmentation increases input diversity, which helps the model generalize better.
Common augmentations:
- Flip (horizontal/vertical)
- Rotation
- Color jitter
- Noise injection
Example using PyTorch:
from torchvision import transforms
transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(15),
transforms.ToTensor()
])
For text: paraphrasing, synonym replacement, back translation.
47. What is Wasserstein GAN (WGAN) and how does it improve training stability?
Answer:
WGAN is a variant of GAN that improves training by:
- Replacing binary cross-entropy loss with Wasserstein distance (a smooth measure of difference between distributions).
- Removes the problem of vanishing gradients in standard GANs.
- Uses a critic instead of discriminator and removes sigmoid.
Key Features:
- Weight clipping or gradient penalty
- Better convergence
Loss Function (simplified):
# Critic loss
loss_D = -torch.mean(real_output) + torch.mean(fake_output)
# Generator loss
loss_G = -torch.mean(fake_output)
48. Write Python code to visualize generated samples after each epoch.
Answer:
import matplotlib.pyplot as plt
def show_generated_images(generator, epoch, latent_dim=100, n=5):
noise = torch.randn(n, latent_dim).to(device)
fake_images = generator(noise).detach().cpu()
plt.figure(figsize=(n, 1))
for i in range(n):
plt.subplot(1, n, i + 1)
plt.imshow(fake_images[i].permute(1, 2, 0).squeeze(), cmap='gray')
plt.axis('off')
plt.suptitle(f"Epoch {epoch}")
plt.show()
Call this function at the end of every epoch in GAN training loop.
49. How do you apply transfer learning to improve generative model performance?
Answer:
Transfer learning in generative models means:
- Reusing pre-trained models (like GPT, StyleGAN).
- Fine-tuning on a smaller domain-specific dataset.
Use cases:
- Train GPT-2 on medical data for domain-specific generation.
- Fine-tune Stable Diffusion on custom art styles (DreamBooth).
Example (using Transformers):
from transformers import GPT2LMHeadModel
model = GPT2LMHeadModel.from_pretrained("gpt2")
model.train() # Fine-tune on your dataset
50. How can you optimize inference time of generative models for real-time applications?
Answer:
Techniques to optimize inference time:
- Model quantization (e.g., float32 → int8)
- Use ONNX or TorchScript for model export
- Use GPU acceleration (CUDA, TensorRT)
- Use batch generation
- Reduce sequence/image size
- Use distilled versions (e.g., DistilGPT2)
Example:
Export to TorchScript
scripted_model = torch.jit.script(model)
torch.jit.save(scripted_model, "model.pt")
51. How do you deploy a generative AI model using FastAPI or Flask?
Answer:
You can deploy a generative AI model using FastAPI or Flask to serve predictions via APIs.
Example using FastAPI:
from fastapi import FastAPI
from transformers import pipeline
app = FastAPI()
generator = pipeline("text-generation", model="gpt2")
@app.get("/generate")
def generate(prompt: str):
output = generator(prompt, max_length=50)
return {"result": output[0]['generated_text']}
Run server:
uvicorn app:app --reload
This exposes the model for real-time use via HTTP.
52. What are use cases of Generative AI in content creation and marketing?
Answer:
Generative AI is transforming content creation in:
- Copywriting – Generating product descriptions, emails, headlines.
- Social Media Posts – Creating engaging content for platforms.
- Blog Writing – Auto-generating long-form content with GPT-based tools.
- SEO Optimization – Keyword-rich text generation.
- Image/Ad Design – Using DALL·E or Stable Diffusion to generate ad creatives.
- Video Scriptwriting – Drafting ad scripts automatically.
Tools used:
- Jasper AI
- ChatGPT
- Copy.ai
- Writesonic
53. How would you implement a chatbot using GPT and LangChain in Python?
Answer:
LangChain makes it easy to build GPT-based chatbots.
Steps:
Install:
pip install langchain openai
Example
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
llm = OpenAI(model_name="gpt-3.5-turbo")
chatbot = ConversationChain(llm=llm)
response = chatbot.predict(input="Hi, what's the weather like?")
print(response)
LangChain supports memory, prompt engineering, and chaining tools.
54. What security concerns exist with deploying LLMs and GANs in production?
Answer:
Key security concerns include:
- Misinformation generation – LLMs may hallucinate or output false data.
- Bias and discrimination – Pretrained models may reflect harmful biases.
- Prompt injection attacks – Malicious prompts that override instructions.
- Data leakage – Unintentional reproduction of training data.
- Image misuse – Deepfakes or fake identity generation.
Mitigation:
- Use moderation filters (OpenAI, AWS).
- Limit prompt scope.
- Regularly monitor output and logs.
- Use watermarking in generated images.
55. How do you use Gradio or Streamlit to create a web UI for generative models?
Answer:
Gradio Example:
import gradio as gr
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
def generate_text(prompt):
return generator(prompt, max_length=50)[0]['generated_text']
gr.Interface(fn=generate_text, inputs="text", outputs="text").launch()
Streamlit Example:
import streamlit as st
from transformers import pipeline
st.title("Text Generator")
generator = pipeline("text-generation", model="gpt2")
prompt = st.text_input("Enter prompt:")
if prompt:
result = generator(prompt, max_length=50)
st.write(result[0]['generated_text'])
Both tools are great for demoing generative models with a user-friendly GUI.
56. How can you implement a recommendation system enhanced with Generative AI?
Answer:
You can use Generative AI to improve recommendations by:
- Generating personalized product descriptions based on user profiles.
- Generating synthetic user interaction data for model training.
- Using embeddings from LLMs for semantic similarity.
Example
from transformers import AutoTokenizer, AutoModel
import torch
# Get semantic vector of product description
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
inputs = tokenizer("Wireless noise-cancelling headphones", return_tensors="pt")
embedding = model(**inputs).last_hidden_state.mean(dim=1)
# Use this embedding for similarity-based recommendations
57. Explain how to use Google Colab to train and visualize generative models.
Answer:
Steps to use Google Colab:
- Go to: https://colab.research.google.com
- Use free GPU: Runtime > Change runtime type > GPU
- Train a GAN or GPT model:
!pip install torch torchvision matplotlib
- Sample code:
import torch
from torchvision.utils import make_grid
import matplotlib.pyplot as plt
# generate fake images from trained GAN
images = generator(torch.randn(64, latent_dim)).detach()
grid = make_grid(images, nrow=8, normalize=True).permute(1, 2, 0)
plt.imshow(grid)
plt.axis('off')
plt.show()
Colab provides GPU acceleration for free (limited hours).
58. How do you handle GPU/TPU memory optimization while training large generative models?
Answer:
Techniques for memory optimization:
- Use torch.cuda.empty_cache() to release memory.
- Use with torch.no_grad() during inference.
- Use mixed-precision training (torch.cuda.amp).
- Reduce batch size or resolution.
- Use gradient checkpointing.
Mixed precision example:
from torch.cuda.amp import GradScaler, autocast
scaler = GradScaler()
for data in dataloader:
optimizer.zero_grad()
with autocast():
output = model(data)
loss = loss_fn(output, target)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
59. What are ethical concerns around AI-generated content and how do you handle them?
Answer:
Handling:
- Apply content filters.
- Disclose AI involvement.
- Use audit trails and output logging.
- Train on curated, diverse datasets.
- Use AI ethics guidelines (e.g., by Google, UNESCO, OpenAI).
60. Explain how to build a multi-modal application that uses both text and image generation.
Answer:
Multi-modal applications combine text and image generation using models like CLIP, DALL·E, or BLIP.
Steps:
- Take text input (e.g., prompt from user).
- Generate image using Stable Diffusion.
- Generate caption or story using GPT or BLIP.
Example (Text → Image → Text):
# Generate image from text
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
image = pipe("A futuristic city at night").images[0]
# Caption the image
from transformers import BlipProcessor, BlipForConditionalGeneration
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
inputs = processor(images=image, return_tensors="pt")
caption_ids = model.generate(**inputs)
print(processor.decode(caption_ids[0], skip_special_tokens=True))