LLM 을 사용한 애플리케이션을 개발하다 보면 수정사항이 생길 수 있습니다. 이때 가능한 쉽고 빠르게 애플리케이션에 수정사항을 반영할 수 있도록 LangChain은

 

- configurable_fields() : Runnable의 특정 Fields(예: LLMs 내 parameters, HubRunnables 내 Prompts)를 실행 시에 설정할 수 있도록 해줌

- configurable_alternatives() : 실행 중에 특정 Runnable의 대안(예: LLMs, Prompts)을 설정할 수 있도록 해줌

 

의 2개 메소드를 제공합니다. 지난번 포스팅에서는 configurable_fileds() 에 대해서 소개했습니다. 

 

이번 포스팅에서는 이중에서도 configurable_alternatives() 을 사용해서 

   1. 실행 시 LLM 중 설정하기  

   2. 실행 시 Prompts 설정하기

에 대해서 소개하겠습니다. 

 

LangChain - configurable_alternatives() 특정 Runnable의 대안 설정하기

 

 

1. configurable_alternatives()를 사용해서 실행 시 LLM 중 설정하기

 

LangChain 의 Component 중에 LLM 모델과 ChatModel 이 있으며, 다른 구성요소와 통합이 되어있습니다.  LangChain은 Large Language Models (LLMs)와 ChatModels 사이에 구분을 두는데, 이 두 모델의 주요 차이점을 이해하는 것은 LangChain을 효과적으로 사용하는 데 중요합니다.

 

LangChain의 LLM과 ChatModel 모델의 주요 차이점은 다음과 같습니다. 

(1) 기능 및 목적 (Functionality and Purpose)

- LLMs (Large Language Models): GPT-3 또는 GPT-4와 같은 일반적인 목적의 언어 모델로, 주어진 프롬프트에 따라 텍스트를 생성할 수 있습니다. 다양한 주제와 형식에 걸쳐 인간과 유사한 텍스트를 이해하고 생성하도록 설계되었습니다. 

- ChatModels: LangChain 내에서 대화 맥락에 특화되어 설계된 전문화된 모델입니다. 이들은 여러 번의 교환을 통해 맥락을 유지하며 대화식 대화에 최적화되어 있으며, 대화식 상호 작용과 사용자 참여에 더 중점을 두고 있습니다. 


(2) 맥락 관리 (Context Management) 

- LLMs: 전통적인 LLM들은 일반적으로 단일 입력-출력 상호 작용(a single input-output interaction)을 처리합니다. 추가적인 맥락 관리 메커니즘 없이 여러 번의 교환에 걸쳐 대화 맥락을 유지하는 능력이 내재되어 있지 않습니다. 

- ChatModels: 이 모델들은 확장된 대화를 처리하도록 설계되어 대화 내역와 맥락(dialogue history and context)을 추적합니다. 대화의 연속성과 흐름(continuity and understanding of the conversation flow)을 이해하는 것이 중요한 챗봇과 같은 응용 프로그램에 적합합니다. 

 


(3) 훈련 및 튜닝 (Training and Tuning) 

- LLMs: 다양한 인터넷 텍스트를 기반으로 사전 훈련됩니다. 훈련은 대화에 특화된 것이 아니라 일관되고 문맥적으로 적절한 텍스트를 이해하고 생성하는 데 중점을 둡니다. 

- ChatModels: 대화 데이터에 미세 조정되거나 대화 처리에 본질적으로 더 나은 아키텍처를 가질 수 있어 대화식 시나리오에서 더 능숙합니다. 


(4) 사용 사례 (Use Cases) 

- LLMs: 콘텐츠 생성, 요약, 질문 답변 등 다양한 텍스트 생성 작업에 적합합니다. 

- ChatModels: 가상 보조원, 고객 서비스 챗봇 등 지속적인 대화가 핵심인 대화식 사용 사례에 특화되어 있습니다. 


(5) 응용 프로그램 통합 (Integration in Applications) 

- LLMs: 대화 기반 앱에서 맥락 관리를 위한 추가 계층이 필요한 다양한 AI 기반 텍스트 응용 프로그램의 백엔드 엔진으로 자주 사용됩니다. 

- ChatModels: 대화 상태를 유지하는 데 이미 최적화되어 있기 때문에 대화식 응용 프로그램에 플러그 앤 플레이(plug-and-play for conversational applications) 방식입니다. 

요약하자면, LangChain의 LLMs와 ChatModels는 모두 언어 생성 기술을 기반으로 하지만, ChatModels는 대화 맥락과 흐름(dialogue context and flow)을 유지하는 능력이 향상된 대화식 사용 사례에 특화된 반면, LLMs는 다양한 텍스트 생성 작업(a wide range of text generation tasks)에 적합한 더 일반적인 목적의 모델입니다. 

 

 

