🤖 AI/ML

GPT

Generative Pre-trained Transformer

OpenAI's large language model. Generates text autoregressively.

📖 Detailed Explanation

GPT (Generative Pre-trained Transformer) is a series of autoregressive language models developed by OpenAI. Starting with GPT-1 (117M parameters) in 2018, it has evolved through GPT-2 (1.5B) and GPT-3 (175B) to GPT-4, and is pre-trained by predicting the next token on large-scale text data.

GPT's core architecture uses only the decoder portion of the Transformer. Given an input sequence, it generates the next token by referring only to previous tokens through masked self-attention. Unlike BERT, which uses a bidirectional encoder, GPT is a unidirectional decoder specialized for text generation.

GPT models are trained in two stages. First, they are pre-trained on a large-scale text corpus (web pages, books, wikis, etc.), and then fine-tuned to match human preferences using RLHF (Reinforcement Learning from Human Feedback). ChatGPT is a version of GPT-3.5 with InstructGPT techniques applied.

In practice, GPT is used through the OpenAI API. Various models such as gpt-4, gpt-4-turbo, and gpt-3.5-turbo are offered, and pricing is set per token (based on GPT-4 Turbo: input $10/1M tokens, output $30/1M tokens). A 128K context window also makes it possible to process long documents.

💻 Code Example

from openai import OpenAI

client = OpenAI(api_key="your-api-key")

# 기본 Chat Completion
response = client.chat.completions.create(
    model="gpt-4-turbo",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Python에서 리스트 컴프리헨션을 설명해주세요."}
    ],
    temperature=0.7,
    max_tokens=500
)
print(response.choices[0].message.content)

# 스트리밍 응답
stream = client.chat.completions.create(
    model="gpt-4-turbo",
    messages=[{"role": "user", "content": "AI의 미래에 대해 설명해주세요."}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

# Function Calling (도구 사용)
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["location"]
        }
    }
}]

response = client.chat.completions.create(
    model="gpt-4-turbo",
    messages=[{"role": "user", "content": "서울 날씨 알려줘"}],
    tools=tools,
    tool_choice="auto"
)

# JSON 모드
response = client.chat.completions.create(
    model="gpt-4-turbo",
    messages=[
        {"role": "system", "content": "You output JSON only."},
        {"role": "user", "content": "List 3 programming languages with their use cases."}
    ],
    response_format={"type": "json_object"}
)

# 토큰 수 확인
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4")
text = "Hello, how are you?"
tokens = encoding.encode(text)
print(f"Token count: {len(tokens)}")  # 5 tokens

🗣️ Say It Like This in Practice

Technical Interview Scenario

"Can you explain the difference between GPT and BERT?" - "GPT is a unidirectional decoder specialized for text generation, while BERT is a bidirectional encoder optimized for text understanding. GPT is trained by next-token prediction, while BERT is trained by masked language modeling and next sentence prediction. GPT is better suited to generation tasks, and BERT to classification and QA."

Project Meeting

"Which is better to use, GPT-4 or GPT-3.5?" - "If cost efficiency matters, GPT-3.5-turbo is 20 times cheaper. However, if you need complex reasoning, code generation, or a long context, GPT-4 is clearly superior. I recommend building an MVP with GPT-3.5 first, and upgrading only the parts where quality falls short to GPT-4."

Code Review

"Is there a reason you set temperature to 0?" - "Yes, this API is for customer support automation, so consistent responses are important. With temperature 0, greedy decoding selects only the highest-probability token, which guarantees reproducibility. For creative content generation, around 0.7-0.9 is appropriate."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Token Cost Management

GPT-4 charges for both input and output tokens. Because the system prompt is included in every request, a long one causes costs to surge. Calculate the token count in advance with tiktoken, and optimize with summarization or chunking when necessary.

2
Beware of Hallucinations

GPT can confidently generate incorrect information. For uses where fact-checking is important, apply RAG (Retrieval-Augmented Generation), or request source citations and add verification steps.

3
Handling Rate Limits

The OpenAI API has limits on requests per minute (RPM) and tokens per minute (TPM). When processing large volumes, implement exponential backoff and retry logic, and apply for a Usage Tier upgrade if necessary.

🔗 Related Terms

📚 Learn More