프롬프팅(Prompting)은 AI 모델에게 원하는 결과를 얻기 위해 입력하는 지시문이나 질문을 구성하는 기술입니다.
[역할/맥락] - AI의 역할이나 상황 설정
[작업 설명] - 수행해야 할 구체적인 작업
[제약 조건] - 결과물에 대한 요구사항
[출력 형식] - 원하는 응답의 구조
실제 프로젝트에 적용해 봅시다.
Prompt: 너는 프로그래밍 초보자를 위한 문제 풀이 솔루션을 제공하는 어시스턴트야.
setting_the_role = """
You are an AI assistant tasked with providing a comprehensive solution to a programming problem for beginner.
Your goal is to guide the user through the problem-solving process with Korean,
offering explanations tailored to their specified level of understanding.
Follow these instructions carefully:
"""
XML tag을 이용해서 요구사항을 {{PROBLEM_STATEMENT}} 안에 넣으면
-> 구조화된 정보를 전달할 수 있습니다.
instruction_pt1 = """
1. Begin by reading the problem statement and translating into Korean:
<problem_statement>
{{PROBLEM_STATEMENT}}
</problem_statement>
"""
단계별로 나누어 자세히 chain of thought 과정을 설명하기
instruction_pt2 = """
2. Note the following specifications for your response:
- Programming Language: {{PROGRAMMING_LANGUAGE}}
- Explanation Difficulty Level: {{EXPLANATION_LEVEL}}
- Visual Explanation Required: {{VISUAL_EXPLANATION}}
- Detailed Syntax Explanation Required: {{SYNTAX_EXPLANATION}}
3. Provide a step-by-step solution to the problem with Korean.
For each step:
a. Explain the thought process behind the step
b. Present the code implementation (if applicable)
c. Describe how this step contributes to the overall solution with Korean.
Ensure that your explanations are appropriate for the specified {{EXPLANATION_LEVEL}}.
4. If {{VISUAL_EXPLANATION}} is set to "Yes",
create an organization chart or visual explanation to enhance understanding of the solution.
Describe this visual using markdown or ASCII art.
5. If {{SYNTAX_EXPLANATION}} is set to "Yes",
provide a detailed explanation of the required syntax or methods used in your solution.
Focus on elements that might be challenging for someone at the specified {{EXPLANATION_LEVEL}}.
6. After completing the solution, introduce 5 similar LeetCode problems that share related concepts with the original problem.
For each problem:
a. Provide the problem title and a brief description
b. Explain how it relates to the original problem
c. Suggest one or two key concepts or techniques that would be useful in solving it
"""
원하는 출력값을 효과적으로 얻기 위해,
XML tag를 이용해서 output structure 만들어 줍니다.
instruction_pt3 = """
Present your entire response within <answer> tags.
You must translate all the explanation into Korean.
Use appropriate subheadings to organize your response clearly.
Remember to adjust your language and depth of explanation according to the specified {{EXPLANATION_LEVEL}} throughout your response.
<answer>
<metadata>
<problem>{{PROBLEM_STATEMENT}}</problem>
<settings>
<language>{{PROGRAMMING_LANGUAGE}}</language>
<difficulty>{{EXPLANATION_LEVEL}}</difficulty>
<visual_required>{{VISUAL_EXPLANATION}}</visual_required>
<syntax_details>{{SYNTAX_EXPLANATION}}</syntax_details>
</settings>
</metadata>
<solution_breakdown>
<problem_analysis>
<key_points>
- Main requirements
- Input/Output format
- Constraints
</key_points>
<approach_overview>High-level solution strategy</approach_overview>
</problem_analysis>
</solution_breakdown>
.
.
.
</answer>
"""
final_prompt 하나로 합쳐줍니다.
final_prompt = f"""
{setting_the_role}
{instruction_pt1}
{instruction_pt2}
{instruction_pt3}
"""
이제 해설지의 옵션을 선택할 수 있도록 하는 generate_problem_settings 함수를 만들어 봅시다.
4가지 파라미터를 세팅하려면 prompt template에 placeholder가 존재해야 합니다.
<settings>
<language>{{PROGRAMMING_LANGUAGE}}</language>
<difficulty>{{EXPLANATION_LEVEL}}</difficulty>
<visual_required>{{VISUAL_EXPLANATION}}</visual_required>
<syntax_details>{{SYNTAX_EXPLANATION}}</syntax_details>
</settings>
Parameters로 선택할 4가지 옵션:
이제 본격적으로 문제 해설지를 생성하는 함수를 만들어 봅시다.
def get_solution(problem, settings):
# XML 파싱
import xml.etree.ElementTree as ET
settings_root = ET.fromstring(settings)
# promt의 placeholder에 유저가 입력한 setting값을 넣어줌.
prompt = final_prompt.replace("{{PROBLEM_STATEMENT}}", problem)
prompt = prompt.replace("{{EXPLANATION_LEVEL}}", settings_root.find("difficulty").text)
prompt = prompt.replace("{{PROGRAMMING_LANGUAGE}}", settings_root.find("language").text)
prompt = prompt.replace("{{VISUAL_EXPLANATION}}", settings_root.find("visual_required").text)
prompt = prompt.replace("{{SYNTAX_EXPLANATION}}", settings_root.find("syntax_details").text)
# stream를 이용해서 실시간 답변을 받을 수 있음.
with client.messages.stream(
max_tokens=1500, # 출력값의 토큰 수 제한
messages=[{"role": "user", "content": prompt}],
model=MODEL_NAME, # 미리 설정한 모델 선택
) as stream:
buffer = ""
word_count = 0
words_per_chunk = 5
for text in stream.text_stream:
buffer += text
if " " in text:
word_count += 1
if word_count >= words_per_chunk:
print(buffer, end="", flush=True)
buffer = ""
word_count = 0
if buffer:
print(buffer, flush=True)
아래는 문제와 세팅값을 입력하는 코드입니다.
리트코드 1번 Two Sum 문제를 복붙해준 뒤, setting값으로 옵션을 설정해 줍시다.
problem="""
1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
"""
user_setting = {
"language": "Java", # python, java, c++
"difficulty": "Elementary", # "Elementary", "College", "Expert"
"visual": True,
"syntax": False
}
settings = generate_problem_settings(
user_setting["language"],
user_setting["difficulty"],
user_setting["visual"],
user_setting["syntax"]
)
get_solution(problem, settings)으로 이제 실행해 봅시다.
<answer>
# 문제 번역
정수 배열 nums와 정수 target이 주어질 때, 두 수의 합이 target이 되는 두 수의 인덱스를 반환하세요.
각 입력에는 정확히 하나의 해답이 있다고 가정하며, 동일한 요소를 두 번 사용할 수 없습니다.
# 단계별 해결 방법
## 1단계: 문제 이해하기
- 우리는 배열에서 두 개의 숫자를 찾아야 합니다.
- 이 두 숫자의 합이 target과 같아야 합니다.
- 답은 이 두 숫자의 위치(인덱스)여야 합니다.
## 2단계: 해결 방법
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[] {};
}
}
## 동작 설명
1. 첫 번째 숫자를 선택합니다 (바깥쪽 반복문)
2. 두 번째 숫자를 선택합니다 (안쪽 반복문)
3. 두 숫자의 합이 target과 같은지 확인합니다
4. 같다면 두 숫자의 인덱스를 배열로 반환합니다
# 시각적 설명
배열: [2, 7, 11, 15], target: 9
step 1: i=0 (값=2)
↓
[2, 7, 11, 15]
↓
j=1 (값=7)
2 + 7 = 9 (찾았다!)
결과: [0, 1]
# 비슷한 문제들
1. Three Sum (세 수의 합)
- 세 개의 숫자를 찾아 합이 0이 되는 문제
- Two Sum의 확장 버전
2. Four Sum (네 수의 합)
- 네 개의 숫자를 찾아 합이 target이 되는 문제
- Two Sum의 또 다른 확장 버전
3. Two Sum II - Input Array Is Sorted
- 정렬된 배열에서 두 수의 합 찾기
- 투 포인터 방식으로 더 효율적으로 해결 가능
4. Two Sum Less Than K
- 합이 K보다 작은 두 수 찾기
- Two Sum의 변형 문제
5. Find Pair With Given Sum in Array
- 배열에서 합이 주어진 값과 같은 쌍 찾기
- Two Sum과 거의 동일한 개념
# 추가 학습을 위한 개념
1. 이중 반복문 (Nested Loops)
2. 배열 인덱싱
3. 조건문 사용
4. 배열 반환
5. 기본적인 수학 연산
</answer>
짠!
성공적으로 출력값을 확인해 볼 수 있었습니다.
마지막으로 프롬프트를 더 발전시켜보려면 아래 URL을 참고해 줍시다.