> ## Documentation Index
> Fetch the complete documentation index at: https://ai.tharung.in/llms.txt
> Use this file to discover all available pages before exploring further.

# COT Prompt example

## Problem Statement

1. Use **GPT-2** to solve a simple mathematical problem through text generation.
2. Apply **few-shot prompting and step-by-step reasoning** by providing solved examples before asking the model to solve a new problem.

```python theme={null}
# first 2 lines are to avoid warning messages from huggingface hub
import os

os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"

from transformers import pipeline

# 1. load the GPT 2 text generation model

generator = pipeline("text-generation", model="gpt2")

# 2. few shot chain-of-thought style prompt

prompt = """
Solve the math problems using the examples below.

Example 1:

Question:
If a person buys 3 notebooks for ₹20 each, what is the total cost?

Solution:
Each notebook costs ₹20.
Number of notebooks = 3.
Total cost = 3 × 20 = ₹60.

Final Answer: ₹60


Example 2:

Question:
If a student buys 5 pens for ₹10 each, what is the total cost?

Solution:
Each pen costs ₹10.
Number of pens = 5.
Total cost = 5 × 10 = ₹50.

Final Answer: ₹50


Now solve this problem:

Question:
A person buys 4 books for ₹25 each. What is the total cost?

Solution:
"""
# 3. generating response

result = generator(prompt, max_new_tokens=100, do_sample=False, pad_token_id=50256)

# 4. generated response - print

print(result[0]["generated_text"])
```

### 1. Import Pipeline

```python theme={null}
from transformers import pipeline
```

Imports the `pipeline` function from Hugging Face Transformers.

***

### 2. Load GPT-2

```python theme={null}
generator = pipeline("text-generation", model="gpt2")
```

Loads the GPT-2 model for text generation.

***

### 3. Few-Shot Prompt

```python theme={null}
prompt = """ ... """
```

The prompt contains **two solved examples** and one new math problem.

This demonstrates:

* **Few-shot prompting**: The model is given examples.
* **Step-by-step reasoning style**: The examples show how the problem should be solved.

***

### 4. Generate Response

```python theme={null}
result = generator(
    prompt,
    max_new_tokens=100,
    do_sample=False,
    pad_token_id=50256
)
```

* `prompt`: Input given to GPT-2.
* `max_new_tokens=100`: Generates up to 100 new tokens.
* `do_sample=False`: Makes generation more deterministic.
* `pad_token_id=50256`: Uses GPT-2's end-of-text token for padding.

***

### 5. Print Output

```python theme={null}
print(result[0]["generated_text"])
```

Prints the original prompt along with the text generated by GPT-2.

## Flow

```text theme={null}
Few-Shot Examples
        ↓
New Math Problem
        ↓
GPT-2 Text Generation
        ↓
Generated Response
```
