프롬프트 템플릿을 '부분적(Partial prompt templates)'으로 사용하는 것이 의미 있을 수 있습니다. 예를 들어, 필요한 값들의 부분 집합을 전달하여, 나머지 값들만을 기대하는 새로운 프롬프트 템플릿을 만듭니다.

LangChain은 이를 두 가지 방법으로 지원합니다. 

1. 문자열 값을 가진 부분적 프롬프트 템플릿 (Partial prompt templates with Strings) 
2. 문자열 값을 반환하는 함수를 사용한 부분적 프롬프트 템플릿 (Partial prompt templates with Functions)

이 두 가지 다른 방법은 다른 사용 사례들을 지원합니다.

 

 

아래 예제에서 문자열 값을 반환하는 함수를 사용한 부분적 프롬프트 템플릿 (Partial with Functions) 을 만들고, LangChain에서 이를 수행하는 방법에 대해 소개하겠습니다. 

 

LangChain - Partial Prompt Templates

 

 

함수를 이용한 부분적 프롬프트 템플릿 사용 사례는 언제나 일반적인 방법으로 가져오고 싶은 변수가 있을 때 적용됩니다.

 

이의 대표적인 예는 날짜나 시간과 관련된 경우입니다. 항상 현재 날짜를 포함하고 싶은 프롬프트가 있다고 가정해보겠습니다. 프롬프트에 그것을 하드코딩 하여 다른 입력 변수들과 함께 전달하는 것은 매우 불편하며 또 휴면에러를 유발할 수도 있습니다. 이 경우, 항상 현재 날짜를 반환하는 함수(Function)로 프롬프트를 부분적(Partial prompt template)으로 사용하면 매우 편리합니다.

 

 

먼저 터미널에서 pip install 로 langchain, openai 모듈을 설치합니다. 

 

! pip install langchain openai

 

 

다음으로, 필요한 모듈을 importing 합니다. 그리고 LLM 모델로는 OpenAI 의 LLM을 쓸 것이므로 OpenAI API Key를 환경변수에 등록해줍니다. 

 

import os

from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser

os.environ["OPENAI_API_KEY"]="sk-xxxx..." # set with yours

 

 

 

이번 예제에서는 현재 날짜와 시간을 가져오는 사용자 정의 함수(User Defined Function)를 정의해서 사용하겠습니다. 

 

# Define a funtion that returns the current date
from datetime import datetime

def get_datetime():
    now = datetime.now()
    return now.strftime("%m/%d/%Y, %H:%M:%S")

 

 

 

부분적 프롬프트 템플릿(Partial prompt templates)을 만드는 방법에는 2가지가 있습니다. 

 

- 방법 1: PromptTemplate()로 prompt를 먼저 만들고, prompt.partial() 로 부분 프롬프트 생성

- 방법 2: PromptTemplate() 의 partial_varialbes 로 부분 변수 초기화하여 부분 프롬프트 생성

 

 

[방법 1] PromptTemplate()로 prompt를 먼저 만들고, prompt.partial() 로 부분 프롬프트 생성

 

# [option 1] Partial prompt template with a function
prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}", 
    input_variables=["adjective", "date"]
)

# -- Partil prompt here --
partial_prompt = prompt.partial(date=get_datetime)

print(partial_prompt.format(adjective="funny"))
# Tell me a funny joke about the day 01/03/2024, 23:39:21

 

 

 

[방법 2] PromptTemplate() 의 partial_varialbes 로 부분 변수 초기화하여 부분 프롬프트 생성

 

# [option 2] You can initialize the prompt with the partialed variables
prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}", 
    input_variables=["adjective"], 
    partial_variables={"date": get_datetime}, # -- partial prompt initialization here --
)

print(prompt.format(adjective="funny"))
# Tell me a funny joke about the day 01/03/2024, 23:41:26

 

 

 

이제, 위에서 만든 부분적 프롬프트 템플릿을 LLM Model, Output Parser와 '|'로 Chaining 해보겠습니다. 

 

# LLM Model
llm = OpenAI()

# Output Parser
parser = StrOutputParser()

# Chaining
chain = prompt | llm | parser

 

 

프롬프트 내 "date" 는 위에서 Partial Variable 로 해서 get_date() 함수로 현재의 날짜와 시간을 가져와서 부분적으로 입력을 해주었으며,  chain.invoke({"adjective": "funny"}) 를 사용해서 "adjective" 변수에 대해서만 사용자가 하드코딩으로 "funny"를 입력해주면 프롬프트 전체를 완성해서 LLM 모델에 전달하여 LLM 모델이 답변을 생성하도록 실행해보겠습니다. 

 

print(prompt.format(adjective="funny"))
# Tell me a funny joke about the day 01/03/2024, 23:41:26


response = chain.invoke({"adjective": "funny"})
print(response)

# Q: What did the calendar say when it saw the date and time?
# A: "Wow, I'm so far ahead of myself!"

 

 

아래에는 chain.invoke({"adjective": "sarcastic"}) 으로 바꾸어서 실행을 해보았습니다. 

promt.format(adjective="sarcastic") 으로 프롬프트를 확인해보면 {date} 부분에 get_date() 함수로 가져온 현지 날짜와 시간이 바뀌어 있음을 알 수 있습니다. 그리고 LLM 모델의 답변도 "adjective"와 "date"가 바뀌었기 때문에 위와는 다르게 바뀌었네요. 

 

print(prompt.format(adjective="sarcastic"))
# Tell me a sarcastic joke about the day 01/04/2024, 00:02:09


response = chain.invoke({"adjective": "sarcastic"})
print(response)

# Q: What did the clock say to the person at 00:01:20 on 1/4/2024? 
# A: "Happy Birthday, a day late!"

 

 

 

[ Reference ]

- LangChain - Partial Prompt Templates: 

https://python.langchain.com/docs/modules/model_io/prompts/partial

 

 

이번 포스팅이 많은 도움이 되었기를 바랍니다. 

행복한 데이터 과학자 되세요!  :-)

 

728x90
반응형
Posted by Rfriend
,