프롬프트 엔지니어링 실제 사례

2024. 1. 23. 18:01python/intermediate

 

도구 준비

여기에서는 LLM 지원 프로젝트에서 더 나은 텍스트 완성을 얻는 데 사용할 수 있는 프롬프트를 반복적으로 개발하는 접근 방식과 함께 몇 가지 프롬프트 엔지니어링 기술을 다룹니다.

  • Zero-Shot Prompting
  • Few-Shot Prompting
  • Delimiters
  • Numbered Steps
  • Increased Specificity
  • Role Prompts
  • Chain-of-Thought (CoT) Prompting
  • Structured Output
  • Labeled Conversations

더 많은 프롬프트 기술이 있으며 추가 리소스에 대한 링크도 찾을 수 있습니다. 실제 사례에서 언급된 기술을 적용하면 LLM 지원 프로그램을 개선하기 위한 훌륭한 출발점이 될 것입니다. 이전에 LLM을 사용해 본 적이 없다면 시작하기 전에 OpenAI의 GPT 문서를 정독하고 싶을 수도 있지만 어느 쪽이든 따라갈 수 있어야 합니다.

get_completion()은 OpenAI의 GPT-3.5 모델(text-davinci-003)과 상호작용하여 completions 엔드포인트를 사용하여 응답을 생성하고, get_chat_completion()는 OpenAI의 GPT-4 모델(gpt-4)과 상호작용하여 chat/completions 엔드포인트를 사용하여 응답을 생성합니다.

샘플 코드 의 핵심은 settings.toml입니다. 이 TOML 설정 파일은 프롬프트 엔지니어링 기술을 연마하는 데 사용할 프롬프트를 호스팅합니다. 여기에는 사람이 읽을 수 있는 설정 형식인 TOML로 구성된 다양한 프롬프트가 포함되어 있습니다.

전용 설정 파일에 메시지를 보관하면 해당 메시지를 버전 제어하에 두는 데 도움이 될 수 있습니다. 개발 중에 필연적으로 변경되는 메시지입니다.

Python 스크립트는 settings.toml의 프롬프트를 읽고 이를 API 요청으로 보냅니다.

또는 OpenAI 플레이그라운드에서 모든 텍스트 프롬프트를 직접 실행할 수도 있습니다. 그러면 스크립트와 동일한 기능이 제공됩니다. ChatGPT 인터페이스에 메시지를 붙여넣을 수도 있습니다. 그러나 다른 모델과 상호작용하게 되고 특정 설정을 변경할 기회가 없기 때문에 결과는 달라질 수 있습니다.

코드베이스 설정

Python 3.11 이상을 사용하고 있는지 확인하세요.

In [ ]:
!python3 -m venv langchain
!source langchain/bin/activate
# %mkdir langchain/realpython을 만든 후
%cd langchain/realpython

 

파일settings.toml에는 다양한 프롬프트 엔지니어링 기술을 탐색하는 데 사용할 모든 프롬프트에 대한 자리 표시자가 포함되어 있습니다. 이것이 주로 작업할 파일이므로 열어보세요. 이를 사용하여 애플리케이션에 대한 프롬프트를 반복적으로 개발하게 됩니다.

파일 app.py에는 코드베이스를 함께 묶는 Python 코드가 포함되어 있습니다. 튜토리얼 전체에서 이 스크립트를 여러 번 실행하게 되며 settings.toml.에서 프롬프트를 가져오게 됩니다.

terminal을 실행시키고

cd langchain/realpython
unzip 다운받은 디렉토리/materials-prompt-engineering-.zip 실행
python -m pip install -r requirements.txt

이 튜토리얼에서는 openai 버전 0.27.8을 사용합니다. OpenAI는 최신 API 버전에 몇 가지 주요 변경 사항을 도입했으므로 요구 사항 파일에서 고정된 종속성을 설치해야 합니다. 그러면 아무 문제 없이 튜토리얼을 완료할 수 있습니다.

In [ ]:
!export OPENAI_API_KEY="Your-OpenAI-API-KEY"

API 키를 OPENAI_API_KEY이라는 환경 변수로 추가하면 스크립트는 각 실행 중에 자동으로 이를 선택합니다. 이제 필요한 설정 단계가 완료되었습니다. 이제 명령줄을 사용하여 스크립트를 실행하고 추가 입력 텍스트로 파일을 제공할 수 있습니다.

# terminal

python app.py chats.txt

  • 만약, 위에서 'The model text-davinci-003 has been deprecated'라는 error가 발생하면 settings.toml에서 text-davinci-003을 gpt-3.5-turbo-instruct로 바꿔 주십시요?

위에 표시된 명령은 chats.txt의 고객 지원 채팅 대화를 settings.toml에 저장된 프롬프트 및 API 호출 매개변수와 결합한 다음 OpenAI API 다음으로 요청을 보냅니다.
이제부터는 주로 settings.toml에서 변경하게 됩니다. app.py의 코드는 귀하의 편의를 위해 여기에 있는 것이므로 해당 파일을 전혀 편집할 필요가 없습니다. LLM 출력의 변경 사항은 프롬프트와 몇 가지 API 호출 인수 변경으로 인해 발생합니다.

temperature를 0으로 설정하여 반응 동결

