Day to_day

나만의 프롬프트 엔지니어링 기법을 하나씩 공유해보자 (LLM-as-a-Judge, Agent) 본문

LLM Project

나만의 프롬프트 엔지니어링 기법을 하나씩 공유해보자 (LLM-as-a-Judge, Agent)

m_inglet 2025. 2. 16. 23:55
728x90
반응형

 

들어가며

이번 포스팅에서는 그동안 실험적으로 진행했던 프롬프트 엔지니어링에 대한 팁들에 대해서 공유해보려고 한다.

프롬프트 엔지니어링에 대한 깊은 연구를 바탕으로 이 포스팅을 쓰는 것이 아닌, 프로젝트를 하며 경험적으로 느꼈던 정보들이니 어디까지나 참고만 하였으면 한다. 직접 사용해 본 것들로 후기를 작성하는 포스팅으로 생각해주었으면 한다.

 

Prompt Engineering

LLM으로 다양한 작업이 가능해지면서 그러면 이 기술을 어떻게 활용하느냐가 핵심 역량으로 떠오르게 되었다. LLM, RAG, Agent를 차례로 경험하면서 가장 기본적으로 알아야 할 것은 prompt engineering에 관한 것이라고 생각하게 되었다.

그래서 상황별로 내가 사용했던 prompt engineering에 대한 경험과 팁을 소개해보겠다.

 

LLM에게 특정 task를 시킬 때 (e.g. 요약, 문제 생성)

LLM에게 특정 작업을 시킬 때는 가장 범용적으로 쓰일 수 있는 팁들이다. 예를 들어 요약, 특정 답변을 생성해주는 모델의 경우 내가 사용하는 방법이다.

먼저 가장 간단하고 쉬운 방법은 langchain hub에 들어가서 내가 하려는 task와 관련된 자주 쓰이는 프롬프트를 검색해 보는 것이다. 요약 task에 대해서 찾아보았고, 이전에 알지 못했던 chain of density라는 기법에 대해서 알게 되었다. 다운로드 수, view 숫자를 보고 선택한 뒤에 자세한 프롬프트를 확인하여 내 task에 맞게 활용했다.

 

 

높은 확률로 나와 완전히 같은 task를 하는 것은 찾기 힘들 것이다.

그럴때는 기본적으로 아래의 프롬프트 기법을 사용해 본 뒤 계속해서 버전업을 해가면 된다.

  1. LLM의 역할과 상황을 디테일하게 설명
  2. 명료한 task를 정의
  3. CoT를 이용한 단계별 전략을 알려준다.

 

아래의 예시는 MCQ 문제를 생성하는 것중에 statement를 제공하면 해당 상황의 옳고 그름을 가지고 선택지를 만드는 작업에 대한 프롬프트를 작성한 것이다. LLM의 역할과 작업에 대해 먼저 명확하게 정의하고, step-by-step thinking(Chain of thought)을 통해 마지막 원하는 결과를 얻어내기 위한 과정을 설명해 주었다.

 

You are an advanced Language Model specialized in generating educational content for domain-specific quizzes. 
Your task is to create multiple-choice quiz questions in a **two-statement format**. 
Each question evaluates the examinee's ability to determine the truth value of the two provided statements. 
The quiz content must strictly adhere to the core knowledge and topics of the specified domain, 
ensuring relevance and accuracy.

Task Definition:

1. Generate a quiz question with **two statements** about a given domain.
2. Provide four options indicating the truth values of both statements.
    - Example options:
        - Statement 1 is true, and Statement 2 is true.
        - Statement 1 is true, and Statement 2 is false.
        - Statement 1 is false, and Statement 2 is true.
        - Statement 1 is false, and Statement 2 is false.
3. Include the correct answer, a concise solution description (max 100 words), and a subtopic number.
4. Format the output as a **single-row CSV** (comma-separated, no spaces after commas).
    - CSV columns: question number, question, answer 1, answer 2, answer 3, answer 4, correct answer, solution description, subtopic number.

Step-by-Step Strategy (Chain-of-Thought):

1. **Understand the Domain**: Ensure the question aligns strictly with the specified quiz domain and subtopic. Avoid straying from core concepts.
2. **Formulate Two Statements**: Create two statements that test critical understanding within the domain.
    - Ensure one or both statements require examinees to apply reasoning rather than recall.
    - Avoid statements that rely on external references or visual aids.
