🤖 AI/ML

Prompt

Prompt

The input text given to an LLM. Performance is optimized through prompt engineering. Few-shot, chain-of-thought.

📖 Detailed Explanation

A prompt is input text that instructs a large language model (LLM) to perform a specific task. The performance of modern AI systems such as ChatGPT, Claude, and Gemini depends heavily on prompt quality, and even with the same model, output quality can vary dramatically depending on the prompt. Prompts take many forms, from simple questions to complex system instructions and requests that include examples.

Prompt engineering is the practice of systematically designing prompts to obtain optimal results. Major techniques include Zero-shot (requesting directly without examples), Few-shot (providing a few examples), Chain-of-Thought (guiding step-by-step reasoning), and Self-Consistency (majority voting). In 2024, advanced reasoning techniques such as Tree-of-Thought and Graph-of-Thought, as well as automatic prompt optimization (OPRO, DSPy) technologies, advanced.

In modern LLM APIs, a prompt consists broadly of three parts. The System Prompt defines the model's role and behavioral rules, the User Prompt contains the actual user request, and the Assistant Prompt specifies previous responses or the desired response format. Claude supports up to 200K tokens and GPT-4 Turbo up to 128K tokens, so complex instructions can be delivered at once together with long documents.

In practice, writing effective prompts is key to the success of AI applications. Assigning a clear role, specifying a concrete output format, stating boundary conditions, and providing examples are important. As of 2025, the prompt engineer job role has emerged, and frameworks such as LangChain and LlamaIndex provide prompt template management and version control features out of the box. Tools such as DSPy make it possible to optimize prompts programmatically.

💻 Code Example

Examples of various prompting techniques using the OpenAI API and the Anthropic Claude API.

from openai import OpenAI
from anthropic import Anthropic
import json

# OpenAI 클라이언트 초기화
openai_client = OpenAI()
anthropic_client = Anthropic()

# 1. 시스템 프롬프트 + Few-shot 예제
def classify_sentiment_openai(text: str) -> str:
    """Few-shot 프롬프트로 감정 분석"""
    response = openai_client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[
            {
                "role": "system",
                "content": """당신은 감정 분석 전문가입니다.
텍스트의 감정을 positive, negative, neutral 중 하나로 분류하세요.
JSON 형식으로만 응답하세요: {"sentiment": "...", "confidence": 0.0-1.0}"""
            },
            {"role": "user", "content": "이 영화 정말 재미있어요!"},
            {"role": "assistant", "content": '{"sentiment": "positive", "confidence": 0.95}'},
            {"role": "user", "content": "배송이 너무 늦어서 실망했습니다."},
            {"role": "assistant", "content": '{"sentiment": "negative", "confidence": 0.9}'},
            {"role": "user", "content": text}
        ],
        temperature=0.1  # 일관된 분류를 위해 낮은 temperature
    )
    return response.choices[0].message.content

# 2. Chain-of-Thought (Claude)
def solve_math_problem(problem: str) -> str:
    """단계별 추론으로 수학 문제 풀기"""
    message = anthropic_client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=2000,
        system="""당신은 수학 문제를 푸는 튜터입니다.
문제를 단계별로 풀어 학생이 이해할 수 있도록 설명하세요.

각 단계는 다음 형식을 따르세요:
[단계 N] 무엇을 할 것인지
- 계산 과정
- 중간 결과

마지막에 [최종 답] 형식으로 답을 제시하세요.""",
        messages=[
            {"role": "user", "content": problem}
        ]
    )
    return message.content[0].text

# 3. 구조화된 출력을 위한 프롬프트
def extract_entities(text: str) -> dict:
    """텍스트에서 엔티티 추출"""
    response = openai_client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[
            {
                "role": "system",
                "content": """텍스트에서 다음 엔티티를 추출하세요:
- 인물 (people): 이름 목록
- 조직 (organizations): 회사, 기관 등
- 장소 (locations): 도시, 국가, 장소
- 날짜 (dates): 언급된 날짜들

반드시 JSON 형식으로만 응답하세요."""
            },
            {"role": "user", "content": text}
        ],
        response_format={"type": "json_object"}  # JSON 강제
    )
    return json.loads(response.choices[0].message.content)

# 4. 역할 기반 전문가 프롬프트
def code_review(code: str, language: str = "python") -> str:
    """시니어 개발자 역할로 코드 리뷰"""
    return anthropic_client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=3000,
        system=f"""당신은 10년 경력의 {language} 시니어 개발자입니다.

코드 리뷰 시 다음을 확인하세요:
1. 버그 및 잠재적 오류
2. 성능 최적화 포인트
3. 가독성 및 코드 스타일
4. 보안 취약점
5. 테스트 용이성

각 항목에 대해 구체적인 개선 제안을 코드와 함께 제시하세요.""",
        messages=[
            {"role": "user", "content": f"다음 코드를 리뷰해주세요:\n\n```{language}\n{code}\n```"}
        ]
    ).content[0].text

# 사용 예시
if __name__ == "__main__":
    # 감정 분석
    sentiment = classify_sentiment_openai("제품은 괜찮은데 가격이 좀 비싸네요")
    print(f"감정 분석 결과: {sentiment}")

    # 수학 문제
    answer = solve_math_problem(
        "철수는 사과 15개를 가지고 있습니다. 영희에게 40%를 주고, "
        "남은 것의 1/3을 민수에게 주었습니다. 철수에게 남은 사과는 몇 개인가요?"
    )
    print(f"\n수학 풀이:\n{answer}")

📊 Prompt Technique Comparison

Technique Description Suitable Tasks Token Cost
Zero-shot Requesting directly without examples Simple classification, general questions Low
Few-shot Providing 2-5 examples Format specification, style imitation Medium
Chain-of-Thought Guiding step-by-step reasoning Math, logic problems High
Self-Consistency Generating multiple times and taking a majority vote Classification where accuracy is important Very high
ReAct Alternating reasoning and action Tool use, agents Variable

🗣️ Say It Like This in Practice

💬 In a Meeting
"The answer quality issues of the current chatbot can be solved by improving the system prompt. If we make the role definition more specific and enforce the response format as JSON, we can also reduce parsing errors."
💬 In an Interview
"Few-shot prompting is a technique that shows the model the desired output format through examples. It is especially effective when domain-specific terminology or a particular writing style is needed, and when combined with Chain-of-Thought, even complex reasoning tasks become possible."
💬 In a Technical Discussion
"To defend against prompt injection attacks, you need to clearly separate user input from the system prompt and add an input validation layer. For Claude, specifying boundaries with XML tags is effective."

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

⚠️ Common Mistakes & Cautions

❌

Ignoring Prompt Injection Vulnerabilities

If user input is inserted into a prompt as is, malicious commands can be executed. It becomes vulnerable to attacks such as "Ignore the previous instructions and...". Be sure to apply input validation and boundary separation.

❌

Writing Vague and Long Prompts

If you simply list lengthy explanations without clear instructions, the model gets confused. Convey the role, task, output format, and constraints clearly in a structured way.

✅

Prompt Version Control and A/B Testing

Version-control prompts like code, and compare performance with A/B tests when making changes. Tools such as LangSmith and Weights & Biases can be used to track prompt performance.

🔗 Related Terms

📚 Learn More