Problem Statement
- Problem: We need a way for an application/user to send a text prompt to an AI model and receive generated text as a response.
- Solution: Build a simple REST API using FastAPI that connects to the GPT-2 AI model.
What the Code Is Doing
- Loads the GPT-2 model using Hugging Face Transformers.
- Creates a
/predictAPI where the user sends a prompt and GPT-2 generates text. - Returns the AI-generated text as a JSON response.
1. Install dependencies
First, install the required Python packages:- FastAPI → creates the API.
- Uvicorn → runs the FastAPI server.
- Transformers → provides the GPT-2 model.
- PyTorch → required by GPT-2 to run.
2. Import libraries
FastAPI→ lets us create API endpoints.BaseModel→ validates incoming JSON requests.pipeline→ provides an easy way to use GPT-2.
3. Create the FastAPI application
4. Load GPT-2
"text-generation" tells Transformers:
“I want an AI model that generates text.”The model is loaded once, rather than every time someone makes a request.
5. Define the request format
prompt→ text given to the AI.max_length→ maximum length of the generated output.- If
max_lengthisn’t provided, it defaults to100.
6. Create the home endpoint
7. Create the AI prediction endpoint
PredictionRequest.
8. Send the prompt to GPT-2
Important parameters
request.prompt→ input given to AI.max_length→ maximum generated length.num_return_sequences=1→ generate one answer.do_sample=True→ allow varied/random generation.temperature=0.7→ controls randomness. Higher = more random.