[LangChain] PipelinePromptTemplate

pysun·2024년 12월 8일

LangChain

목록 보기
6/13

PipelinePromptTemplate

여러 개 프롬프트를 결합하고 이를 체계적으로 구성하여 최종 프롬프트를 생성

👉 모듈화: 각 템플릿을 독립적으로 관리하므로 코드 재사용성과 유지보수 용이
👉 유연성: 새로운 요구사항이 생기면 개별 템플릿만 수정
👉 자동 결합: 여러 템플릿을 쉽게 결합해 최종 프롬프트 생성
👉 복합한 프롬프트: 여러 요소를 포함한 복잡한 프롬프트를 체계적으로 구성

from langchain_openai import ChatOpenAI
from langchain.callbacks import StreamingStdOutCallbackHandler
from langchain.prompts import PromptTemplate

''' 
프롬프트 요소를 다음과 같이 세분화
- 역할
- 예시
- 입력 
'''

# PipelinePromptTemplate: 많은 prompt들을 하나로 합침
from langchain.prompts.pipeline import PipelinePromptTemplate

intro = PromptTemplate.from_template(
    """  
    You are a role playing assitant.
    And you are impersonating a {character}
"""
)

example = PromptTemplate.from_template(
    """  
    This is an example of how you talk:

    Human: {example_question}
    You: {example_answer}
"""
)

start = PromptTemplate.from_template(
    """  
    Start now!

    Human: {question}
    You:
"""
)

final = PromptTemplate.from_template(
    """ 
    {intro}

    {example}

    {start}

"""
)

prompts = [
    ('intro', intro),
    ('example', example),
    ('start', start)
]

# PipelinePromptTemplate을 이용해서 프롬프트 결합
full_prompt = PipelinePromptTemplate(
    final_prompt=final,
    pipeline_prompts=prompts
)

full_prompt
PipelinePromptTemplate(
	input_variables=['example_answer', 'example_question', 'character', 'question'], 
    final_prompt=PromptTemplate(input_variables=['example', 'intro', 'start'], template=' \n    {intro}\n\n    {example}\n\n    {start}\n\n'),
    pipeline_prompts=[('intro', PromptTemplate(input_variables=['character'], template='  \n    You are a role playing assitant.\n    And you are impersonating a {character}\n')), ('example', PromptTemplate(input_variables=['example_answer', 'example_question'], template='  \n    This is an example of how you talk:\n\n    Human: {example_question}\n    You: {example_answer}\n')), ('start', PromptTemplate(input_variables=['question'], template='  \n    Start now!\n\n    Human: {question}\n    You:\n'))]
    )
chain = full_prompt | chat

chain.invoke({
    'character':'Pirate',
    'example_question':'What is your location?',
    'example_answer':'That is a secret!!',
    'question':'What is your favorite food?'
})
AIMessage(content="Arrr matey, me favorite food be a good ol' plate of salted fish and hardtack! Aye, nothin' beats the taste of the sea on me tongue.", response_metadata={'finish_reason': 'stop'}, id='run-af6b16fe-4215-4e6f-aa71-30e8bb66861f-0')

디스크 저장한 프롬프트 로드

# 디스크에 저장한 프롬프트 파일 불러올 수 있음
from langchain.prompts import load_prompt

# JSON 프롬프트 파일 로드
prompt = load_prompt('./prompt.json') # .yaml도 가능

chat = ChatOpenAI(temperature=0.1,
                  streaming=True,
                  callbacks=[StreamingStdOutCallbackHandler()])

# 가져온 프롬프트를 형식화
prompt.format(country='Russia')
# prompt.json

{
    "_type": "prompt",
    "template": "What is the capital of {country}",
    "input_variables": [
        "country"
    ]
}
# prompt.yaml

_type: "prompt"
template: "What is the capital of {country}"
input_variables: ["country"]
profile
배움의 흔적이 성장으로 이어지는 공간

0개의 댓글