Mistral AI의 프롬프팅 능력

Mistral AI의 프롬프팅 능력 (Prompting Capabilities with Mistral AI)

Mistral 모델을 처음 사용할 때 다루는 프롬프트의 핵심 능력을 배우는 문서예요. 분류(Classification), 요약(Summarization), 개인화(Personalization), 평가(Evaluation) 네 가지 프롬프팅 능력을 예시로 알아봐요.

출처: 문서

본문

Mistral 모델을 처음 사용하기 시작하면, 첫 상호작용은 프롬프트를 중심으로 이뤄져요. 효과적인 프롬프트를 만드는 기술은 Mistral 모델이나 다른 LLM에서 바람직한 응답을 생성하는 데 필수적이에요. 이 가이드는 네 가지 프롬프팅 능력을 보여주는 예시 프롬프트를 안내해요:

  • Classification (분류)
  • Summarization (요약)
  • Personalization (개인화)
  • Evaluation (평가)
! pip install mistralai
from mistralai.client import Mistral
api_key = "TYPE YOUR API KEY"
def run_mistral(user_message, model="mistral-large-latest"):
    client = Mistral(api_key=api_key)
    messages = [
        {"role":"user", "content":user_message}
    ]
    chat_response = client.chat.complete(
        model=model,
        messages=messages
    )
    return (chat_response.choices[0].message.content)

분류 (Classification)

Mistral 모델은 텍스트를 개별 클래스로 쉽게 분류할 수 있어요. 이 예시 프롬프트에서는 미리 정의된 카테고리 목록을 만들고 Mistral 모델에 사용자 문의를 분류하도록 요청해요.

def user_message(inquiry):
    user_message = (
        f"""
        You are a bank customer service bot. Your task is to assess customer intent
        and categorize customer inquiry after <<<>>> into one of the following predefined categories:

        card arrival
        change pin
        exchange rate
        country support
        cancel transfer
        charge dispute

        If the text doesn't fit into any of the above categories, classify it as:
        customer service

        You will only respond with the predefined category. Do not include the word "Category". Do not provide explanations or notes.

        ####
        Here are some examples:

        Inquiry: How do I know if I will get my card, or if it is lost? I am concerned about the delivery process and would like to ensure that I will receive my card as expected. Could you please provide information about the tracking process for my card, or confirm if there are any indicators to identify if the card has been lost during delivery?
        Category: card arrival
        Inquiry: I am planning an international trip to Paris and would like to inquire about the current exchange rates for Euros as well as any associated fees for foreign transactions.
        Category: exchange rate
        Inquiry: What countries are getting support? I will be traveling and living abroad for an extended period of time, specifically in France and Germany, and would appreciate any information regarding compatibility and functionality in these regions.
        Category: country support
        Inquiry: Can I get help starting my computer? I am having difficulty starting my computer, and would appreciate your expertise in helping me troubleshoot the issue.
        Category: customer service
        ###

        <<<
        Inquiry: {inquiry}
        >>>
        """
    )
    return user_message

사용한 전략:

  • Few shot learning (few-shot/in-context learning): 프롬프트에 몇 가지 예시를 주고, LLM이 그 예시를 바탕으로 대응 출력을 생성하게 하는 방식이에요. 특히 과제가 어렵거나 모델이 특정 방식으로 응답하길 원할 때 성능을 높일 수 있어요.
  • Delimiter (구분자): ###, <<<, >>> 같은 구분자는 텍스트의 서로 다른 섹션 경계를 지정해요. 예시에서는 ###로 예시를, <<<>>>로 고객 문의를 구분했어요.
  • Role playing (역할 부여): LLM에 역할을 부여하면(예: "You are a bank customer service bot.") 모델에 개인적 맥락을 더해 더 나은 성능을 이끌어내요.
print(run_mistral(user_message(
    "I am inquiring about the availability of your cards in the EU, as I am a resident of France and am interested in using your cards. "
)))
print(run_mistral(user_message("What's the weather today?")))

요약 (Summarization)

요약은 LLM의 자연어 이해·생성 능력 덕분에 흔한 작업이에요. 에세이에 대한 흥미로운 질문을 만들고 에세이를 요약하는 예시 프롬프트를 볼게요.

import requests
response = requests.get('https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt')
essay = response.text
message = f"""
You are a commentator. Your task is to write a report on an essay.
When presented with the essay, come up with interesting questions to ask, and answer each question.
Afterward, combine all the information and write a report in the markdown format.

# Essay:
{essay}

# Instructions:
## Summarize:
In clear and concise language, summarize the key points and themes presented in the essay.

## Interesting Questions:
Generate three distinct and thought-provoking questions that can be asked about the content of the essay. For each question:
- After "Q: ", describe the problem
- After "A: ", provide a detailed explanation of the problem addressed in the question.
- Enclose the ultimate answer in <>.

## Write a report
Using the essay summary and the answers to the interesting questions, create a comprehensive report in Markdown format.
"""
print(run_mistral(message))

사용한 전략:

  • Step-by-step instructions (단계별 지시): chain-of-thought 프롬프팅에서 영감을 받은 전략으로, LLM이 복잡한 작업을 해결하기 위해 일련의 중간 추론 단계를 사용하게 해요. 작업을 더 단순하고 작은 단계로 분해하면 더 쉽게 풀고, 모델 동작을 디버깅·검사하기도 쉬워요. 예시에서는 요약 → 흥미로운 질문 생성 → 보고서 작성 세 단계로 나눴어요.
  • Example generation (예시 생성): LLM에 설명과 단계가 있는 예시를 생성하도록 요청해 추론·이해 과정을 자동으로 유도할 수 있어요.
  • Output formatting (출력 형식): "write a report in the Markdown format"처럼 직접 요청해 특정 형식으로 출력하게 할 수 있어요.