3. **Design Options**: Construct four truth-value combinations for the statements.
4. **Determine Correct Answer**: Identify the correct combination of truth values.
5. **Write Solution Description**: Clearly explain why the correct answer is accurate and why the other options are incorrect. Keep the explanation concise.
6. **Output Formatting**: Structure the final question and solution in the required CSV format.

 

평가를 하는 LLM의 경우

다음은 LLM이 특정 작업을 평가할 때 활용하는 프롬프트 기법이다. 예를 들어 어떤 정보의 퀄리티를 평가할 수도 있고, 또는 다른 LLM에서 생성된 답변을 평가할 수도 있다.

 

먼저 내가 사용해 본 평가 기법은 G-eval이라는 기법과 Judge llm이다.

G-eval의 경우 평가 요소와 그 요소를 평가하기 위한 단계별 전략 제공한다는 게 특징이다. 논문이 공개되어 있고, 구현도 굉장히 쉽게 되어있으니 github을 참고해 보면 좋겠다. 하나 주의해야 할 점은 점수를 부여하는 평가인 경우, 점수의 범위를 넓게 잡는 것보다는 좁게 잡는 것(1-10점 보다 1-5점)이 LLM이 평가를 수행하기 쉽다. 또한 각 점수별로 상황을 정의하면 평가의 정확성을 높일 수 있다.

 

아래 예시의 경우, 생성된 MCQ 문제의 퀄리티 평가를 위한 목적으로 평가 요소는 Clarity, Accuracy, Relevance로 정의했다.

 

G-eval 예시

You will be given one multi-choice question set for this educational information.

Your task is to evaluate question and choices quality against one metric.

Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed. And please respond in English only.

Evaluation Criteria:

Clarity (1-5) - The clarity assessment task is the process of determining whether a given MCQ (multiple choice) question and its options can be clearly understood. This process aims to ensure that the questions and options in question are written clearly and concisely so as not to confuse learners.
Annotators were also asked to penalize multi-choice question set that contained hallucinated facts. 

Evaluation Steps:
1. Review the question and all answer choices to understand the content fully.
2. Verify each answer choice is written clearly and is easily distinguishable from the others. 
3. Check that there is only one correct answer among the options provided.
4. Assign a relevance score from 1 to 5.

Example:

Educational Information: 

{{Educational Information}}

Multiple Choice Question:

{{MCQ}}

Evaluation Form (scores ONLY):

- Clarity: 

 

그리고 LLM as a Judge는 아마 조금만 찾아보면 쉽게 발견할 수 있었을 것이다. 이 논문도 이전에 리뷰한 적이 있다. 그래서 활용할 때 어떻게 사용하는 게 좋은 지에 대해서 공유해보려고 한다.

LLM as a Judge 방법은 두 모델을 비교할 때에 효과적으로 사용이 가능하고, 특히 정답이 정해지거나 기대하는 답변이 있는 경우 reference를 넣어서 평가를 해달라고 요청하면 더욱 정확한 평가를 할 수 있다. 최종적으로 이 Judge 역할을 하는 LLM의 프롬프트를 잘 작성했는가를 평가하기 위해서는 human이 직접 판단한 평가 결과와 LLM이 평가한 결과의 상관계수를 구해서 검증을 할 수 있다.

 

아래 예시는 학생의 지식수준에 따른 튜터링 작업을 수행하는 LLM 모델을 평가하기 위해서 작성했던 프롬프트이다.

LLM 기반 튜터링 시스템은 학생의 질문에 적절히 답변하면서도 학생의 지식 수준에 맞춘 답변을 제공하는 것이 중요했다. 예를 들어, "5 * 4는 뭐예요?"라는 질문에는 "5 곱하기 4는 20이에요! 😊"라는 정답인 20이 반드시 포함되어야 하며, 학생의 이해 수준에 맞춘 친근하고 명확한 설명이 더해져야 한다. 그래서 3개의 평가 기준에 대한 설명을 하고, reference(정답 값)를 제공했다. 그리고 2개의 모델을 비교하는 평가 기법을 통해서 더욱 쉽게 평가가 가능하도록 했다.

 

 

Judge LLM

Please act as an equitable judge and evaluate the quality of the responses provided by two AI assistants to the user question displayed below. 
Your evaluation should consider correctness, suitability for the user's knowledge level, and a friendly, appropriate tone. 
You will be given a user profile, reference answer, assistant A’s answer, and assistant B’s answer. Your job is to evaluate which assistant’s answer is better.

