상세 컨텐츠

본문 제목

Quick start

LangChain

by LYShin 2023. 6. 23. 20:00

본문

- 출처 : https://python.langchain.com/docs/get_started/quickstart

- 이 블로그 글은 LangChain API document의 글을 기반으로 번역되었으며 이 과정에서 약간의 내용이 추가되었습니다.

- 입력 문장이나 메세지는 한글도 가능하지만, 비용 측면에서 영어가 더 저렴하여 원본과 같이 영어로 진행했습니다.

- LangChain을 사용하기 위한 LLM API는 다양하지만, 본 글에서는 OpenAI의 API를 사용합니다.

 

 

 

1. Installation

LangChain 설치는 pipconda, 두 가지로 할 수 있습니다. anaconda prompt로 접근하면 아래 두 코드로 설치 가능하고, Jupyter를 사용하는 경우에는 pip과 conda 앞에 ! 혹은 %를 붙여 설치하면 됩니다. 

#1.
pip install langchain

#2.
conda install langchain -c conda-forge

 

2. Environment setup

LangChain을 사용하는 것은 하나 이상의 model providers, data stores, APIs 등이 결합된 통합이 필요합니다. 예를 들어, OpenAI의 model APIs가 있습니다. 자세한 설치 방법은 이후에 설명하겠습니다.

from langchain.llms import OpenAI

# 1
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

# 2
llm = OpenAI(openai_api_key="...")

 

3. Building an application

이제 Language model application을 만드는 것을 시작할 수 있습니다. LangChain은 LM application을 만드는데 사용되는 많은 모듈을 제공합니다. 모듈은 간단한 App을 위해 단 한 가지만 사용될 수도 있고, 더 복잡한 App을 위해 복합적으로 사용될 수 있습니다.

 

4. LLMs


LM으로부터 completion를 얻어봅니다. LangChain의 기본 Block은 LLM입니다. LLM은 텍스트를 입력받아 텍스트를 반환합니다.

예를 들어, 회사의 description을 기반으로 회사 이름을 생성해내는 application을 만드는 것을 생각해 봅시다. 이를 위해 우리는 OpenAI model wrapper를 사용해야합니다. 이 예시에서 무작위의 대답을 얻기 위해 높은 temperature를 설정합니다.

 

** OpenAI에서 제공하는 API에서 temperature은 대답의 자유도의 크기라고 생각하면 편합니다. temperature가 클수록 더 다양한 대답을 제공합니다.

llm = OpenAI(temperature=0.9)

text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))

>> Socktastical.

 

5. Chat models

Chat model은 language models의 변형입니다. Chat model은 내부적으로 language model을 사용하지만, 그것이 표현하는 인터페이스는 사뭇 다릅니다. 'text in, text out'이 기본적인 LM의 인터페이스라면, Chat model의 인터페이스는 'chat messages'의 input, output입니다.

한개 이상의 메세지를 chat model에 입력하여 chat completion을 받을 수 있습니다. completion 역시 메세지형식입니다. Langchain에서 지원하는 메세지의 종류는 AIMessage, HumanMessage, SystemMessage, 그리고 ChatMessage입니다. ChatMessage는 chat model의 completion이라고 생각하면 쉽게 이해할 수 있습니다. 따라서 대부분의 경우 ChatMessage를 제외한 3개의 메세지를 다룰 것입니다. 

 

ChatOpenAIpredict_messagespredict를 사용할 수 있습니다. chat model이 메세지를 입력으로 받아 메세지를 출력하는 것은 일반적인 LLM과의 차별점입니다. 이 차별점을 이해하는 것은 유용하지만, 때로는 동일하게 다루는 것이 편리합니다. LangChainpredict 인터페이스를 사용하여 일반적인 LLM을 사용하는 것처럼 chat model을 다룰 수 있습니다.

from langchain.chat_models import ChatOpenAI
from langchain.schema import AIMessage, HumanMessage, SystemMessage
chat = ChatOpenAI(temperature = 0)

chat.predict_messages([HumanMessage(content = "Translate this sentence from English to French. I love programming.")])
>> AIMessage(content="J'aime programmer.", additional_kwargs={}, example=False)

chat.predict("Translate this sentence from English to French. I love programming.")
>> J'aime programmer

 

6. Prompt templates

대부분의 LLM app은 유저의 입력을 바로 LLM에 통과시키지 않습니다. 일반적으로 그것은 prompt template라고 불리는 텍스트와 함께 유저의 입력을 더해 추가적인 텍스트를 만듭니다.

이전 예시에서 company name을 생성하는데 사용한 텍스트에는 product와 instruction이 포함되어있습니다. 그러나 유저입장에서 오직 company/product에 대한 description만 제공하는 것이 더 편할 것입니다.

 

LLM과 Chat model을 활용하는 예시를 다룹니다.

# 1. LLM

from langchain.prompts import PromptTemplate

prompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")
prompt.format(product="colorful socks")
'What is a good name for a company that makes colorful socks?'

 

# 2. Chat model

from langchain.prompts.chat import  ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
 HumanMessage(content='I love programming.', additional_kwargs={}, example=False)]


7. Chains

우리는 modelprompt template이 준비되었으니, 이제 그 두개를 결합해야합니다. chain은 model, prompt, 그리고 다른 chain과 같은 여러가지 기본 요소를 연결하는데 사용됩니다.

이번에는 LLM과 Chat model을 활용하는 예시를 다룹니다.

# 1. LLM
from langchain.chains import LLMChain

chain = LLMChain(llm=llm, prompt=prompt)
chain.run("colorful socks")
'\n\nKaleidoscope Kicks.'

 