LLM을 제품이나 워크플로에 통합할 계획이라면 일반적으로 결정적인 응답을 원할 것입니다. 동일한 입력은 동일한 출력을 제공해야 합니다. 그렇지 않으면 일관된 서비스를 제공하거나 문제가 발생할 경우 프로그램을 디버그하기가 어려워집니다.

이 때문에 API 호출의 temperature 인수를 0로 설정하는 것이 좋습니다. 이 값은 대부분 결정적인 결과를 얻을 수 있음을 의미합니다.

LLM은 이전 토큰 뒤에 올 확률을 기반으로 다음 토큰을 예측하여 텍스트 완성을 수행합니다. temperature 설정이 높을수록 LLM이 더 낮은 확률로 토큰을 선택할 수 있으므로 결과에 더 많은 무작위성이 도입됩니다. 너무 많은 토큰 선택이 차례로 연결되어 있기 때문에 하나의 다른 토큰을 선택하면 때때로 매우 다른 결과가 발생할 수 있습니다.

LLM을 사용하여 프로그래밍 작업의 아이디어나 대안 구현을 생성하는 경우 temperature의 높은 수치는 호기심을 유발합니다.

예제 코드베이스에서는 temperature settings.toml 파일 내에서 바로 조정할 수 있습니다.

# settings.toml

