DeepLearning.AI 강의 ChatGPT Prompt Engineering for Developers - Guidelines 요약
https://www.deeplearning.ai/short-courses/chatgpt-prompt-engineering-for-developers/
ChatGPT Prompt Engineering for Developers
What you’ll learn in this course In ChatGPT Prompt Engineering for Developers, you will learn how to use a large language model (LLM) to quickly build new and powerful applications. Using the OpenAI API, you’ll...
www.deeplearning.ai
Python 에 openAI 라이브러리 설치
pip install openai
https://platform.openai.com/account/api-keys 에서 계정의 secret key 설정 가능
openAI API key 로드
!export OPENAI_API_KEY='sk-...'
혹은
import openai
openai.api_key = "sk-..."
chat completions endpoint 함수
공식 문서: https://platform.openai.com/docs/guides/chat
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0, # this is the degree of randomness of the model's output
)
return response.choices[0].message["content"]
효과적인 프롬프트 작성 원칙
1. 명확하고 구체적인 지시를 작성
2. 모델에게 생각할 시간을 줄 것
구체적 전략
1. 구분자(delimiters)를 사용해 입력 부분을 명확하게 구분
* delimiters: ```, """, <>, <tag></tag>, : 등
text = f"""
You should express what you want a model to do by \
providing instructions that are as clear and \
specific as you can possibly make them. \
This will guide the model towards the desired output, \
and reduce the chances of receiving irrelevant \
or incorrect responses. Don't confuse writing a \
clear prompt with writing a short prompt. \
In many cases, longer prompts provide more clarity \
and context for the model, which can lead to \
more detailed and relevant outputs.
"""
prompt = f"""
Summarize the text delimited by triple backticks \
into a single sentence.
```{text}```
"""
response = get_completion(prompt)
print(response)
2. 구조화된 출력 (json, html) 요청
prompt = f"""
Generate a list of three made-up book titles along \
with their authors and genres.
Provide them in JSON format with the following keys:
book_id, title, author, genre.
"""
response = get_completion(prompt)
print(response)
3. 주어진 조건을 만족하였는지 모델에게 체크 요청
text_1 = f"""
Making a cup of tea is easy! First, you need to get some \
water boiling. While that's happening, \
grab a cup and put a tea bag in it. Once the water is \
hot enough, just pour it over the tea bag. \
Let it sit for a bit so the tea can steep. After a \
few minutes, take out the tea bag. If you \
like, you can add some sugar or milk to taste. \
And that's it! You've got yourself a delicious \
cup of tea to enjoy.
"""
prompt = f"""
You will be provided with text delimited by triple quotes.
If it contains a sequence of instructions, \
re-write those instructions in the following format:
Step 1 - ...
Step 2 - …
…
Step N - …
If the text does not contain a sequence of instructions, \
then simply write \"No steps provided.\"
\"\"\"{text_1}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 1:")
print(response)
4. Few-Shots 프롬프팅
prompt = f"""
Your task is to answer in a consistent style.
<child>: Teach me about patience.
<grandparent>: The river that carves the deepest \
valley flows from a modest spring; the \
grandest symphony originates from a single note; \
the most intricate tapestry begins with a solitary thread.
<child>: Teach me about resilience.
"""
response = get_completion(prompt)
print(response)
모델에게 생각할 시간을 주기 위한 전략들
1. 주어진 과제를 완성하기 위해 필요한 단계들을 구체적으로 명시
text = f"""
In a charming village, siblings Jack and Jill set out on \
a quest to fetch water from a hilltop \
well. As they climbed, singing joyfully, misfortune \
struck—Jack tripped on a stone and tumbled \
down the hill, with Jill following suit. \
Though slightly battered, the pair returned home to \
comforting embraces. Despite the mishap, \
their adventurous spirits remained undimmed, and they \
continued exploring with delight.
"""
# example 1
prompt_1 = f"""
Perform the following actions:
1 - Summarize the following text delimited by triple \
backticks with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the following \
keys: french_summary, num_names.
Separate your answers with line breaks.
Text:
```{text}```
"""
response = get_completion(prompt_1)
print("Completion for prompt 1:")
print(response)
- 지정된 형식으로 출력을 요청
prompt_2 = f"""
Your task is to perform the following actions:
1 - Summarize the following text delimited by
<> with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the
following keys: french_summary, num_names.
Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in Italian summary>
Output JSON: <json with summary and num_names>
Text: <{text}>
"""
response = get_completion(prompt_2)
print("\nCompletion for prompt 2:")
print(response)
2. 성급히 결론을 내기 전에 모델이 자체적인 해결책을 마련하도록 지시
prompt = f"""
Determine if the student's solution is correct or not.
Question:
I'm building a solar power installation and I need \
help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations
as a function of the number of square feet.
Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
response = get_completion(prompt)
print(response)
모델의 한계: 환영 현상(Hallucinations)
- LLM은 잘 알려지지 않은 주제에 대한 질문에 답변을 시도 혹은 그럴듯하게 들리지만 실제로는 사실이 아닌 것을 만들어낼 수도 있음
환영 현상을 줄이는 추가 전략
- 모델에게 텍스트에서 관련된 인용구를 찾게 하고 이를 사용하여 질문에 답하도록 요청, 답변을 원문에서 추적
'Data Science > Prompt Engineering' 카테고리의 다른 글
ChatGPT Prompt Engineering for Developers - (6) Transforming (0) | 2023.11.08 |
---|---|
ChatGPT Prompt Engineering for Developers - (5) Inferring (0) | 2023.11.08 |
ChatGPT Prompt Engineering for Developers - (4) Summarizing (0) | 2023.11.07 |
ChatGPT Prompt Engineering for Developers - (3) Iterative (0) | 2023.11.06 |
ChatGPT Prompt Engineering for Developers - (1) Introduction (0) | 2023.10.30 |