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
ChatGPT Prompt Engineering for Developers
4 - Inferring 정리
Setup
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
openai.api_key = os.getenv('OPENAI_API_KEY')
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"]
Inferring - 추론 하기
1) Sentiment 감정 분석
로지텍의 MX-KEYS 키보드 리뷰에 대한 작성자의 감정을 분석해보자.
Prompt Task 작성
1) What is the sentiment of the following product review,
2) Which is delimited with triple backticks?
3) Translate in korean.
결과 포멧
Review text: ```{review}```
review_1 = """
비교적 내구성이 낮은 펜타그래프를 전전하다가 이 제품에 정착했다는 후기가 많은 로지텍의 MX Keys입니다.
특유의 조용조용한 타격감과 메탈 바디에 블랙, 그레이가 섞인 고급진 디자인으로 사무실 책상에서 존재감을 드러냅니다. 오목한 키캡 디자인으로 키 구분감이 좋아 오타가 줄어들었다는 의견도 많은 제품입니다.
블루투스로 멀티페어링이 가능하며, 연결된 OS를 인식하여 자동으로 기능키 및 단축키를 인식하기 때문에 기기를 바꿀 때마다 따로 설정하지 않아도 되어 편리합니다.
가격은 다소 비싸지만 정숙한 키감의 고급스러운 사무실용 키보드를 찾으시는 분께 추천드립니다.
다만, 스페이스바 길이가 길어 적응하기 힘들다는 의견도 있으며, 로지텍의 최신 연결방식인 로지볼트를 지원하지 않아, 블루투스를 지원하지 않는 기기에서 로지텍 마우스와 함께 사용하는 경우에는 USB 동글을 2개 꽂아야 한다는 점이 아쉽습니다.
"""
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?
translate in korean.
Review text: ```{review_1}```
"""
response = get_completion(prompt)
print(response)
+ label로 사용하기 위해 positive or negative 지정
Prompt Task 작성
1) What is the sentiment of the following product review,
2) Which is delimited with triple backticks?
3) Give your answer as a single word, either “positive” or ”negative”
4) Translate in korean.
결과 포멧
Review text: ```{review}```
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?
Give your answer as a single word, either “positive” or ”negative”
Review text: ```{review_1}```
"""
response = get_completion(prompt)
print(response)
2) Extract product and company name from customer reviews (품목 정보 추출)
Prompt Task 작성
1) Identify the following items from the review text:
- Item purchased by reviewer -- (품목 명시)
- Company that made the itemFormat your answer as a list of lower-case words (제조사 명시)
2) The review is delimited with triple backticks. Format your response as a JSON object with "Item" and "Brand" as the keys. If the information isn't present, use "unknown" as the value. (output format json)
3) Make your response as short as possible.
4) Translate in korean.
결과 포멧
Review text: ```{review}```
prompt = f"""
Identify the following items from the review text:
- Item purchased by reviewer
- Company that made the item
The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
translate in korean.
Review text: '''{review_1}'''
"""
response = get_completion(prompt)
print(response)
##
3) Doing multiple tasks at once
Prompt Task 작성
1)Identify the following items from the review text:
- Sentiment (positive or negative)
- Is the reviewer expressing anger? (true or false)
- Item purchased by reviewer
- Company that made the item
2) The review is delimited with triple backticks. Format your response as a JSON object with "Sentiment", "Anger", "Item" and "Brand" as the keys. If the information isn't present, use "unknown" as the value.
3) Make your response as short as possible.
4) Format the Anger value as a boolean.
5) Translate in Koreans.
결과 포멧
Review text: ```{review}```
prompt = f"""
Identify the following items from the review text:
- Sentiment (positive or negative)
- Is the reviewer expressing anger? (true or false)
- Item purchased by reviewer
- Company that made the item
The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Sentiment", "Anger", "Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
Format the Anger value as a boolean.translate in korean.
Review text: '''{review_1}'''
"""
response = get_completion(prompt)
print(response)
4) Inferring topics
'피노키오' 이야기를 보고 5가지 주제를 뽑아내보자
Prompt Task 작성
1) Determine five topics that are being discussed in the following text, which is delimited by triple backticks.
2) Make each item one or two words long.
3) Format your response as a list of items separated by comas.
4) Translate in korean.
결과 포멧
Text sample: ```{story}```
story = "피노키오는 학교로 가는 길에 서커스단과 마주쳤고, 신발을 던져 점을 쳐서 학교로 갈지 서커스를 보러 갈지 결정했다. 학교로 가는 점이 나왔지만, 몇번이나 계속 점을 쳐 서커스로 가는 점괘가 나오자 교과서를 판 돈으로 서커스 관람료를 내고 입장했다. 서커스단은 마침 인형극을 공연하고 있었다. 그런데 때마침 들어온 피노키오를 보고, 관객들은 인형극은 무시한채 피노키오를 무대로 데려와 껴안으며 즐거워했다. 그 덕분에 인형극은 엉망이 되고 화가 머리끝까지 난 인형 놀잇꾼은 피노키오를 잡아서 기둥에 매달아 버렸다. 인형 놀잇꾼은 저녁밥으로 먹을 양고기를 굽는 화덕에 피노키오를 장작으로 집어넣으려 한다. 피노키오는 자비를 구하자, 인형 놀잇꾼은 피노키오 대신 다른 인형을 장작으로 쓰겠다고 말했다. 그러자 피노키오는 자신을 대신 때라고 나섰고, 인형 놀잇꾼은 피노키오의 용기에 감탄해 두 인형을 모두 살려 주고는 피노키오에게 금화 다섯 닢을 주고 집으로 돌려보냈다."
prompt = f"""
Determine five topics that are being discussed in the \
following text, which is delimited by triple backticks.
Make each item one or two words long.
Format your response as a list of items separated by commas. translate in korean.
Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)
response.split(sep=',')
+ 원하는 주제의 글인지 판별하는 classification 추가
Make a story for certain topics
Prompt Task 작성
1) Determine whether each item in the following list of topics is a topic in the text below, which is delimited with triple backticks.
2) Give your answer as list with 0 or 1 for each topic
3) List of topics: {",".join(topic_list)}
4) Translate in Koreans.
결과 포멧
Text sample: ```{story}```
topic_list = ['피노키오', ' 서커스', ' 인형극', ' 자비', ' 금화']
###
prompt = f"""
Determine whether each item in the following list of topics is a topic in the text below, which
is delimited with triple backticks.
Give your answer as list with 0 or 1 for each topic.
List of topics: {", ".join(topic_list)}
Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)
topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\n')}
if topic_dict['피노키오'] == 1:
print("피노키오 이야기!")
'Tools > ChatGPT' 카테고리의 다른 글
[LLM] ChatGPT Prompt Engineering for Developers - Expanding (0) | 2023.05.06 |
---|---|
[LLM] ChatGPT Prompt Engineering for Developers - Transforming (0) | 2023.05.05 |
[LLM] ChatGPT Prompt Engineering for Developers - Summarizing (0) | 2023.05.04 |
[LLM] ChatGPT Prompt Engineering for Developers - Iterative (0) | 2023.05.03 |
[LLM] ChatGPT Prompt Engineering for Developers - Guidelines (0) | 2023.05.02 |