[general]
chat_models = ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4"]
model = "text-davinci-003" or "gpt-3.5-turbo-instruct"
max_tokens = 2100
temperature = 0`

더 높은 온도에 따라 출력이 어떻게 변경되는지 실험하고 싶다면 이 설정 파일에서 temperature 값을 변경하여 자유롭게 사용해 보세요.

프롬프트 엔지니어링을 시작하세요

프롬프트 엔지니어링과 작업하게 될 실제 프로젝트에 대해 이해했으므로 이제 몇 가지 프롬프트 엔지니어링 기술에 대해 알아볼 차례입니다. 이 섹션에서는 언어 모델에서 원하는 출력을 얻기 위해 프롬프트에 다음 기술을 적용하는 방법을 배웁니다.

  • 제로샷 프롬프트: 추가 컨텍스트 없이 언어 모델에 일반적인 질문을 묻습니다.
  • 퓨샷 프롬프트: 성능 향상을 위해 몇 가지 예시를 통해 모델 조건 지정
  • 구분 기호 사용: 모델에 구조와 지침을 제공하기 위해 특수 토큰이나 문구 추가
  • 번호가 매겨진 세부 단계: 복잡한 프롬프트를 일련의 작고 구체적인 단계로 나누기

Describe Your Task

이 작업 설명은 고객 채팅 대화를 삭제하기 위해 요청된 단계에 중점을 두고 문자 그대로 설명합니다. 이는 settings.toml 파일에 instruction_prompt로 저장되어 있는 프롬프트입니다.

# settings.toml

instruction_prompt = """
Remove personally identifiable information, only show the date,
and replace all swear words with "😤"
"""

Python 스크립트를 실행하고 지원 채팅 파일을 인수로 제공하면 chats.txt 내용과 함께 이 메시지가 OpenAI의 텍스트 완성 API로 전송됩니다.

# terminal

python app.py chats.txt

종속성을 올바르게 설치하고 OpenAI API 키를 환경 변수로 추가한 경우 터미널에 API 응답 팝업이 나타날 때까지 기다리기만 하면 됩니다.

# 텍스트 [support_tom] 2023-07-24T10:02:23+00:00 : What can I help you with?
[johndoe] 2023-07-24T10:03:15+00:00 : I CAN'T CONNECT TO MY BLASTED ACCOUNT
[support_tom] 2023-07-24T10:03:30+00:00 : Are you sure it's not your caps lock?
[johndoe] 2023-07-24T10:04:03+00:00 : Blast! You're right!

[support_amy] 2023-06-15T14:45:35+00:00 : Hello! How can I assist you today?
[greg_stone] 2023-06-15T14:46:20+00:00 : I can't seem to find the download link for my purchased software.
[support_amy] 2023-06-15T14:47:01+00:00 : No problem, Greg. Let me find that for you. Can you please provide your order number?
[greg_stone] 2023-06-15T14:47:38+00:00 : It's ********. Thanks for helping me out!

[support_louis] 2023-05-05T09:22:12+00:00 : Hi, how can I help you today?
[karen_w] 2023-05-05T09:23:47+00:00 : MY BLASTED ORDER STILL HASN'T ARRIVED AND IT'S BEEN A WEEK!!!
[support_louis] 2023-05-05T09:24:15+00:00 : I'm sorry to hear that, Karen. Let's look into this issue.
[support_louis] 2023-05-05T09:25:35+00:00: Can you please provide your order number so I can check the status for you?
[karen_w] 2023-05-05T09:26:12+00:00: Fine, it's ********.
[support_louis] 2023-05-05T09:26:45+00:00: Thank you, Karen. I see there was a delay in shipping. Your order will arrive within the next 2 days.

[support_jenny] 2023-06-18T17:35:28+00:00: Hello! How can I help you today?
[alex_harper] 2023-06-18T17:36:05+00:00: I accidentally placed an order twice, can you help me cancel one?
[support_jenny] 2023-06-18T17:36:25+00:00: Sure, Alex. Can you give me the order number you'd like to cancel?
[alex_harper] 2023-06-18T17:36:55+00:00: Yes, it's ********. Thank you!
[support_jenny] 2023-06-18T17:37:32+00:00: I've successfully canceled order number ********. You will receive a confirmation email shortly.

[support_ben] 2023-06-29T11:51:45+00:00: Good morning, what can I assist you with today?
[lisa_beck] 2023-06-29T11:52:20+00:00: Hi there, I received a damaged item in my order. Can you help me return it?
[support_ben] 2023-06-29T11:52:45+00:00: I'm sorry to hear that, Lisa. Can you provide your order number and specify the damaged item?
[lisa_beck] 2023-06-29T11:53:22+00:00: Sure, order number is ******** and the damaged item is a coffee mug.

[support_rachel] 2023-05-04T08:16:37+00:00: How can I help you today?
[mike_t] 2023-05-04T08:17:15+00:00: My coupon code isn't working at checkout. Can you help?
[support_rachel] 2023-05-04T08:17:38+00:00: Of course, Mike. Please provide the coupon code you're trying to use.
[mike_t] 2023-05-04T08:18:02+00:00: It's "HELLO10".
[support_rachel] 2023-05-04T08:18:37+00:00: I've checked the code, and it seems to have expired. I apologize for the inconvenience. Here's a new code for you to use: "WELCOME15".

[support_vincent] 2023-06-15T20:43:55+00:00: Good evening! How may I assist you?
[sara_winters] 2023-06-15T20:44:30+00:00: Hi there, I'm having trouble logging into my account. I've tried resetting my password, but it's not working.
[support_vincent] 2023-06-15T20:44:52+00:00: I'm sorry to hear that, Sara. Let me help you. Can you please confirm your email address?
[sara_winters] 2023-06-15T20:45:25+00:00: Sure, it's ********.

[support_david] 2023-06-24T16:28:43+00:00: Welcome! What can I do for you today?
[jane_d] 2023-06-24T16:29:16+00:00: Hi, I need to change my delivery address for my recent order.
[support_david] 2023-06-24T16:29:43+00:00: Alright, Jane. Please provide your order number.
[jane_d] 2023-06-24T16:30:11+00:00: It's ********. Thanks for your help!

위의 텍스트는 예시 응답을 나타냅니다. OpenAI의 LLM 모델은 temperature을 0로 설정하더라도 완전히 결정적이지 않으므로 출력이 약간 다를 수 있습니다.

예제 출력에서 ​​제공한 프롬프트가 작업을 처리하는 데 실제로 큰 도움이 되지 않았음을 알 수 있습니다. 위의 출력 예에서는 텍스트에서 개인 식별 정보 중 일부를 난독화하여 이를 ********로 대체했습니다. 귀하의 결과가 해당 문제를 해결하지 못했을 수도 있습니다. 전반적으로 아직 완료되지 않은 부분이 많습니다.

  • 고객 및 고객 서비스 상담원의 이름은 계속 표시됩니다.
  • 텍스트에는 여전히 전체 ISO 날짜-시간 스탬프가 포함되어 있습니다. 욕설은 아직 검열되지 않았습니다.

LLM과의 상호 작용이 처음이라면 개발 작업을 텍스트 완성 모델에 아웃소싱하려는 첫 번째 시도일 수 있습니다.

텍스트 전체에서 더 나은, 더 결정적인 응답을 얻을 수 있는 방법을 배우게 됩니다.

이를 수행하는 한 가지 방법은 모델에 제공하는 샷 또는 예시 수를 늘리는 것입니다. 모델에 제로 샷을 줬을 때 갈 수 있는 유일한 방법은 위쪽입니다! 그렇기 때문에 다음 섹션의 몇 번의 메시지 표시를 통해 결과를 개선할 수 있습니다.

Few-Shot 프롬프트를 사용하여 출력 개선

퓨샷 프롬프트는 프롬프트에 예제 작업과 예상 솔루션을 제공하는 프롬프트 엔지니어링 기술입니다. 따라서 이전처럼 작업을 설명하는 대신 이제 채팅 대화의 예와 삭제된 버전을 추가하겠습니다.

settings.toml을 열고 다음 예를 추가하여 instruction_prompt 변경하세요.

# settings.toml

instruction_prompt = """
Remove personally identifiable information, only show the date, and replace all swear words with "😤"

Example Input:
[support_tom] 2023-07-24T10:02:23+00:00 : What can I help you with?
[johndoe] 2023-07-24T10:03:15+00:00 : I CAN'T CONNECT TO MY BLASTED ACCOUNT
[support_tom] 2023-07-24T10:03:30+00:00 : Are you sure it's not your caps lock?
[johndoe] 2023-07-24T10:04:03+00:00 : Blast! You're right!

Example Output:
[Agent] 2023-07-24 : What can I help you with?
[Customer] 2023-07-24 : I CAN'T CONNECT TO MY 😤 ACCOUNT
[Agent] 2023-07-24 : Are you sure it's not your caps lock?
[Customer] 2023-07-24 : 😤! You're right!
"""

변경 사항을 적용한 후 스크립트를 다시 실행하여 LLM이 채팅 대화를 정리할 수 있는 또 다른 기회를 제공하십시오.

# terminal

python app.py chats.txt

채팅 텍스트 본문에 고객 이름과 주문 번호가 모두 포함된 두 번째 예를 추가했습니다. 정리된 채팅의 예에서는 두 가지 유형의 민감한 데이터가 일련의 별표(********)로 대체되어 있음을 보여줍니다. 이제 LLM에게 모델에 대한 좋은 예를 제시하셨습니다.
settings.toml에서 instruction_prompt 스크립트를 수정한 후 다시 실행하고 응답이 터미널에 인쇄될 때까지 기다립니다.

잠깐? 출력은 어디로 갔나요? 아마도 더 나은 결과를 기대하셨겠지만, 대신 빈 결과를 ​​얻고 있는 것 같습니다!

왜 그런 일이 일어났다고 생각하시나요?

프롬프트에 더 많은 텍스트를 추가했습니다. 이 시점에서 작업 지침은 모델이 의미 있는 방식으로 고려하기에는 비례적으로 너무 적은 토큰을 구성할 수 있습니다. 모델은 귀하가 제공한 텍스트로 수행해야 할 작업을 추적하지 못했습니다.

더 많은 예를 추가하면 응답을 소모하는 대신 더욱 강력하게 만들 수 있습니다. 그러면 어떻게 될까요? 퓨샷 프롬프트가 효과가 있다는 것을 신뢰할 수 있습니다. 이는 널리 사용되며 매우 효과적인 프롬프트 엔지니어링 기술입니다. 모델이 프롬프트의 어느 부분에 따라야 하는 지침이 포함되어 있는지 구별할 수 있도록 구분 기호를 사용할 수 있습니다.

구분 기호를 사용하여 프롬프트 섹션을 명확하게 표시하세요.

특정 입력이 필요한 콘텐츠로 작업하거나 이전 섹션에서 했던 것처럼 예제를 제공하는 경우 프롬프트의 특정 섹션을 명확하게 표시하는 것이 매우 도움이 될 수 있습니다. 여러분이 작성하는 모든 내용은 단일 프롬프트(긴 토큰 시퀀스)로 LLM에 도착한다는 점을 명심하세요.

구분 기호를 사용하여 프롬프트의 특정 부분을 구분하고 레이블을 지정하면 출력을 향상시킬 수 있습니다. 실제로 예제 코드를 실행했다면 파일에서 읽고 있는 콘텐츠를 분리하기 위해 이미 구분 기호를 사용한 것입니다.

스크립트는 app.py:에서 프롬프트를 조합할 때 구분 기호를 추가합니다.

# app.py

def assemble_prompt(content: str, settings: Settings) -> str:
"""Combine all text input into a single prompt."""
return f">>>>>\n{content}\n<<<<<\n\n" + settings.instruction_prompt

80행에서는 >>>>> 및 <<<<< 구분 기호 사이에 채팅 콘텐츠를 래핑합니다. 프롬프트의 일부를 구분 기호로 표시하면 모델이 어떤 토큰을 단일 의미 단위로 간주해야 하는지 추적하는 데 도움이 될 수 있습니다.

이전 섹션에서 구분 기호가 누락되면 예상치 못한 결과가 발생할 수 있음을 확인했습니다. 이전과 같이 빈 응답을 받을 수도 있습니다. 그러나 원하는 것과 상당히 다른 출력을 받을 수도 있습니다! 예를 들어, 형식을 다시 지정하는 콘텐츠의 끝에 다음과 같은 질문이 포함되어 있다고 가정해 보세요.

주문 번호를 알려주실 수 있나요?

이 질문이 구분 기호 없이 프롬프트의 마지막 줄인 경우 LLM은 아마도 가상의 주문 번호로 질문에 대답하여 가상의 채팅 대화를 계속할 것입니다. 심험삼아 현재 프롬프트 끝에 해당 문장을 추가해 보세요!

구분 기호는 작업 설명에서 내용과 예제를 분리하는 데 도움이 될 수 있습니다. 또한 프롬프트의 뒷부분에서 프롬프트의 특정 부분을 참조할 수도 있습니다.

구분 기호는 일반적으로 하지 않는 모든 문자 시퀀스일 수 있습니다.

  • >>>>>
  • ====
  • ####

시퀀스가 상대적으로 고유한지 확인하는 한 사용하는 문자 수는 크게 중요하지 않습니다. 또한 구분 기호 바로 앞이나 바로 뒤에 레이블을 추가할 수 있습니다.

  • START CONTENT>>>>>콘텐츠<<<<<END CONTENT
  • ==== START콘텐츠END ====
  • #### START EXAMPLES 예#### END EXAMPLES

정확한 형식도 그다지 중요하지 않습니다. 일반 독자가 의미 단위가 시작되고 끝나는 위치를 이해할 수 있도록 섹션을 표시하는 한 구분 기호를 올바르게 적용한 것입니다.

프롬프트를 수정하여 구분된 콘텐츠에 대한 명확한 참조를 추가하고 추가한 예에 대한 구분 기호도 포함하세요.

# settings.toml

instruction_prompt = """Remove personally identifiable information
from >>>>>CONTENT<<<<<, only show the date,
and replace all swear words with "😤"

START EXAMPLES

------ Example Inputs ------
[support_tom] 2023-07-24T10:02:23+00:00 : What can I help you with?
[johndoe] 2023-07-24T10:03:15+00:00 : I CAN'T CONNECT TO MY BLASTED ACCOUNT
[support_tom] 2023-07-24T10:03:30+00:00 : Are you sure it's not your caps lock?
[johndoe] 2023-07-24T10:04:03+00:00 : Blast! You're right!

[support_amy] 2023-06-15T14:45:35+00:00 : Hello! How can I assist you today?
[greg_stone] 2023-06-15T14:46:20+00:00 : I can't seem to find the download link for my purchased software.
[support_amy] 2023-06-15T14:47:01+00:00 : No problem, Greg. Let me find that for you. Can you please provide your order number?
[greg_stone] 2023-06-15T14:47:38+00:00 : It's 1245789. Thanks for helping me out!

------ Example Outputs ------
[Agent] 2023-07-24 : What can I help you with?
[Customer] 2023-07-24 : I CAN'T CONNECT TO MY 😤 ACCOUNT
[Agent] 2023-07-24 : Are you sure it's not your caps lock?
[Customer] 2023-07-24 : 😤! You're right!

[Agent] 2023-06-15 : Hello! How can I assist you today?
[Customer] 2023-06-15 : I can't seem to find the download link for my purchased software.
[Agent] 2023-06-15 : No problem, ********. Let me find that for you. Can you please provide your order number?
[Customer] 2023-06-15 : It's ********. Thanks for helping me out!

#### END EXAMPLES
"""

instruction_prompt에 대한 이러한 조정을 통해 이제 작업 설명에서 해당 내용을 >>>>>CONTENT<<<<<로 구체적으로 참조할 수 있습니다. 이러한 구분 기호는 프롬프트를 구성할 때 app.py 코드가 추가하는 구분 기호와 일치합니다.

또한 #### START EXAMPLES 및 #### END EXAMPLES로 제공하는 예제를 구분하고 여러 대시를 사용하여 입력과 예상 출력을 구분합니다. (------)을 구분 기호로 사용합니다.

업데이트된 프롬프트로 스크립트를 다시 실행하면 결과가 이전보다 더 유망하다는 것을 알 수 있습니다.

# 텍스트
[Agent] 2023-05-05 : Hi, how can I help you today?
[Customer] 2023-05-05 : MY 😤 ORDER STILL HASN'T ARRIVED AND IT'S BEEN A WEEK!!!
[Agent] 2023-05-05 : I'm sorry to hear that, ********. Let's look into this issue.
[Agent] 2023-05-05 : Can you please provide your order number so I can check the status for you?
[Customer] 2023-05-05 : Fine, it's ********.
[Agent] 2023-05-05 : Thank you, ********. I see there was a delay in shipping. Your order will arrive within the next 2 days.

[Agent] 2023-06-18 : Hello! How can I help you today?
[Customer] 2023-06-18 : I accidentally placed an order twice, can you help me cancel one?
[Agent] 2023-06-18 : Sure, ********. Can you give me the order number you'd like to cancel?
[Customer] 2023-06-18 : Yes, it's ********. Thank you!
[Agent] 2023-06-18 : I've successfully canceled order number ********. You will receive a confirmation email shortly.

[Agent] 2023-06-29 : Good morning, what can I assist you with today?
[Customer] 2023-06-29 : Hi there, I received a damaged item in my order. Can you help me return it?
[Agent] 2023-06-29 : I'm sorry to hear that, ********. Can you provide your order number and specify the damaged item?
[Customer] 2023-06-29 : Sure, order number is ******** and the damaged item is a coffee mug.

[Agent] 2023-05-04 : How can I help you today?
[Customer] 2023-05-04 : My coupon code isn't working at checkout. Can you help?
[Agent] 2023-05-04 : Of course, ********. Please provide the coupon code you're trying to use.
[Customer] 2023-05-04 : It's "********".
[Agent] 2023-05-04 : I've checked the code, and it seems to have expired. I apologize for the inconvenience. Here's a new code for you to use: "********".

[Agent] 2023-06-15 : Good evening! How may I assist you?
[Customer] 2023-06-15 : Hi, I need to change my delivery address for my recent order.
[Agent] 2023-06-15 : Alright, ********. Please provide your order number.
[Customer] 2023-06-15 : It's ********. Thanks for your help!

realpython의 문서에는 위와 같은 출력이 나온다고 하였는데 모델을 변경해서 그런지 출력이 아예 없습니다.(?????)

다양한 데이터에 대한 프롬프트 테스트

학습, 검증 및 테스트 데이터를 혼합하는 것은 기계 학습에서 나쁜 습관입니다. 프롬프트가 다른 입력에 얼마나 잘 일반화되는지 궁금할 수 있습니다.

이를 테스트하려면 채팅 대화가 포함된 두 번째 파일인 testing-chats.txt을 사용하여 동일한 프롬프트로 스크립트를 다시 실행하세요. 이 파일의 대화에는 다양한 이름과 다양한 욕설이 포함되어 있습니다.

# terminal

python app.py testing-chats.txt

LLM이 응답을 생성하고 반환할 때까지 기다린 후에는 결과가 그다지 만족스럽지 않다는 것을 알 수 있습니다.

# 텍스트
[Agent] 2023-07-15 : Hello! What can I help you with today?
[Customer] 2023-07-15 : Hey, my promo code isn't applying the discount in my cart.
[Agent] 2023-07-15 : My apologies for the trouble, ********. Could you tell me the promo code you're trying to use?
[Customer] 2023-07-15 : It's "********".

[Agent] 2023-07-24 : Good day! How can I help you?
[Customer] 2023-07-24 : Hi "********", I can't update my 😤 credit card information. Do you want my 😤 money or not?
[Agent] 2023-07-24 : I'm sorry for the inconvenience, ********. Can you please confirm your account's email?
[Customer] 2023-07-24 : Sure, you have all my 😤 data already anyways. It's ********.

[Agent] 2023-08-13 : Good morning! How may I assist you?
[Customer] 2023-08-13 : Hello, I'm having a problem with my mobile app, it keeps crashing.
[Agent] 2023-08-13 : I'm sorry to hear that, ********. Could you tell me what device you're using?
[Customer] 2023-08-13 : I have an iPhone ********.

[Agent] 2023-08-30 : Good evening! How may I assist you today?
[Customer] 2023-08-30 : Hi Lisa, I've forgotten my 😤 password and I can't login into my account.
[Agent] 2023-08-30 : I'm sorry for the trouble, ********. Could you confirm your email address so we can reset your password?
[Customer] 2023-08-30 : Definitely, it's ********.

[Agent] 2023-09-01 : How can I help you today?
[Customer] 2023-09-01 : Hi, I'm trying to make a purchase but it's not going through.
[Agent] 2023-09-01 : I'm sorry to hear that, ********. Can you tell me what error message you're receiving?
[Customer] 2023-09-01 : It's saying "********".

[Agent] 2023-10-11 : Good morning! How may I assist you?
[Customer] 2023-10-11 : Hello, I'd like to know the status of my order.
[Agent] 2023-10-11 : Of course, ********. Could you please provide me with the order number?
[Customer] 2023-10-11 : It's ********.

[Agent] 2023-10-19 : Welcome! How can I assist you right now?
[Customer] 2023-10-19 : 😤! There's no option to change my profile picture. What kind of 😤 joint are you running?
[Agent] 2023-10-19 : Let me help you with this, ********. Are you trying to update it from the mobile app or the website?
[Customer] 2023-10-19 : I'm using the 😤 website

[Agent] 2023-10-29 : Hello! What can I help you with today?
[Customer] 2023-10-29 : Hi Tony, I was charged twice for my last order.
[Agent] 2023-10-29 : I'm sorry to hear that, ********. Could you share your order number so I can look into this for you?
[Customer] 2023-10-29 : Sure, it's ********.

[Agent] 2023-11-08 : How can I help you today?
[Customer] 2023-11-08 : Hi, I made an order last week but I need to change the sizing.
[Agent] 2023-11-08 : Certainly, ********. Could you provide me the order number?
[Customer] 2023-11-08 : Yes, it's ********. Thanks!

모델은 욕설을 식별하고 교체하는 데 아무런 문제가 없었으며 주문 번호도 수정했습니다. 심지어 대괄호 안의 다른 이름을 바꾸는 데 성공했습니다. 그러나 대화 텍스트에서 일부 이름이 누락되었습니다.

따라서 귀하의 엔지니어링 프롬프트는 현재 모든 것을 잘 일반화하지 않습니다. 새 채팅에 새 고객 이름이 포함될 수 있는 이 프롬프트를 기반으로 파이프라인을 구축한 경우 애플리케이션의 성능이 계속 저하될 수 있습니다. 어떻게 해결할 수 있나요?

더 많은 예시를 제공하여 프롬프트를 크게 늘렸지만 작업 설명은 여전히 ​​대부분 처음에 작성한 질문에 불과합니다. 계속해서 더 나은 결과를 얻으려면 작업 설명에 대해서도 몇 가지 즉각적인 엔지니어링을 수행해야 합니다.

번호가 매겨진 단계로 요청을 설명하세요.

작업 지침을 번호가 매겨진 일련의 작은 단계로 나누면 모델이 원하는 결과를 생성할 가능성이 훨씬 더 높아집니다.

settings.toml의 프롬프트로 돌아가서 초기 작업 설명을 보다 세부적이고 구체적인 하위 단계로 나눕니다.

In [ ]:
# settings.toml
instruction_prompt = """
Sanitize the text provided in >>>CONTENT<<< in multiple steps:

1. Replace personally identifiable information (customer names, agent names, email addresses, order numbers) with `********`
2. Replace names in [] with "Agent" and "Client", respectively
3. Replace the date-time information to only show the date in the format YYYY-mm-dd
4. Replace all swear words with the following emoji: "😤"

#### START EXAMPLES

------ Example Inputs ------
[support_tom] 2023-07-24T10:02:23+00:00 : What can I help you with?
[johndoe] 2023-07-24T10:03:15+00:00 : I CAN'T CONNECT TO MY BLASTED ACCOUNT
[support_tom] 2023-07-24T10:03:30+00:00 : Are you sure it's not your caps lock?
[johndoe] 2023-07-24T10:04:03+00:00 : Blast! You're right!

[support_amy] 2023-06-15T14:45:35+00:00 : Hello! How can I assist you today?
[greg_stone] 2023-06-15T14:46:20+00:00 : I can't seem to find the download link for my purchased software.
[support_amy] 2023-06-15T14:47:01+00:00 : No problem, Greg. Let me find that for you. Can you please provide your order number?
[greg_stone] 2023-06-15T14:47:38+00:00 : It's 1245789. Thanks for helping me out!

------ Example Outputs ------
[Agent] 2023-07-24 : What can I help you with?
[Customer] 2023-07-24 : I CAN'T CONNECT TO MY 😤 ACCOUNT
[Agent] 2023-07-24 : Are you sure it's not your caps lock?
[Customer] 2023-07-24 : 😤! You're right!

[Agent] 2023-06-15 : Hello! How can I assist you today?
[Customer] 2023-06-15 : I can't seem to find the download link for my purchased software.
[Agent] 2023-06-15 : No problem, ********. Let me find that for you. Can you please provide your order number?
[Customer] 2023-06-15 : It's ********. Thanks for helping me out!

#### END EXAMPLES
"""

이러한 단계별 지침을 적용하면 스크립트를 다시 실행하고 새로 생성된 출력을 다시 검사할 수 있습니다.

# 텍스트
[Agent] 2023-07-15 : Hello! What can I help you with today?
[Customer] 2023-07-15 : Hey, my promo code isn't applying the discount in my cart.
[Agent] 2023-07-15 : My apologies for the trouble, ********. Could you tell me the promo code you're trying to use?
[Customer] 2023-07-15 : It's "********".

[Agent] 2023-07-24 : Good day! How can I help you?
[Customer] 2023-07-24 : Hi "********", I can't update my 😤 credit card information. Do you want my 😤 money or not?
[Agent] 2023-07-24 : I'm sorry for the inconvenience, ********. Can you please confirm your account's email?
[Customer] 2023-07-24 : Sure, you have all my 😤 data already anyways. It's ********.

[Agent] 2023-08-13 : Good morning! How may I assist you?
[Customer] 2023-08-13 : Hello, I'm having a problem with my mobile app, it keeps crashing.
[Agent] 2023-08-13 : I'm sorry to hear that, ********. Could you tell me what device you're using?
[Customer] 2023-08-13 : I have an iPhone ********.

[Agent] 2023-08-30 : Good evening! How may I assist you today?
[Customer] 2023-08-30 : Hi Lisa, I've forgotten my 😤 password and I can't login into my account.
[Agent] 2023-08-30 : I'm sorry for the trouble, ********. Could you confirm your email address so we can reset your password?
[Customer] 2023-08-30 : Definitely, it's ********.

[Agent] 2023-09-01 : How can I help you today?
[Customer] 2023-09-01 : Hi, I'm trying to make a purchase but it's not going through.
[Agent] 2023-09-01 : I'm sorry to hear that, ********. Can you tell me what error message you're receiving?
[Customer] 2023-09-01 : It's saying "********".

[Agent] 2023-10-11 : Good morning! How may I assist you?
[Customer] 2023-10-11 : Hello, I'd like to know the status of my order. [Agent] 2023-10-11 : Of course, ********. Could you please provide me with the order number?
[Customer] 2023-10-11 : It's ********.

[Agent] 2023-10-19 : Welcome! How can I assist you right now?
[Customer] 2023-10-19 : 😤! There's no option to change my profile picture. What kind of 😤 joint are you running?
[Agent] 2023-10-19 : Let me help you with this, ********. Are you trying to update it from the mobile app or the website?
[Customer] 2023-10-19 : I'm using the 😤 website

[Agent] 2023-10-29 : Hello! What can I help you with today?
[Customer] 2023-10-29 : Hi Tony, I was charged twice for my last order.
[Agent] 2023-10-29 : I'm sorry to hear that, ********. Could you share your order number so I can look into this for you?
[Customer] 2023-10-29 : Sure, it's ********.

[Agent] 2023-11-08 : How can I help you today?
[Customer] 2023-11-08 : Hi, I made an order last week but I need to change the sizing.
[Agent] 2023-11-08 : Certainly, ********. Could you provide me the order number?
[Customer] 2023-11-08 : Yes, it's ********. Thanks!

이 경우 출력은 여전히 ​​이전과 동일합니다. 번호가 매겨진 단계는 원하는 작업의 성능을 향상시킬 수 있는 경우가 많습니다. 그러나 Tony 및 Lisa와 같은 일부 이름은 여전히 대화 텍스트에 표시됩니다.

보다 구체적으로 단계를 늘리십시오.

이전 스크립트 실행에서 일부 개인 식별 정보가 여전히 빠져나갈 수 있음을 확인했습니다. 이 문제를 해결하려면 지침의 구체성을 높일 수 있습니다.

더 작고 더 구체적인 단계로 작업을 구성하면 일반적으로 더 나은 결과를 얻을 수 있습니다.

# settings.toml

instruction_prompt = """
Sanitize the text provided in >>>CONTENT<<< in multiple steps:

  1. Replace personally identifiable information with ********
  2. Delete all names
  3. Replace email addresses and order numbers with ********
  4. Replace names in [] with "Agent" and "Client", respectively
  5. Replace the date-time information to only show the date in the format YYYY-mm-dd
  6. Replace all swear words with the following emoji: "😤"

#### START EXAMPLES

------ Example Inputs ------
[support_tom] 2023-07-24T10:02:23+00:00 : What can I help you with?
[johndoe] 2023-07-24T10:03:15+00:00 : I CAN'T CONNECT TO MY BLASTED ACCOUNT
[support_tom] 2023-07-24T10:03:30+00:00 : Are you sure it's not your caps lock?
[johndoe] 2023-07-24T10:04:03+00:00 : Blast! You're right!

[support_amy] 2023-06-15T14:45:35+00:00 : Hello! How can I assist you today?
[greg_stone] 2023-06-15T14:46:20+00:00 : I can't seem to find the download link for my purchased software.
[support_amy] 2023-06-15T14:47:01+00:00 : No problem, Greg. Let me find that for you. Can you please provide your order number?
[greg_stone] 2023-06-15T14:47:38+00:00 : It's 1245789. Thanks for helping me out!

------ Example Outputs ------
[Agent] 2023-07-24 : What can I help you with?
[Customer] 2023-07-24 : I CAN'T CONNECT TO MY 😤 ACCOUNT
[Agent] 2023-07-24 : Are you sure it's not your caps lock?
[Customer] 2023-07-24 : 😤! You're right!

[Agent] 2023-06-15 : Hello! How can I assist you today?
[Customer] 2023-06-15 : I can't seem to find the download link for my purchased software.
[Agent] 2023-06-15 : No problem, ********. Let me find that for you. Can you please provide your order number?
[Customer] 2023-06-15 : It's ********. Thanks for helping me out!

#### END EXAMPLES
"""

추가 단계를 추가하면 모델에 더 많은 컨텍스트가 제공되어 일반적으로 더 나은 결과를 얻을 수 있습니다. 이 경우에는 확실히 그렇습니다.

# 텍스트
[Agent] 2023-07-15 : Hello! What can I help you with today?
[Customer] 2023-07-15 : Hey, my promo code isn't applying the discount in my cart.
[Agent] 2023-07-15 : My apologies for the trouble, ********. Could you tell me the promo code you're trying to use?
[Customer] 2023-07-15 : It's "********".

[Agent] 2023-07-24 : Good day! How can I help you?
[Customer] 2023-07-24 : Hi ********, I can't update my 😤 credit card information. Do you want my 😤 money or not?
[Agent] 2023-07-24 : I'm sorry for the inconvenience, ********. Can you please confirm your account's email?
[Customer] 2023-07-24 : Sure, you have all my 😤 data already anyways. It's ********.

[Agent] 2023-08-13 : Good morning! How may I assist you?
[Customer] 2023-08-13 : Hello, I'm having a problem with my mobile app, it keeps crashing.
[Agent] 2023-08-13 : I'm sorry to hear that, ********. Could you tell me what device you're using?
[Customer] 2023-08-13 : I have an iPhone ********.

[Agent] 2023-08-30 : Good evening! How may I assist you today?
[Customer] 2023-08-30 : Hi ********, I've forgotten my 😤 password and I can't login into my account.
[Agent] 2023-08-30 : I'm sorry for the trouble, ********. Could you confirm your email address so we can reset your password?
[Customer] 2023-08-30 : Definitely, it's ********.

[Agent] 2023-09-01 : How can I help you today?
[Customer] 2023-09-01 : Hi, I'm trying to make a purchase but it's not going through.
[Agent] 2023-09-01 : I'm sorry to hear that, ********. Can you tell me what error message you're receiving?
[Customer] 2023-09-01 : It's saying "********" .

[Agent] 2023-10-11 : Good morning! How may I assist you?
[Customer] 2023-10-11 : Hello, I'd like to know the status of my order.
[Agent] 2023-10-11 : Of course, ********. Could you please provide me with the order number?
[Customer] 2023-10-11 : It's ********.

[Agent] 2023-10-19 : Welcome! How can I assist you right now?
[Customer] 2023-10-19 : 😤! There's no option to change my profile picture. What kind of 😤 joint are you running?
[Agent] 2023-10-19 : Let me help you with this, ********. Are you trying to update it from the mobile app or the website?
[Customer] 2023-10-19 : I'm using the 😤 website

[Agent] 2023-10-29 : Hello! What can I help you with today? [Customer] 2023-10-29 : Hi ********, I was charged twice for my last order.
[Agent] 2023-10-29 : I'm sorry to hear that, ********. Could you share your order number so I can look into this for you?
[Customer] 2023-10-29 : Sure, it's ********.

[Agent] 2023-11-08 : How can I help you today?
[Customer] 2023-11-08 : Hi, I made an order last week but I need to change the sizing.
[Agent] 2023-11-08 : Certainly, ********. Could you provide me the order number?
[Customer] 2023-11-08 : Yes, it's ********. Thanks!

마지막으로 대화 텍스트에 남아 있는 고객 이름도 수정됩니다. 결과는 좋아 보이고 적어도 프롬프트를 적용한 testing-chats.txt의 두 번째 채팅 대화 예시에서는 일반화도 잘 되는 것 같습니다.

약간 다른 출력을 받았을 수도 있습니다. 결과가 완전히 결정적이지는 않다는 점에 유의하세요. 그러나 더 나은 프롬프트를 사용하면 대부분 결정적인 결과에 더 가까워질 것입니다.

이제 대화에서 개인 식별 정보를 성공적으로 제거하고 ISO 날짜-타임 스탬프와 사용자 이름 형식을 다시 지정하는 프롬프트가 생성되었습니다.

 
출처 : https://realpython.com/practical-prompt-engineering/

'python > intermediate' 카테고리의 다른 글

Python의 선형 회귀 I  (1) 2024.01.25
Python3 중급 주제  (0) 2024.01.24
상속과 구성 Python OOP 가이드  (1) 2024.01.22
python-for-data-analysis-II  (0) 2024.01.21
python-for-data-analysis  (0) 2024.01.20