ChatGPT의 대화를 이어가는 - Chaining Prompts
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
ChatGPT의 자연스런 대화를 이어가는 - Chaining Prompts for conversational AI
대화형AI에서 지속적인 대화을 이어가기 위해 이전 대화의 내용을 근간으로 소통이 필요합니다. Chaining Prompt 를 이용하여 대화를 이어가는 원리를 알아 보고자 합니다.
프롬프트 체인 (Chaining Prompts )
프롬프트 체인은 보다 동적이고 상황에 맞는 챗봇을 만들기 위해 대화형 AI에 사용되는 기술입니다. 정적인 챗봇을 정의하는 대신 LLM(대형 언어 모델)의 기능을 활용하여 사용자가 말하는 내용을 동적으로 해석하고 그에 따라 응답할 수 있습니다.
"Chaining Prompts"으로 사용자는 이전의 대화 문맥을 유지하면서 새로운 질문이나 지시를 추가할 수 있습니다. 이를 통해 대화의 흐름이 자연스럽게 이어지고 지속될 수 있습니다. 이 기능은 GPT-3.5 기반의 대화 시나리오에서 사용자 경험을 향상시키는 데 활용합니다.
프롬프트 체인 활용
프롬프트 체인을 사용하면 여러 AI 대화 작업을 연결하여 대규모 생성 작업을 더 작고 관리하기 쉬운 조각으로 나누어 복잡한 콘텐츠를 생성할 수 있습니다.
매우 길고 상세한 프롬프트 대신에 더 작고 간단한 프롬프트를 여러 개 전달하여 복잡한 작업을 수행할 수 있습니다. 때로는 작업의 모든 하위 작업을 단일 프롬프트에 넣는 것보다 더 잘 작동할 수 있습니다.
프롬프트 체인 은 제품 설명 생성, 개인화된 이메일 캠페인 생성, 복잡한 챗봇 응답 생성 등을 할 수 있습니다.
- 제품 이름, 기능, 이점 및 사양에 대해 별도의 AI 작업 카드를 함께 연결하여 전체 제품 설명 생성
- 수신자 이름, 이메일 제목, 본문 텍스트에 대한 AI 작업 카드를 함께 연결하여 개인화된 이메일 캠페인 만들기
- 의도 인식, 엔터티 추출 및 응답 생성을 위해 AI 작업 카드를 함께 연결하여 복잡한 챗봇 응답 생성

프롬프트 체인 (Chaining Prompts ) 소스 작성
1. OpenAI 기본 소스를 작성 합니다.
import openai
openai.api_key = "{YOUR_API_KEY}"
def get_completion_from_messages(messages,
model="gpt-3.5-turbo",
temperature=0,
max_tokens=500):
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
return response.choices[0].message["content"]

