크크루쿠쿠

Prompt Engineering Guide 2. Basic Prompting 본문

DeepLearning/공부

Prompt Engineering Guide 2. Basic Prompting

JH_KIM 2023. 5. 2. 03:38

이 글은 https://github.com/dair-ai/Prompt-Engineering-Guide 를 공부하기 위해 제 입맛대로 번역한 글입니다


    Basic Prompting

    전에는 기본적인 예시를 소개했었습니다.

    이번 회차에는 프롬프트가 어떻게 쓰이는지에 대한 많은 예시와 고급 가이드에서 중요하게 다룰 핵심 개념을 소개합니다.

    예시를 보는 건 종종 best way이기 때문에 우리는 잘 만들어진 prompt로 예시를 이용해 잘 공부해 봅시다.


     

    Text Summarization

    가장 흔한 언어 모델에서의 task입니다. 다양한 분야와 유형이 포함될 수 있으며 가장 유망한 응용 분야는 기사 같은 것들을 빠르고 쉽게 요약하는 것입니다.

    한번 항생제에 대해 배우고 싶다 가정하면 다음과 같은 프롬프트를 작성해 볼 수 있습니다.

    Prompt:
    Explain antibiotics
    
    Output:
    Antibiotics are medications used to treat infections caused by bacteria.
    They work by either killing the bacteria or inhibiting their growth. 
    In some cases, antibiotics may be used to prevent infections from occurring. 
    Antibiotics are usually prescribed by a doctor and should only be taken as directed. 
    Taking antibiotics without a prescription can lead to antibiotic resistance
    , which can make it difficult to treat future infections.

    "A:" 는 QA에 사용하는 명시적 프롬프트입니다. 여기서는 모델이 좀 더 얘기하게끔 이 형식을 사용했습니다. 이 예시에서는 이 방법이 유용할 때와 vs 유용하지 않을 때의 차이가 명확하지 않지만 나중에 다른 예시에서 보여드리겠습니다.

    정보가 너무 많아 요약을 하고 싶다 가정하면 다음과 같이 지시할 수 있습니다.

    Prompt:
    Antibiotics are medications used to treat infections caused by bacteria.
    They work by either killing the bacteria or inhibiting their growth. 
    In some cases, antibiotics may be used to prevent infections from occurring. 
    Antibiotics are usually prescribed by a doctor and should only be taken as directed. 
    Taking antibiotics without a prescription can lead to antibiotic resistance
    , which can make it difficult to treat future infections.
    
    Explain the above in one sentence:
    
    Output:
    Antibiotics are medications used to treat bacterial infections by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection.

    나중에 할 accuracy에 많은 집중을 하지 않고 했습니다. 이 모델은 단락을 한 문장으로 요약했습니다. instruction을 이용해 더 좋은 결과물을 만들 수 있지만 그건 다음 장에서 다루도록 하겠습니다.

     

    Information Extraction

    언어 모델은 자연어 생성 관련해서 학습이 되지만 classification이나 기타 다른 다양한 작업도 가능합니다.

    다음은 주어진 단락에서 정보를 추출하는 프롬프트의 예입니다.

    Prompt:
    Author-contribution statements and acknowledgements in research papers should state clearly and specifically whether
    , and to what extent, the authors used AI technologies such as ChatGPT in the preparation of their manuscript and analysis. 
    They should also indicate which LLMs were used. 
    This will alert editors and reviewers to scrutinize manuscripts more carefully for potential biases, inaccuracies and improper source crediting. 
    Likewise, scientific journals should be transparent about their use of LLMs, for example when selecting submitted manuscripts.
    
    Mention the large language model based product mentioned in the paragraph above:
    
    Output:
    The large language model based product mentioned in the paragraph above is ChatGPT.

    아까와 같이 개선할 방법은 무궁무진하지만 이 방법은 이미 유용합니다.

    이제 모델에 다양한 task를 수행가능한 것은 분명히 봤습니다. 이는 이미 AI product builder들이 강력한 제품과 경험을 하는 데 사용하는 기능입니다.

    Question Answering

    모델이 특정 답변에 응답하도록 하는 가장 좋은 방법은 prompt의 format을 개선시키는 것입니다.

    다음은 좀 더 instruct가 반영된 프롬프트의 예시입니다.

    Prompt:
    Answer the question based on the context below. 
    Keep the answer short. Respond "Unsure about answer" if not sure about the answer.
    
    Context: Teplizumab traces its roots to a New Jersey drug company called Ortho Pharmaceutical. 
    There, scientists generated an early version of the antibody, dubbed OKT3. 
    Originally sourced from mice, the molecule was able to bind to the surface of T cells and limit their cell-killing potential. 
    In 1986, it was approved to help prevent organ rejection after kidney transplants, making it the first therapeutic antibody allowed for human use.
    
    Question: What was OKT3 originally sourced from?
    
    Answer:
    
    Output:
    Mice.

     

    Text Classification

    지금까지는 간단한 instruction을 이용해 작업을 수행했습니다. Prompt engineer라면 더 좋은 instruction을 쓰는 거에 익숙해져야 합니다. 그게 전부가 아니라 더 어려운 경우에는 instruction만으로는 충분하지 않다는 것을 알게 될 것입니다. 이때는 context와 다양한 요소에 대해 더 많이 생각해야 합니다. 다른 요소로는 input data나 예시등이 있습니다.

    텍스트 분류의 예를 들어 이를 설명해 보겠습니다.

    Prompt:
    Classify the text into neutral, negative or positive. 
    
    Text: I think the food was okay. 
    Sentiment:
    
    Output:
    Neutral

    텍스트를 분류하라는 instruction을 줬고 Netural이라는 정답을 줬습니다. 문제가 있는 건 아니지만 만약 실제로 correct 한 fromat의 label을 원할 경우를 가정해 봅시다. 'Netural' 대신 'neutral'을 원할 경우에는 어떻게 해야 할까요?

    여러 방법이 있겠지만 여기서 우리는 specificity를 집중해서 보면, 프롬프트에 더 많은 정보를 제공할수록 더 좋은 결과를 제공합니다. 정확한 행동을 위해 예제를 제공해 봅시다.

     

    Prompt:
    Classify the text into neutral, negative or positive. 
    
    Text: I think the vacation is okay.
    Sentiment: neutral 
    
    Text: I think the food was okay. 
    Sentiment:
    
    Output:
    neutral

     

    (개인 실험)

    Prompt:
    Classify the text into neutral, negative or positive. And answer is must be lowercase
    
    Text: I think the food was okay. 
    Sentiment:
    
    Output:
    neutral

     

    Conversation

    프롬프트 엔지니어링을 통해 얻을 수 있는 가장 흥미로운 점 중 하나는 LLM에게 작동 방식, 의도, identity를 instructing 할 수 있는 것입니다. 이 점은 conversation system을 구축할 때 매우 유용합니다.

    예를 들어 질문에 대해 보다 기술적이고 과학적인 답변을 생성할 수 있는 대화형 시스템을 만든다고 가정해 봅시다. 지시를 통해 어떻게 행동해야 하는지 명시적으로 알려주고 있다는 점에 주목하세요. 이를 역할 프롬프트라고도 합니다.

    Prompt:
    The following is a conversation with an AI research assistant. 
    The assistant tone is technical and scientific.
    
    Human: Hello, who are you?
    AI: Greeting! I am an AI research assistant. How can I help you today?
    Human: Can you tell me about the creation of blackholes?
    AI:
    
    Output:
    Sure! Black holes are regions of spacetime where the gravitational force is so strong that nothing, not even light, can escape from it. 
    They are created when a very massive star dies and its core collapses in on itself, forming a singularity of infinite density. 
    The intense gravity of the singularity pulls in all the matter and radiation around it, creating the black hole.

    꽤 technical하게 들립니다. 이제 좀 더 시스템이 쉽게 접근할 수 있는 답변을 제공하도록 instruct 해보겠습니다.

    Prompt:
    The following is a conversation with an AI research assistant. 
    The assistant answers should be easy to understand even by primary school students.
    
    Human: Hello, who are you?
    AI: Greeting! I am an AI research assistant. How can I help you today?
    Human: Can you tell me about the creation of black holes?
    AI: 
    
    Output:
    Sure! Black holes are created when a very massive star runs out of fuel and collapses in on itself. 
    The gravity of the star is so strong that nothing, not even light, can escape its pull. 
    This creates a point in space-time with an intense gravitational force called a black hole.

     

    Code Generation

    LLM에서 또 매우 효과적인 application 중 하나는 code generation입니다. 코파일럿이 좋은 예시입니다. clever 한 promps가 있다면 code generation task는 무궁무진해집니다.

    먼저 사용자를 맞아주는 간단한 프로그램을 시도해 봅시다.

    Prompt:
    /*
    Ask the user for their name and say "Hello"
    */
    
    Output:
    let name = prompt("What is your name?");
    console.log(`Hello, ${name}!`);

    보다시피 우리는 특정 언어를 지정해주지 않았다는 것을 알 수 있습니다.

    살짝 level을 올려서 좀만 더 노력하면 얼마나 LLM이 강력해지는지 보여드리겠습니다.

    Prompt:
    """
    Table departments, columns = [DepartmentId, DepartmentName]
    Table students, columns = [DepartmentId, StudentId, StudentName]
    Create a MySQL query for all students in the Computer Science Department
    """
    
    Output:
    SELECT StudentId, StudentName 
    FROM students 
    WHERE DepartmentId IN (SELECT DepartmentId FROM departments WHERE DepartmentName = 'Computer Science');

    이 경우 데이터베이스 스키마에 대한 데이터를 제공하고 유효한 MySQL 쿼리를 생성하도록 요청했습니다.

    Reasoning

    오늘날 LLM에게 가장 어려운 task는 아마 reasoning 일 것입니다.

    Reasoning은 LLM에서 가장 복잡한 application의 유형으로 가장 기대되는 분야 중 하나입니다.

    수학적 능력에 대해서는 약간의 개선이 있었습니다. (GPT-4 부터는 큰 개선이 있습니다.) 현재는 어려움을 겪고 있기 때문에 더욱 발전된 prompt engineering 기술이 필요합니다. 다음 guide에서 그것에 대해 좀 더 알아보겠습니다.

    일단 지금은 basic example로 살펴봅시다.

     

    Prompt:
    What is 9,000 * 9,000?
    
    Output:
    81,000,000

    이제 좀 더 어려운 문제를 줘봅시다.

    (개인적으로 사람인 저도 문제를 이해 못 했습니다..)

    Prompt:
    The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. 
    
    A: 
    
    Output
    No, the odd numbers in this group add up to an odd number: 119.

    정말 엉뚱한 답을 내놓습니다! prompt를 개선시켜 더 개선시켜 봅시다

     

    Prompt:
    The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. 
    
    Solve by breaking the problem into steps. 
    First, identify the odd numbers, add them, and indicate whether the result is odd or even. 
    
    Output:
    Odd numbers: 15, 5, 13, 7, 1
    Sum: 41 
    41 is an odd number.

    좀 더 나은 모습을 볼 수 있습니다. 이렇게 step by step으로 어떻게 사고해야 할지 알려주면서 하면 좀 더 나은 모습을 볼 수 있습니다.

    Comments