LangChain에서 통합하여 제공하는 LLMs, ChatModels 의 리스트는 아래 링크를 참조하세요. 

 

- LLMs : https://python.langchain.com/docs/integrations/llms/

- ChatModels: https://python.langchain.com/docs/integrations/chat/

 

아래 테이블은 LangChain의 ChatModels 에서 각 모델별로 invoke, async invoke, stream, async stream 별로 통합되어 있는 기능 현황을 정리한 것입니다. ('2023.12월 기준, 최신현황은 위 링크 참조하세요.) 

 

LangChain - ChatModels

 

LangChain - ChatModels Integration

 

 

먼저 openai, langchian 이 설치되어 있지 않다면 터미널에서 pip install 을 사용해서 설치해주기 바랍니다. 

 

! pip install -q openai langchain

 

 

 

이제 LangChain 의 configurable_alternatives() 메소드를 사용해서 ChatModels 중에서 ChatAnthropic, ChatOpenAI gpt-3.5-turbo, gpt-4 의 세 개 모델 중에서 실행 중에 설정해서 사용할 수 있도록 해보겠습니다. 

 

ConfigurableField 에서 id="llm" 으로 설정을 해서, 이후에 LLM 모델을 변경하고자 할 때 {"llm" : "Model_Name"} 처럼 사용하면 됩니다. 디폴트 LLM 모델은 defaulty_key="anthropic" 으로 설정했습니다. 

 

from langchain.chat_models import ChatAnthropic, ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain_core.runnables import ConfigurableField


llm = ChatAnthropic(temperature=0).configurable_alternatives(
    # This gives this field an id
    # When configuring the end runnable, we can then use this id to configure this field
    ConfigurableField(id="llm"),
    # This sets a default_key.
    # If we specify this key, the default LLM (ChatAnthropic initialized above) will be used
    default_key="anthropic",
    # This adds a new option, with name `openai` that is equal to `ChatOpenAI()`
    openai=ChatOpenAI(),
    # This adds a new option, with name `gpt4` that is equal to `ChatOpenAI(model="gpt-4")`
    gpt4=ChatOpenAI(model="gpt-4"),
    # You can add more configuration options here
)

prompt = PromptTemplate.from_template("Tell me a joke about {topic}")
chain = prompt | llm

* 코드 예시는 LangChain Tutorial 의 코드를 그대로 소개합니다. 

 

 

위에서 정의한 chain 을 invoke 해서 실행하면 디폴트로 설정한 ChatAntoropic 모델을 사용해서 답변을 생성합니다. 

 

# By default it will call Anthropic
chain.invoke({"topic": "bears"})

# AIMessage(content=" Here's a silly joke about bears:
# \n\nWhat do you call a bear with no teeth?\nA gummy bear!")

 

 

LLM 모델을 ChatOpenAI 로 변경해서 설정하려고 하면 아래처럼 chain.with_config(configurable = {"llm": "openai"}) 처럼 해주면 됩니다. 

 

# We can use `.with_config(configurable={"llm": "openai"})` to specify an llm to use
chain.with_config(configurable={"llm": "openai"}).invoke({"topic": "bears"})

# AIMessage(content="Sure, here's a bear joke for you:\n\nWhy don't bears wear shoes?
# \n\nBecause they already have bear feet!")

 

 

 

2. configurable_alternatives()를 사용해서  실행 시 Prompts 설정하기

 

다음으로 configurable_alternatives() 를 사용해서 ConfigurableField()에 여러개의 Prompts 를 등록해놓고, chain을 실행할 때 여러개의 Prompts 대안 중에서 선택해서 설정하여 사용할 수 있도록 해보겠습니다. 

 

아래 예에서는 Prompts 에 "joke"와 "poem" 의 2개를 등록해놓고, "joke"를 디폴트 프롬프트로 설정해두었습니다. 

 

llm = ChatAnthropic(temperature=0)
prompt = PromptTemplate.from_template(
    "Tell me a joke about {topic}"
).configurable_alternatives(
    # This gives this field an id
    # When configuring the end runnable, we can then use this id to configure this field
    ConfigurableField(id="prompt"),
    # This sets a default_key.
    # If we specify this key, the default LLM (ChatAnthropic initialized above) will be used
    default_key="joke",
    # This adds a new option, with name `poem`
    poem=PromptTemplate.from_template("Write a short poem about {topic}"),
    # You can add more configuration options here
)

chain = prompt | llm

 

 

디폴트 설정으로 위에서 정의한 chain을 invoke 해서 실행하면 "joke" 프롬프트가 적용이 되어서 답변을 생성합니다. 

 

# By default it will write a joke
chain.invoke({"topic": "bears"})

# AIMessage(content=" Here's a silly joke about bears:
# \n\nWhat do you call a bear with no teeth?\nA gummy bear!")

 

 

만약 프롬프트를 기본 설정인 "joke" 대신에 "poem"으로 실행 시에 바꾸고자 한다면 아래처럼 chain.with_config(configurable={"prompt": "poem"}) 처럼 Prompt 대안을 바꿔주면 됩니다. 

 

# We can configure it write a poem
chain.with_config(configurable={"prompt": "poem"}).invoke({"topic": "bears"})

# AIMessage(content=' Here is a short poem about bears:
# \n\nThe bears awaken from their sleep
# \nAnd lumber out into the deep\nForests filled with trees so tall
# \nForaging for food before nightfall 
# \nTheir furry coats and claws so sharp
# \nSniffing for berries and fish to nab
# \nLumbering about without a care
# \nThe mighty grizzly and black bear
# \nProud creatures, wild and free
# \nRuling their domain majestically
# \nWandering the woods they call their own
# \nBefore returning to their dens alone')

 

 

 

[ Reference ]

* LangChain Turorial - "Configure chain internals at runtime":

https://python.langchain.com/docs/expression_language/how_to/configure

 

 

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

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

 

 

 

728x90
반응형
Posted by Rfriend
,

LLM 을 사용한 애플리케이션을 개발하다 보면 수정사항이 생길 수 있습니다. 이때 가능한 쉽고 빠르게 애플리케이션에 수정사항을 반영할 수 있도록 LangChain은

 

- configurable_fields() : Runnable의 특정 Fields(예: LLMs 내 parameters, HubRunnables 내 Prompts)를 실행 시에 설정할 수 있도록 해줌

- configurable_alternatives() : 실행 중에 특정 Runnable의 대안(예: LLMs, Prompts)을 설정할 수 있도록 해줌

 

의 2개 메소드를 제공합니다. 

 

이번 포스팅에서는 이중에서도 configurable_fields() 을 사용해서 

- (1) LLM 내 parameter 설정하기

- (2) HubRunnables 내 Prompts 설정하기

에 대해서 소개하겠습니다. 

 

LangChain - configurable_fields()

 

 

 

(1) configurable_fields() 를 사용해서 LLM 내 parameters 설정하기

 

먼저 openai 와 langchain 모듈이 설치되어있지 않다면 pip install 을 사용해서 설치하기 바랍니다. 

 

! pip install -q openai langchain

 

 

ChatGPT LLM 모델에서 설정 가능한 주요 파라미터로는 다음과 같은 것들이 있습니다. 

 

- (a) Max Tokens: 모델이 응답에서 생성해야 하는 최대 토큰(단어 또는 문자, 모델의 토큰화에 따라 다름) 수입니다. 이것은 콘텐츠의 길이를 조절하는 것입니다. 설정 방법에 따라 한 줄짜리 또는 전체 소설을 얻을 수 있습니다. 생성할 텍스트의 최대 길이를 전달합니다. 현재 최대 4,096개의 토큰까지의 숫자를 받아들입니다. 기본값은 2,048입니다. 

- (b) Temperature: 응답의 무작위성을 조절합니다. 높은 온도는 더 다양하고 예측하기 어려운 결과를 낳으며, 낮은 온도는 출력을 더 결정론적으로 만들어 가장 가능성 있는 응답에 가깝게 합니다. 기본값은 0.7이며, 0부터 1 사이의 값을 받아들입니다. 

- (c) Frequency Penalty: 모델이 같은 줄이나 구절을 반복할 확률을 감소시키는 데 사용됩니다. 빈도 벌칙 매개변수는 반복을 처벌하며, 높은 숫자는 출력을 다양하게 만들어 드물게 사용되는 단어를 촉진시키고, 음수 값은 더 일반적이고 때로는 반복적인 언어를 얻습니다. -2.0부터 2.0 사이에서 변동되며, 기본값은 0입니다. 

 

 

아래 예제에서는 LLM 의 Temperature 파라미터를 configurable_fileds() 메소드를 사용해서 실행 시에 설정 가능하도록 하였습니다. 디폴트는 temperature=0.0 으로 해서 결정론적이고 보수적으로 응답이 생성되도록 하였습니다. 

 

ConfigurableFiled() 에서 Configuration을 하려는 Field의 id, name, description 의 메타정보를 입력해줄 수 있으며, 나중에 실행 시 재설정할 때 Distionary에서 'id' 와 재설정값을 {key: value} pair로 재설정해주면 됩니다. 

 

## (1) Configuration Fields with LLMs

from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain_core.runnables import ConfigurableField

OPENAI_API_KEY="sk-xxxx...."

model = ChatOpenAI(temperature=0, openai_api_key=OPENAI_API_KEY)\
.configurable_fields(
    temperature=ConfigurableField(
        id="llm_temperature",
        name="LLM Temperature",
        description="The temperature of the LLM",
    )
)

prompt = PromptTemplate.from_template("Write a joke about {topic}")
chain = prompt | model

chain.invoke({"topic": "dog"})
# AIMessage(content="Why don't dogs make good dancers?
#                    \n\nBecause they have two left paws!")
#                    \n\nBecause he heard the drinks were on the house!')

 

 

 

아래 예제 코드에서는 LLM 모델의 temperature=0.9 로 재설정하여 보다 창의적인 응답을 생성하도록 하였습니다. 

 

## Configuration of LLM's temperature
chain.with_config(configurable={"llm_temperature":0.9}).invoke({"topic": "dog"})

# AIMessage(content="Why couldn't the dog tell lies?
#                    \nBecause he always got caught up in his own ruff tales!")

 

 

 

 

(2) configurable_fields() 를 사용해서 HubRunnables 내 Prompts 설정하기

 

LangChain은 최근 프롬프트를 업로드, 탐색, 가져오기 및 관리하기 위한 장소로 LangChain Hub를 출시했습니다. LangChain Hub의 주요 목표는 개발자들이 새로운 사용 사례와 정교한 프롬프트를 발견할 수 있는 주요 장소가 되는 것입니다. LangChainHub는 자주 사용되는 프롬프트(Prompts), 체인(Chains), 에이전트(Agents) 등을 찾고 등록할 수 있는 곳입니다. (https://smith.langchain.com/hub)

 

LangChain Hub에서 Prompt를 다운로드 받아서 쉽게 코드를 확인하고, 또 수정도 할 수 있습니다. 

 

* LangChain Blog - LangChainHub post: https://blog.langchain.dev/langchainhub/

 

LangChain Hub : https://smith.langchain.com/hub

 

 

LangChain Hub를 사용하기 위해 먼저 langchainhub 모듈을 pip install을 사용해서 설치합니다. 

 

! pip install langchainhub

 

 

HubRunnable() 메소드와 configurable_fileds() 메소드를 사용해서 LangChain Hub 내에 있는 Prompts 를 chain 실행 시에 쉽게 바꿔치기 할 수 있습니다. 

 

아래 예에서는 기본 Prompt로 "rlm/rag-prompt" 를 사용하도록 설정을 해놓고, ConfigurableField() 에서 'id', 'name', 'description' 의 메타정보를 등록해주었습니다. 

 

from langchain.runnables.hub import HubRunnable

prompt = HubRunnable("rlm/rag-prompt").configurable_fields(
    owner_repo_commit=ConfigurableField(
        id="hub_commit",
        name="Hub Commit",
        description="The Hub commit to pull from",
    )
)


prompt.invoke({"question": "foo", "context": "bar"})

# ChatPromptValue(messages=[HumanMessage(
# content="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: foo 
# \nContext: bar 
# \nAnswer:")])

 

 

참고로 LangChain Hub 내 'rlm/rag-prompt' 에서 "RAG prompt" 부분만 소개하면 아래와 같습니다. 

 

# RAG prompt
from langchain import hub
prompt = hub.pull("rlm/rag-prompt")

 

 

 

이번에는 LangChain Hub 내 "rlm/rag-prompt-llama" Prompt 로 재설정해보겠습니다. Llama LLM 모델의 Prompt 로 변경되었습니다. 

 

prompt.with_config(
    configurable={"hub_commit": "rlm/rag-prompt-llama"}).invoke(
        {"question": "foo", "context": "bar"}
)

# ChatPromptValue(messages=[HumanMessage(
# content="
#   [INST]
#       <<SYS>> 
#           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.
#       <</SYS>> 
#   \nQuestion: foo 
#   \nContext: bar 
#   \nAnswer: 
# [/INST]")])

 

 

참고로 LangChain Hub 에서 'rlm/rag-prompt-llama' 에서 "RAG prompt" 부분만 소개하면 아래와 같습니다. 

 

# RAG prompt
from langchain import hub
prompt = hub.pull("rlm/rag-prompt-llama")

 

 

[ Reference ]

- LangChain Tutorial - Configuration Fields: https://python.langchain.com/docs/expression_language/how_to/configure

 

 

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

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

 

728x90
반응형
Posted by Rfriend
,