Skip to main content

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 /predict API 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

This creates your API application. The API will have the title GPT-2 API.

4. Load GPT-2

This loads the GPT-2 AI model. "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

This defines what the client should send. For example:
  • prompt → text given to the AI.
  • max_length → maximum length of the generated output.
  • If max_length isn’t provided, it defaults to 100.

6. Create the home endpoint

When someone visits:
the API responds:
This is mainly a simple way to check that the server is working.

7. Create the AI prediction endpoint

This creates:
The API expects a JSON request matching PredictionRequest.

8. Send the prompt to GPT-2

This is where the AI actually generates text. For example, the user sends:
GPT-2 receives the prompt and predicts what text should come next.

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.

9. Return the AI response

The API sends the original prompt and AI-generated text back to the client. Example response:

10. Run the API

Save the file as:
Then run:
You should see something like:
Open:
You should get:

11. How the AI API works overall

Request

AI

GPT-2 takes:
and predicts the next tokens/words based on what it learned during training.

Response

In short: FastAPI is the server/API, GPT-2 is the AI, the prompt is the input, and the generated text is the AI output.