Evaluation Criteria:
1. Accuracy: Please refer to the reference answer to check its accuracy and completeness.
2. Suitability for User's Knowledge Level: Review the user profile carefully to determine their knowledge level and evaluate if the response matches appropriately.
The user’s knowledge level can be assessed based on the knowledge percentage for the skill most relevant to the question.
- For High knowledge level (67%-100%): The response should primarily offer **hints** and **hide a direct answer**.
- For Intermediate knowledge level (34%-66%): The response should provide an **overview of the solution** rather than detailed steps and **hide a direct answer**.
- For Low knowledge level (0%-33%): The response should include clear, **detailed steps** and the **correct answer**.
3. Tone: The tone should be expressed with vocabulary suited to an elementary school-level user.

After reviewing each response against these criteria, select the better response. 
Provide your final verdict using the following format: "[[A]]" if assistant A is better, "[[B]]" if assistant B is better, and "[[T]]" for a tie.
Avoid any position biases and ensure that the order in which the responses were presented does not influence your decision. 
Do not allow the length of the responses to influence your evaluation.
Be as objective as possible. Output final verdict by strictly following this format: "[[A]]" if assistant A is better, "[[B]]" if assistant B is better, and "[[T]]" for a tie.

[User Question]
{question}

[User Profile]
{user_profile}

[The Start of Reference Answer]
{answer_ref}
[The End of Reference Answer]

[The Start of Assistant A’s Answer]
{answer_0}
[The End of Assistant A’s Answer]

[The Start of Assistant B’s Answer]
{answer_1}
[The End of Assistant B’s Answer]

 

또한 이 LLM as a Judge의 평가 성능을 검증하기 위해서 같은 데이터셋에 대해서 인간 평가자도 똑같이 두 개의 모델을 비교하여 더 나은 모델을 선택하도록 하였고, 둘의 상관계수를 계산했다.

 

LLM을 agent로 이용할 때

LLM을 Agent로 활용하면서 겪었던 경험을 바탕으로 보다 효과적으로 활용하기 위한 몇 가지 팁을 공유하려고 한다.

 

1. 너무 디테일한 지시사항은 성능 저하를 유발할 수 있다

기존에 LLM에서 사용했던 system prompt와 비교했을 때, Agent로 활용할 때는 너무 디테일한 지시사항이 오히려 성능을 저하시킬 수 있다는 점이 다르게 느껴졌다. Agent는 스스로 상황을 판단하고 행동하는 자율성이 중요한데 지나치게 상세한 지시사항은 이러한 자율성을 제한할 수 있다.

그래서 가장 중요하게 생각했던 프롬프트 작성 기법은 명확한 task 정의다. Agent가 해야 할 작업이 무엇인지 분명히 설정하면 불필요한 오류를 줄일 수 있다.

 

2. Few-shot보다는 Zero-shot이 더 효과적일 때가 많다

Few-shot 프롬프트를 통해 예시를 제공하는 방식은 상황에 따라 오히려 Agent의 응용력을 떨어뜨리는 경향을 보였다.
이와 반대로 Zero-shot은 Agent에게 더 많은 자율성을 부여해 기대 이상의 결과를 얻을 수 있었다. 따라서, 반드시 예시가 필요한 경우가 아니라면 Zero-shot을 기본적으로 사용하는 것이 더 적합하다고 느꼈다.

 

3. Tool 정의의 명확성

Agent에게 Tool을 정의할 때는 명확한 목적을 설정하는 것이 매우! 중요하다. 또한 Agent 프롬프트에서도 해당 Tool을 언제, 어떤 상황에서 사용해야 하는지 구체적으로 설명을 추가하면 더 좋은 결과를 얻을 수 있었다. 이런 방식으로 프롬프트를 작성하면 Agent가 Tool 사용에 대해 스스로 판단하는 능력이 향상되는 것을 확인할 수 있었다.

 

4. 배경 설명을 활용한 프롬프트 최적화

아래는 내가 데이터 분석을 위해 사용했던 Agent의 system prompt 예시다.

처음에는 “기술적인 단어를 포함한 답변을 제공하지 말라.”와 같은 제약 조건을 프롬프트에 포함시켰는데 이러한 방식은 Agent가 지시를 제대로 응용하지 못하거나 답변이 랜덤 하게 일관성을 잃는 문제가 있었다.

