'configurable_alternatives()'에 해당되는 글 1건

  1. 2023.12.23 [LangChain[ configurable_alternative() 메소드로 LLMs, Prompts Runnable의 대안 설정하기

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
,