langchain
Langchain/1. Prompt
mhiiii
2024. 2. 6. 23:40
728x90
Prompt
Prompt란?
언어 모델에 대한 프롬프트는 사용자가 제공하는 지침이나 입력의 집합
1. Prompt의 구성 요소
일반적으로 프롬프트는 아래와 같은 순서로 구성된다.
- 명령어 (instructions)
- 외부 정보 또는 맥락 (External information or context)
- 사용자 입력 또는 질의 (User input or query)
- 출력 (Output indicator)
2. 함수
LLM에 전달되어야 할 명령을 더 쉽게 입력하게 해준다.
2-1. PromptTemplate
일반적인 프롬프트 템플릿 생성에 사용
코드 예시
(유튜브 실습을 통해 공부한 것을 정리)
prompt = PromptTemplate(
template="{주제} 5개를 추천해줘.\n{format_instructions}",
input_variables=["주제"],
partial_variables={"format_instructions": format_instructions}
)
model = OpenAI(temperature=0)
_input = prompt.format(주제="영화")
output = model(_input)
결과
2-2. ChatPromptTemplate
채팅 LLM에 프롬프트를 전달하는 데에 활용
특정 Schema 존재
- SystemMessage : AI에게 해야 할 일을 알려주는 배경 context
- HumanMessage : 사용자 메시지
- AIMessage : AI가 응답한 내용을 보여주는 상세 메시지
import 예시
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
코드 예시
(유튜브 실습을 통해 공부한 것을 정리)
template = """
너는 요리사야. 내가 가진 재료들을 갖고 만들 수 있는 요리를 추천하고, 그 요리의 레시피를 제시해줘.
내가 가진 재료는 아래와 같아.
<재료>
{재료}
"""
# ChatGPT 모델을 로드합니다.
chatgpt = ChatOpenAI(temperature=0)
#ChatGPT에게 역할을 부여합니다.(위에서 정의한 Template 사용)
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
#사용자가 입력할 매개변수 template을 선언합니다.
human_template = "{재료}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
system, human 템플릿을 함께 model에 전달
#ChatPromptTemplate에 system message와 human message 템플릿을 삽입합니다.
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
#ChatGPT API에 ChatPromptTemplate을 입력할 때, human message의 매개변수인 '재료'를 할당하여 전달합니다.
#이와 같은 방식을 통해 ChatGPT는 ChatPromptTemplate의 구성요소인 system message와 human message를 전달받아, 대답 생성에 활용합니다.
answer = chatgpt(chat_prompt.format_prompt(재료="양파, 계란, 사과, 빵").to_messages())
print(answer.content)
결과
2-3. FewShotPromptTemplate
예시 결과를 제시하여 원하는 결과물로 유도
- 원하는 결과물 형태가 특수할 때
- 구조화된 답변을 원할 때
코드 예시
prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="Question: {input}",
input_variables=["input"]
)
print(davinch3(
prompt.format(input="호날두로 삼행시 만들어줘")
))
결과
이외에도 다양한 함수가 존재한다.
PipelinePrompt, CustomPrompt 등..
참고
Langchain - PromptTemplate, LLM 프롬프트 입력을 더 편하게
728x90