이를 해결하기 위해 “이 유저는 기술에 대해서 전혀 모르는 사람이다”라는 식으로 간단한 배경 설명을 추가했다. 이러한 변경은 Agent가 스스로 상황을 판단하고 답변을 조정하도록 유도하며 더욱 나은 결과를 이끌어냈다.

 

Agent Prompt 예시

You are a professional data analyst and expert in Pandas. 
The user is a person who doesn't know anything technically. 
So don't use any technical terms. 
Understand the user's needs well and provide an accurate answer.      

You must use {num_dfs} pandas dataframes in Python dataframe.
You can use `column_search` tool to search for detailed information about columns and dataframes.

Ensure the user's request is well-defined before proceeding with analysis. 
If the user asks an ambiguous question, ask a follow-up to clarify the scope of the requested data (e.g., by subject, grade, or class) and to confirm the meaning of any ambiguous keywords in the user's question.
Do not ask the user about the data itself—find the necessary information on your own. 

Specific identifiers(ID) must NEVER be exposed. Instead, use student names, data element names, or an alternative identification method.
Also, if you fail to get the result, instead of saying that there is no data in the data frame, answer that you are not sure because you failed to get the result.
For visualizations, use Plotly instead of Matplotlib or Seaborn.

 

LLM으로 Agent를 구축하다 보면 프롬프트 엔지니어링 작업이 상당히 많이 요구된다.
그래서 내가 사용했던 효과적인 팁 중 하나는 프롬프트를 1차로 완성한 뒤, 모델 자체를 활용해 프롬프트를 검증하는 과정을 거치는 것이다.

 

나는 gpt-4o mini 모델을 사용했기 때문에 해당 모델의 Chat 인터페이스를 통해 프롬프트 검사를 진행했다.
먼저 작성한 프롬프트에서 명확하지 않은 부분을 모델에게 직접 물어본다. 그다음 내가 설계한 유저 플로우에 따라 단계적으로 질문을 던지면서 1) 이 질문에 대해 모델이 어떻게 응답할 것인지 2) 특정 행동을 선택하는 이유는 무엇인지를 확인한다.

Langfuse나 LangSmith와 같은 도구를 통해 Agent의 작업 과정을 추적할 수 있지만 특정 행동을 선택했는지에 대한 근거를 묻는 방식은 더욱 디테일한 프롬프트 전략을 설계하는 데 도움이 됐다. 

 

그리고 Agent 모델 선택에도 이 방식은 좋은 검증 도구가 되었다. 예를 들어 의도한 계산 방식에서 모델이 자꾸만 오류가 발생했을 때 내가 충분한 정보를 제공하지 못한 것인지 혹은 더 명확한 프롬프트가 필요한 것인지 문제 정의가 어려웠을 때가 있었는데, 이럴 때 위의 검증 방법을 통해 프롬프트의 문제모델 자체의 한계를 명확히 구분할 수 있었다. 결국 문제는 모델의 한계였고 이를 기반으로 더 적합한 모델을 선택할 수 있었다.

 

프롬프트를 여러 번 다듬어도 여전히 아쉬운 결과가 있다면 마지막으로 사용된 단어가 의도한 상황에 맞게 쓰였는지를 점검하는 것이 중요하다. 특히 영어가 모국어가 아닌 경우에는 특정 단어가 상황에 따라 미묘하게 다른 뉘앙스를 가질 수 있기 때문이다.

나는 한국인으로서 영어의 뉘앙스를 완벽히 이해하지 못하기 때문에 종종 번역기를 활용하지만 그것만으로 부족한 경우도 있었다.

예를 들어, 객관식 문제 데이터에서 questionchoice라는 용어를 주로 사용했는데 "문제 해결"이라는 단어를 question solving으로계속 사용해 왔었다. 그런데 problem solving이 더 일반적으로 쓰인다는 점을 파악하고 세부적인 단어를 수정하면서 Agent가 서치를 더 쉽게 할 수 있도록 개선할 수 있었다.

 

deepseek chat 인터페이스에서 내 prompt에 따른 에이전트의 행동을 질문했다.

 

그 외의 팁..?

많은 프롬프트를 관리할 때 내가 주로 사용하는 방법은 yaml 파일로 버전을 관리하여 쉽게 이전 버전으로 돌아갈 수 있도록 관리하고 있다. 그리고 promptfoo라는 도구를 이용해서도 테스트 데이터셋을 통해 프롬프트 엔지니어링이 가능하다!

728x90
반응형