개인화 (Personalization)

LLM은 개별 사용자와 밀접하게 일치하는 콘텐츠를 전달할 수 있어 개인화 작업에 탁월해요. 이 예시에서는 고객 질문에 대응하는 개인화된 이메일 응답을 만들어요.

email = """
Dear mortgage lender,

What's your 30-year fixed-rate APR, how is it compared to the 15-year fixed rate?

Regards,
Anna
"""
message = f"""

You are a mortgage lender customer service bot, and your task is to create personalized email responses to address customer questions.
Answer the customer's inquiry using the provided facts below. Ensure that your response is clear, concise, and
directly addresses the customer's question. Address the customer in a friendly and professional manner. Sign the email with
"Lender Customer Support."

# Facts
30-year fixed-rate: interest rate 6.403%, APR 6.484%
20-year fixed-rate: interest rate 6.329%, APR 6.429%
15-year fixed-rate: interest rate 5.705%, APR 5.848%
10-year fixed-rate: interest rate 5.500%, APR 5.720%
7-year ARM: interest rate 7.011%, APR 7.660%
5-year ARM: interest rate 6.880%, APR 7.754%
3-year ARM: interest rate 6.125%, APR 7.204%
30-year fixed-rate FHA: interest rate 5.527%, APR 6.316%
30-year fixed-rate VA: interest rate 5.684%, APR 6.062%

# Email
{email}
"""
print(run_mistral(message))

사용한 전략:

  • Providing facts (사실 제공): 프롬프트에 사실을 포함하는 것은 고객 지원 봇 개발에 유용해요. 이 사실들을 제시할 때는 명확하고 간결한 언어를 쓰는 게 중요하며, LLM이 고객 질문에 정확하고 빠르게 응답하도록 도와줘요.

평가 (Evaluation)

LLM 출력을 평가하는 방법은 다양해요. 신뢰도 점수 포함, 평가 단계 도입, 또는 다른 LLM을 평가에 사용하는 세 가지 접근법을 살펴볼게요.

신뢰도 점수 포함 (Include a confidence score)

생성된 출력과 함께 신뢰도 점수를 프롬프트에 포함할 수 있어요.

def run_mistral(user_message, model="mistral-large-latest"):
    client = Mistral(api_key=api_key)
    messages = [
        {
            "role":"user",
            "content": user_message
        }
    ]
    chat_response = client.chat.complete(
        model=model,
        messages=messages,
        temperature=1,
        response_format = {
            "type": "json_object"
        }
    )
    return (chat_response.choices[0].message.content)
message = f"""
You are a summarization system that can provide summaries with associated confidence scores.
In clear and concise language, provide three short summaries of the following essay, along with their confidence scores.
You will only respond with a JSON object with the key Summary and Confidence. Do not provide explanations.

# Essay:
{essay}


"""
print(run_mistral(message))

사용한 전략:

  • JSON output: 다운스트림 작업을 위해 JSON 형식 출력이 자주 선호돼요. response_format을 {"type": "json_object"}로 설정해 JSON 모드를 켜고, 프롬프트에서 "You will only respond with a JSON object with the key Summary and Confidence."라고 지정할 수 있어요. JSON 객체 안의 키를 지정하면 명확성과 일관성에 유리해요.
  • Higher Temperature: 이 예시에서는 모델이 더 창의적이고 서로 다른 세 개의 요약을 생성하도록 temperature 점수를 높였어요.

평가 단계 도입 (Introduce an evaluation step)

프롬프트에 두 번째 평가 단계를 추가할 수도 있어요.

message = f"""
You are given an essay text and need to provide summaries and evaluate them.

# Essay:
{essay}

Step 1: In this step, provide three short summaries of the given essay. Each summary should be clear, concise, and capture the key points of the speech. Aim for around 2-3 sentences for each summary.
Step 2: Evaluate the three summaries from Step 1 and rate which one you believe is the best. Explain your choice by pointing out specific reasons such as clarity, completeness, and relevance to the speech content.


"""
print(run_mistral(message))

다른 LLM을 평가에 사용 (Employ another LLM for evaluation)

프로덕션 시스템에서는 평가 단계를 생성 단계와 분리하기 위해 다른 LLM을 평가에 사용하는 것이 일반적이에요.

Step 1: 첫 번째 LLM으로 세 개의 요약을 생성해요.

message = f"""
Provide three short summaries of the given essay. Each summary should be clear, concise, and capture the key points of the essay.
Aim for around 2-3 sentences for each summary.

# essay:
{essay}


"""
summaries = run_mistral(message)
print(summaries)

Step 2: 다른 LLM으로 생성된 요약에 점수를 매겨요.

message = f"""
You are given an essay and three summaries of the essay. Evaluate the three summaries and rate which one you believe is the best.
Explain your choice by pointing out specific reasons such as clarity, completeness, and relevance to the essay content.

# Essay:
{essay}

# Summaries
{summaries}


"""
print(run_mistral(message))

사용한 전략:

  • LLM chaining (LLM 체이닝): 두 LLM을 순서대로 연결해 첫 번째 LLM의 출력이 두 번째 LLM의 입력이 되게 하는 방식이에요. 특정 사용 사례에 맞게 조정할 수 있으며, 예를 들어 두 LLM의 출력을 세 번째 LLM으로 보내는 3-LLM 체인을 쓸 수도 있어요. 유연하지만 API 호출이 늘어나 비용이 증가할 수 있다는 점을 고려해야 해요.

더 알아보기 (Learn more)