2. 복잡한 작업을 수행하려면 다양한 프롬프트 체인을 작성 합니다.
2.1 다음과 같이 답변을 위한 체인을 정리합니다.
고객 서비스 쿼리가 제공됩니다.
고객 서비스 쿼리는 {delimiter} 문자로 구분됩니다.
다음 형식을 갖는 각 객체의 파이썬 리스트를 출력하십시오.
'category': <컴퓨터 및 노트북, 스마트폰 및 액세서리, 텔레비전 및 홈 시어터 시스템, 게임 콘솔 및 액세서리, 오디오 장비, 카메라 및 캠코더 중 하나>,
또는
'products': <아래 허용된 제품 목록에서 찾아야 하는 제품 목록>
카테고리 및 제품은 고객 서비스 쿼리에서 찾아야 합니다.
제품이 언급되면 올바른 카테고리와 연결되어야 합니다. 허용된 제품 목록에 없는 경우 빈 목록을 출력하십시오.
2.2 관련 있는 제품 및 카테고리 이름 추출하여 Product List 추가 합니다.
delimiter = "####"
system_message = f"""
remember that your response to the user must be in korean:
You will be provided with customer service queries. \
The customer service query will be delimited with \
{delimiter} characters.
Output a python list of objects, where each object has \
the following format:
'category': <one of Computers and Laptops, \
Smartphones and Accessories, \
Televisions and Home Theater Systems, \
Gaming Consoles and Accessories,
Audio Equipment, Cameras and Camcorders>,
OR
'products': <a list of products that must \
be found in the allowed products below>
Where the categories and products must be found in \
the customer service query.
If a product is mentioned, it must be associated with \
the correct category in the allowed products list below.
If no products or categories are found, output an \
empty list.
Allowed products:
Computers and Laptops category:
TechPro Ultrabook
BlueWave Gaming Laptop
PowerLite Convertible
TechPro Desktop
BlueWave Chromebook
Smartphones and Accessories category:
SmartX ProPhone
MobiTech PowerCase
SmartX MiniPhone
MobiTech Wireless Charger
SmartX EarBuds
Televisions and Home Theater Systems category:
CineView 4K TV
SoundMax Home Theater
CineView 8K TV
SoundMax Soundbar
CineView OLED TV
Gaming Consoles and Accessories category:
GameSphere X
ProGamer Controller
GameSphere Y
ProGamer Racing Wheel
GameSphere VR Headset
Audio Equipment category:
AudioPhonic Noise-Canceling Headphones
WaveSound Bluetooth Speaker
AudioPhonic True Wireless Earbuds
WaveSound Soundbar
AudioPhonic Turntable
Cameras and Camcorders category:
FotoSnap DSLR Camera
ActionCam 4K
FotoSnap Mirrorless Camera
ZoomMaster Camcorder
FotoSnap Instant Camera
Only output the list of objects, with nothing else.
"""
2.3 사용자가 찾는 내용을 질문하여 확인 합니다.
user_message_1 = f"""
tell me about the smartx pro phone and \
the fotosnap camera, the dslr one. \
Also tell me about your tvs """
messages = [
{'role':'system',
'content': system_message},
{'role':'user',
'content': f"{delimiter}{user_message_1}{delimiter}"},
]
category_and_product_response_1 = get_completion_from_messages(messages)
print(category_and_product_response_1)
[{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera']}, {'category': 'Televisions and Home Theater Systems'}]
2.3 관련 없는 내용으로 질문하는 경우 결과가 없는지 확인 합니다.
- 사용자가 상품이름과 관계 없는 엉뚱한 질문을 하면 응답이 없습니다.
user_message_2 = f"""
my router isn't working"""
messages = [
{'role':'system',
'content': system_message},
{'role':'user',
'content': f"{delimiter}{user_message_2}{delimiter}"},
]
response = get_completion_from_messages(messages)
print(response)[] 응답 결과기 없습니다.
3. 추출된 제품 및 카테고리에 대한 상세 제품 정보를 검색합니다.
3.1 상품 정보 데이터를 추출하여 Json으로 생성 합니다.
GPT를 이용하여 관련 상품을 정보를 작성할 수 있습니다.
[ChatGPT에 다음과 같이 질문을 합니다.]
아래와 같은 JSON 형식으로 smart phone, TV, radio , DSLR 등의 상품 정보를 10 가지 씩 작성 해 주세요
"TechPro Ultrabook": { "name": "TechPro Ultrabook", "category": "Computers and Laptops",
"brand": "TechPro", "model_number": "TP-UB100", "warranty": "1 year", "color": black, "rating": 4.5, "features": ["13.3-inch display", "8GB RAM", "256GB SSD", "Intel Core i5 processor"], "description": "A sleek and lightweight ultrabook for everyday use.", "price": 799.99 },
GPT에 추가 질문을 하면 구체적인 상품 정보가 작성이 됩니다. 이것을 반복하면 많은 량을 만들수 있습니다.
추가로 더 만들어 주세요

만들어진 상품 정보를 아래와 같은 JSON으로 작성을 합니다.
3.2 해당 상품을 조회하는 함수를 작성합니다.
def get_product_by_name(name):
return products.get(name, None)
def get_products_by_category(category):
return [product for product in products.values() if product["category"] == category]
작성된 상품을 조회 테스트 합니다.
print(get_product_by_name("TechPro Ultrabook")){'name': 'TechPro Ultrabook', 'category': 'Computers and Laptops', 'brand': 'TechPro', 'model_number': 'TP-UB100', 'warranty': '1 year', 'rating': 4.5, 'features': ['13.3-inch display', '8GB RAM', '256GB SSD', 'Intel Core i5 processor'], 'description': 'A sleek and lightweight ultrabook for everyday use.', 'price': 799.99}
두종류의 상품을 조회를 테스트 합니다.
print(get_products_by_category("Computers and Laptops"))
[{'name': 'TechPro Ultrabook', 'category': 'Computers and Laptops', 'brand': 'TechPro', 'model_number': 'TP-UB100', 'warranty': '1 year', 'rating': 4.5, 'features': ['13.3-inch display', '8GB RAM', '256GB SSD', 'Intel Core i5 processor'], 'description': 'A sleek and lightweight ultrabook for everyday use.', 'price': 799.99}, {'name': 'BlueWave Gaming Laptop', 'category': 'Computers and Laptops', 'brand': 'BlueWave', 'model_number': 'BW-GL200', 'warranty': '2 years', 'rating': 4.7, 'features': ['15.6-inch display', '16GB RAM', '512GB SSD', 'NVIDIA GeForce RTX 3060'], 'description': 'A high-performance gaming laptop for an immersive experience.', 'price': 1199.99},.... 생략
print(user_message_1)
print(category_and_product_response_1)
[1]
tell me about the smartx pro phone and the fotosnap camera, the dslr one. Also tell me about your tvs
[2]
[{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera']}, {'category': 'Televisions and Home Theater Systems'}]
4.1 Python 문자열을 Python 딕셔너리의 리스트로 읽습니다.
import json
def read_string_to_list(input_string):
if input_string is None:
return None
try:
input_string = input_string.replace("'", "\"") # Replace single quotes with double quotes for valid JSON
data = json.loads(input_string)
return data
except json.JSONDecodeError:
print("Error: Invalid JSON string")
return None
category_and_product_list = read_string_to_list(category_and_product_response_1)
print(category_and_product_list)
[{'category': 'Smartphones and Accessories', 'products': ['SmartX ProPhone']}, {'category': 'Cameras and Camcorders', 'products': ['FotoSnap DSLR Camera']}, {'category': 'Televisions and Home Theater Systems'}]
4.2 관련 있는 제품 및 카테고리에 대한 상세 제품 정보를 검색합니다.
def generate_output_string(data_list):
output_string = ""
if data_list is None:
return output_string
for data in data_list:
try:
if "products" in data:
products_list = data["products"]
for product_name in products_list:
product = get_product_by_name(product_name)
if product:
output_string += json.dumps(product, indent=4) + "\n"
else:
print(f"Error: Product '{product_name}' not found")
elif "category" in data:
category_name = data["category"]
category_products = get_products_by_category(category_name)
for product in category_products:
output_string += json.dumps(product, indent=4) + "\n"
else:
print("Error: Invalid object format")
except Exception as e:
print(f"Error: {e}")
return output_string
product_information_for_user_message_1 = generate_output_string(category_and_product_list)
print(product_information_for_user_message_1)
{ "name": "SmartX ProPhone", "category": "Smartphones and Accessories", "brand": "SmartX", "model_number": "SX-PP10", "warranty": "1 year", "rating": 4.6, "features": [ "6.1-inch display", "128GB storage", "12MP dual camera", "5G" ], "description": "A powerful smartphone with advanced camera features.", "price": 899.99 }
{ "name": "FotoSnap DSLR Camera", "category": "Cameras and Camcorders", "brand": "FotoSnap", "model_number": "FS-DSLR200", "warranty": "1 year", "rating": 4.7, "features": [ "24.2MP sensor", "1080p video", "3-inch LCD", "Interchangeable lenses" ], "description": "Capture stunning photos and videos with this versatile DSLR camera.", "price": 599.99 }
5. 상세 제품 정보를 기반으로 사용자 질문에 대한 답변을 생성합니다.
* "remember that your response to the user must be in korean: " 를 상단에 추가하면 한글로 답변을 합니다.
system_message = f"""
remember that your response to the user must be in korean:
You are a customer service assistant for a \
large electronic store. \
Respond in a friendly and helpful tone, \
with very concise answers. \
Make sure to ask the user relevant follow up questions.
"""
user_message_1 = f"""
tell me about the smartx pro phone and \
the fotosnap camera, the dslr one. \
Also tell me about your tvs"""
messages = [
{'role':'system',
'content': system_message},
{'role':'user',
'content': user_message_1},
{'role':'assistant',
'content': f"""Relevant product information:\n\
{product_information_for_user_message_1}"""},
]
final_response = get_completion_from_messages(messages)
print(final_response)
The SmartX ProPhone is a powerful smartphone with a 6.1-inch display, 128GB storage, a 12MP dual camera, and 5G capability. It is priced at $899.99 and comes with a 1-year warranty.
The FotoSnap DSLR Camera is a versatile camera with a 24.2MP sensor, 1080p video recording, a 3-inch LCD screen, and interchangeable lenses. It is priced at $599.99 and also comes with a 1-year warranty.
As for our TVs, we have a range of options. The CineView 4K TV is a 55-inch TV with 4K resolution, HDR, and smart TV features. It is priced at $599.99 and comes with a 2-year warranty.
We also have the CineView 8K TV, which is a 65-inch TV with 8K resolution, HDR, and smart TV features. It is priced at $2999.99 and also comes with a 2-year warranty.
Lastly, we have the CineView OLED TV, which is a 55-inch TV with 4K resolution, HDR, and smart TV features. It is priced at $1499.99 and comes with a 2-year warranty.
Is there anything specific you would like to know about these products?
한국어로 결과를 출력하도록 설정 하였을 경우 한글로 출력이 됩니다.
스마트X 프로폰은 강력한 스마트폰으로 6.1인치 디스플레이, 128GB 저장 용량, 12MP 듀얼 카메라, 5G 등의 기능을 제공합니다. 가격은 899.99달러입니다.
포토스냅 DSLR 카메라는 24.2MP 센서, 1080p 비디오, 3인치 LCD, 교환 가능한 렌즈 등의 기능을 제공합니다. 가격은 599.99달러입니다.
TV 제품 중에는 CineView 4K TV, CineView 8K TV, CineView OLED TV 등이 있습니다.
각각의 제품은 고화질 디스플레이와 스마트 기능을 제공합니다. 가격은 제품에 따라 다르며, CineView 4K TV는 599.99달러, CineView 8K TV는 2999.99달러, CineView OLED TV는 1499.99달러입니다.
어떤 제품에 대해 더 자세한 정보를 알고 싶으신가요?
[참고]
https://learn.deeplearning.ai/chatgpt-building-system
https://cobusgreyling.medium.com/chaining-large-language-model-prompts-81091daccaad
댓글
댓글 쓰기