# 2. chat model

from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

chat = ChatOpenAI(temperature=0)

template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run(input_language="English", output_language="French", text="I love programming.")
"J'adore la programmation."

8. Agents

첫 번째 chain은 미리 결정된 단계의 시퀀스를 실행습니다. 복잡한 작업흐름을 다루기 위해, 입력에 근거하여 동적으로 행동을 선택할 필요가 있습니다.

이 때 Agents가 필요합니다. Agents는 LM을 사용하여 어떤 순서로 어떤 행동을 할지 결정합니다. Agent는 tools에 대해 접근할 수 있고, 반복하여 tool을 선택하고, 사용하여 최종 응답을 반환합니다.

 

agent를 로드하기 위해 3가지가 필요합니다.

  • LLM/Chat model : agent를 구동하는 language model
  • Tool(s) : 특정한 duty를 수행하는 기능. Google Search, Database lookup, Python REPL 등을 의미
  • Agent name : agent class를 reference하는 문자열. agent class는 어떤 작업을 수행할 지 결정하기 위해 언어 모델이 사용하는 prompt에 의해 크게 매개변수화됩니다.

LLM과 Chat model을 활용하는 예시를 다룹니다.

 

** tool 중 하나인 serpapi를 사용하기 위해서는 SERPAPI KEY 필요합니다.

 

# 환경 변수에 SERPAPI KEY를 입력합니다.
os.environ["SERPAPI_API_KEY"] = SERPAPI_API_KEY

# 1. LLM
from langchain.agents import load_tools, initialize_agent, AgentType
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)

tools = load_tools(['serpapi','llm-math'], llm= llm)

agent = initialize_agent(tools, llm, agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose = True)
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")
> Entering new  chain...
 I need to find the temperature first, then use the calculator to raise it to the .023 power.
Action: Search
Action Input: "High temperature in SF yesterday"
Observation: High: 66.2ºf @1:40 PM Low: 55.04ºf @5:56 AM Approx. Precipitation / Rain Total: in. 1hr.
Thought: I now need to use the calculator to raise 66.2 to the .023 power
Action: Calculator
Action Input: 66.2^.023
Observation: Answer: 1.1012343099196273
Thought: I now know the final answer
Final Answer: 1.1012343099196273

> Finished chain.
'1.1012343099196273'

 

# 2. chat model

from langchain.agents import load_tools, initialize_agent, AgentType
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI

chat = ChatOpenAI(temperature=0)

llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)

agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
> Entering new  chain...
Thought: I need to use a search engine to find Olivia Wilde's boyfriend and a calculator to raise his age to the 0.23 power.
Action:
```
{
  "action": "Search",
  "action_input": "Olivia Wilde boyfriend"
}
```

Observation: Looks like Olivia Wilde and Jason Sudeikis are starting 2023 on good terms. Amid their highly publicized custody battle – and the actress' ...
Thought:Now I need to use a calculator to raise Jason Sudeikis' age to the 0.23 power.
Action:
```
{
  "action": "Calculator",
  "action_input": "pow(47, 0.23)"
}
```


Observation: Answer: 2.4242784855673896
Thought:The answer to the question "Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?" is 2.4242784855673896.
Final Answer: 2.4242784855673896.

> Finished chain.
'2.4242784855673896.'

 

9. Memory

많은 app에서 이전 대화를 레퍼런스로 사용하길 원할 것입니다. 이는 chatbot의 경우와 같이 이전 메세지의 맥락에서 새로운 메세지의 내용을 이해하길 원하는 것과 비슷합니다.

Memory module은 application state를 유지하는 방법을 제공합니다. base Memory interface는 간단합니다. 가장 최근에 주어진 입력과 출력을 저장하고, 출력을 다음 입력으로 사용합니다.

많은 내장된 메모리 시스템 중 가장 단순한 방법은 buffer memory입니다. buffer memory는 현재 입력에 최근 몇 개의 입/출력을 앞부분에 추가하는 방식입니다. 

 

LLM과 Chat model을 활용하는 예시를 다룹니다.

 

 

# 1. LLM

from langchain import OpenAI, ConversationChain

llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, verbose=True)

conversation.run("Hi there!")
> Entering new  chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

Current conversation:

Human: Hi there!
AI:

> Finished chain.
" Hi there! It's nice to meet you. My name is AI. What's your name?"
conversation.run("My name is Lee!")
> Entering new  chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

Current conversation:
Human: Hi there!
AI:  Hi there! It's nice to meet you. My name is AI. What's your name?
Human: My name is Lee!
AI:

> Finished chain.
' Nice to meet you, Lee! What can I do for you today?'

 

 

# 2. chat model

from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory

prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template(
        "The following is a friendly conversation between a human and an AI. The AI is talkative and "
        "provides lots of specific details from its context. If the AI does not know the answer to a "
        "question, it truthfully says it does not know."
    ),
    MessagesPlaceholder(variable_name="history"),
    HumanMessagePromptTemplate.from_template("{input}")
])

llm = ChatOpenAI(temperature=0)
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)

conversation.predict(input="Hi there!")
'Hello! How can I assist you today?'
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
"That sounds like fun! I'm happy to chat with you. What would you like to talk about?"
conversation.predict(input="Tell me about yourself.")
"Sure! I am an AI language model created by OpenAI. 
I was trained on a large dataset of text from the internet, 
which allows me to understand and generate human-like language. 
I can answer questions, provide information, and even have conversations with people like you!
Is there anything specific you'd like to know about me?"

관련글 더보기

댓글 영역