langchain / / 2024. 6. 5. 15:00

[langchain] Prompt Template 사용법

PromptTemplate은 언어 모델에 프롬프트를 생성하기 위한 사전 정의된 포맷이다. 템플릿은 작업을 수행하는데 필요한 instructions, few-shot 예제, 특정 컨텍스트와 질문을 포함할 수 있다.

LangChain은 PromptTemplate으로 생성 및 작동하는 기능을 제공한다. LangChain은 다양한 언어모델에서 사용할 수 있는 템플릿을 재사용 할 수 있도록 템플릿을 만드는 것을 목표로 하고 있다.

일반적으로, 언어 모델은 프롬프트가 string이거나 list 형태여야 한다.

PromptTemplate

문자열 프롬프트에 대한 템플릿을 만드는데 PromptTemplate를 사용한다.

기본적으로 PromptTemplate는 템플릿의 문자열 포맷을 사용한다.

from langchain.prompts import PromptTemplate

template = "{task}을 수행하는 로직을 {language}으로 작성해 줘~"

prompt_template = PromptTemplate.from_template(template)
print(prompt_template) 
prompt = prompt_template.format(task="0부터 10까지 계산", language="파이썬")
print(prompt) 

실행결과

# prompt_template 출력값
input_variables=['language', 'task'] template='{task}을 수행하는 로직을 {language}으로 작성해 줘~'

# prompt 출력값
0부터 10까지 계산을 수행하는 로직을 파이썬으로 작성해 줘~

task, language 2개의 변수를 지정했고 format을 통해 해당 변수 값을 할당한다.

파일에서 읽기

template.json

{
  "name": null,
  "input_variables": [
    "num1",
    "num2",
    "operator"
  ],
  "input_types": {},
  "output_parser": null,
  "partial_variables": {},
  "template": "{num1} {operator} {num2}는?",
  "template_format": "f-string",
  "validate_template": false,
  "_type": "prompt"
}
prompt_template = load_prompt("prompts/template.json")
prompt = prompt_template.format(num1=3, num2=5, operator="+")
print(prompt)

실행 결과

3 + 5는?

ChatPromptTemplate

ChatPromptTemplate는 대화형에서 메시지의 템플릿을 구성하는데 사용된다.

각 채팅 메시지는 메시지 내용과 role이라는 추가 파라미터와 관련이 있다. 예를 들면, Open AI Completion API에서, 채팅 메시지는 AI Assistant, human, system 역할과 관련이 있다.

prompt_template = ChatPromptTemplate.from_messages(
    [
        ("system", "당신은 맛집 전문가이다."),
        ("ai", "나는 {city}을 방문하려고 한다."),
        ("human", "{question}"),
    ]
)

prompt = prompt_template.format_messages(city="서울", question="맛집 추천해줘")
print(prompt)

실행결과

[SystemMessage(content='당신은 맛집 전문가이다.'), AIMessage(content='나는 서울을 방문하려고 한다.'), HumanMessage(content='맛집 추천해줘')]

Message Prompts

LangChain은 다양한 종류의 MessagePromptTemplate를 제공한다. 가장 일반적으로 사용되는 것은 AIMessagePromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate이고 AI 메시지, 시스템 메시지, 사용자 메시지를 만드는데 사용된다.

from langchain_core.prompts import ChatMessagePromptTemplate

prompt = "나는 {country}로 여행가고 싶어"

chat_message_prompt = ChatMessagePromptTemplate.from_template(
    role="Steve", template=prompt
)
prompt = chat_message_prompt.format(country="한국")
print(prompt)

실행결과

content='나는 한국로 여행가고 싶어' role='Steve'

FewShotPromptTemplate

FewShotPromptTemplate의 목적은 사용자 입력을 기반으로 예제를 선택하고 최종 프롬프트에서 모델에 제시할 예제를 포맷팅하는데 있다.

FewShotPromptTemplate를 만드는 단계는 아래와 같다.

  1. example set 생성
  2. Few-shot example에 formatter 생성
  3. example과 formatter를 FewShotPromptTemplate에 주입
llm = ChatOpenAI()

examples = [
    {
        "question": "1 더하기 1은?",
        "answer": "2이지롱~",
    },
    {
        "question": "1 곱하기 1은?",
        "answer": "1이지롱~",
    },
]

example_prompt = PromptTemplate(
    input_variables=["question", "answer"],
    template="Question: {question}\n{answer}",
)

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {question}",
    input_variables=["question"],
)

question = "7x9은?"
chain = prompt | llm | StrOutputParser()
response = chain.invoke({"question": question})
print(response)

출력결과

63이지롱~

few-shot template을 사용하면 이전 답변을 했던 것과 동일한 패턴으로 답변을 하게 된다.

LangChain Hub

https://smith.langchain.com/hub에 보면 다양한 유형의 프롬프트가 있다. 이를 다운받아서 사용할 수 있다.

우선 langchainhub를 설치하자.

pipenv install langchainhub

hub에서 필요한 프롬프트를 검색해서 사용

prompt = hub.pull("rlm/rag-prompt")
# prompt = hub.pull("rlm/rag-prompt", api_url="https://api.hub.langchain.com")
print(prompt)

실행결과

input_variables=['context', 'question'] metadata={'lc_hub_owner': 'rlm', 'lc_hub_repo': 'rag-prompt', 'lc_hub_commit_hash': '50442af133e61576e74536c6556cefe1fac147cad032f4377b60c436e6cdcb6e'} messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template="You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\nQuestion: {question} \nContext: {context} \nAnswer:"))]

이렇듯 다양한 유형이 프롬프트가 있으니 필요한 것은 다운받아서 사용할 수가 있다.

참고

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유