Hoonsi

랭체인(LangChain) - 시작하기 > 빠른 시작 - 번역본 본문

기획, 개발, 마케팅, AI/랭체인(LangChain)

랭체인(LangChain) - 시작하기 > 빠른 시작 - 번역본

훈시스 2023. 7. 12. 11:58

#설치


LangChain을 설치하려면 실행합니다:

pip install langchain

자세한 내용은 설치 가이드를 참조하세요.

 

 

#환경 설정(Environment setup​)


LangChain을 사용하려면 일반적으로 하나 이상의 모델 공급자, 데이터 저장소, API 등과의 통합이 필요합니다. 이 예제에서는 OpenAI의 모델 API를 사용하겠습니다.

먼저 파이썬 패키지를 설치해야 합니다:

pip install openai

API에 액세스하려면 계정을 생성하고 여기로 이동하여 얻을 수 있는 API 키가 필요합니다. 키를 받으면 실행하여 환경 변수로 설정할 수 있습니다:

export OPENAI_API_KEY="..."

환경 변수를 설정하지 않으려면 OpenAI LLM 클래스를 시작할 때 openai_api_key라는 이름의 파라미터를 통해 키를 직접 전달할 수 있습니다:

from langchain.llms import OpenAI

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

 

 

#애플리케이션 구축 (Building an application)


이제 언어 모델 애플리케이션 구축을 시작할 수 있습니다. LangChain은 언어 모델 애플리케이션을 구축하는 데 사용할 수 있는 많은 모듈을 제공합니다. 모듈은 간단한 애플리케이션에서 독립형으로 사용할 수 있으며, 더 복잡한 사용 사례를 위해 결합할 수도 있습니다.

 

 

#거대 언어 모델(LLMs)


언어 모델에서 예측 가져오기
LangChain의 기본 빌딩 블록은 텍스트를 받아 더 많은 텍스트를 생성하는 LLM입니다.

예를 들어, 회사 설명을 기반으로 회사 이름을 생성하는 애플리케이션을 구축한다고 가정해 보겠습니다. 이를 위해서는 OpenAI 모델 래퍼를 초기화해야 합니다. 이 경우 출력이 더 무작위적이기를 원하므로 모델을 HIGH 온도로 초기화합니다.

from langchain.llms import OpenAI

llm = OpenAI(temperature=0.9)

이제 텍스트를 입력하고 예측을 얻을 수 있습니다!!

llm.predict("What would be a good company name for a company that makes colorful socks?")
# >> Feetful of Fun

 

 

#대화 모델(Chat models)


채팅 모델은 언어 모델의 변형입니다. 채팅 모델은 내부적으로 언어 모델을 사용하지만 노출되는 인터페이스가 약간 다릅니다. '텍스트 입력, 텍스트 출력' API를 노출하는 대신 '채팅 메시지'를 입력 및 출력으로 하는 인터페이스를 노출합니다.

하나 이상의 메시지를 채팅 모델에 전달하여 채팅 완료를 얻을 수 있습니다. 응답은 메시지가 됩니다. 현재 LangChain에서 지원되는 메시지 유형은 AI메시지(AIMessage), 휴먼메시지(HumanMessage), 시스템메시지(SystemMessage), 챗메시지(ChatMessage)이며, ChatMessage는 임의의 역할 매개변수를 받습니다. 대부분의 경우 휴먼메시지, AI메시지, 시스템메시지만 다루게 될 것입니다.

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={})

 

 

#프롬프트 템플릿(Prompt templates​)


 

대부분의 LLM 애플리케이션은 사용자 입력을 LLM에 직접 전달하지 않습니다. 일반적으로 사용자 입력을 프롬프트 템플릿이라고 하는 더 큰 텍스트에 추가하여 당면한 특정 작업에 대한 추가 컨텍스트를 제공합니다.

이전 예제에서 모델에 전달한 텍스트에는 회사 이름을 생성하는 지침이 포함되어 있었습니다. 이 애플리케이션의 경우 사용자가 모델에 지침을 제공할 필요 없이 회사/제품에 대한 설명만 제공하면 좋을 것 같습니다.

 

거대 언어 모델(LLMs)

PromptTemplates을 사용하면 쉽습니다! 이 경우 템플릿은 매우 간단합니다:

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?

 

대화 모델(chat models)

LLM과 마찬가지로 메시지프롬프트템플릿을 사용하여 템플릿을 사용할 수 있습니다. 하나 이상의 메시지 프롬프트 템플릿으로부터 ChatPromptTemplate을 빌드할 수 있습니다. ChatPromptTemplate의 format_messages 메서드를 사용하여 형식이 지정된 메시지를 생성할 수 있습니다.

이 메서드는 메시지 목록을 생성하기 때문에 문자열만 생성하는 일반 프롬프트 템플릿보다 약간 더 복잡합니다. 사용 가능한 더 많은 옵션을 이해하려면 여기에서 프롬프트에 대한 자세한 가이드를 참조하세요.

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.")
]

 

 

#체인(Chains)


 

 이제 모델과 프롬프트 템플릿이 생겼으니 이 두 가지를 결합하고 싶을 것입니다. 체인은 모델, 프롬프트 및 기타 체인과 같은 여러 기본 요소를 서로 연결(또는 체인)할 수 있는 방법을 제공합니다.

 

거대 언어 모델(LLMs)

가장 간단하고 일반적인 유형의 체인은 입력을 먼저 프롬프트 템플릿으로 전달한 다음 LLM으로 전달하는 LLMChain입니다. 기존 모델과 프롬프트 템플릿에서 LLM 체인을 구성할 수 있습니다.

이를 사용하여, 아래 코드를 :

llm.predict("What would be a good company name for a company that makes colorful socks?")

이렇게 대체할 수 있습니다 :

from langchain.chains import LLMChain

chain = LLMChain(llm=llm, prompt=prompt)
chain.run("colorful socks")

 

대화 모델(chat models)

LLM체인(LLMChain)은 대화 모델(chat models)에도 사용할 수 있습니다:

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'aime programmer.

 

 

#에이전트(Agents)


 

 첫 번째 체인은 미리 정해진 일련의 단계를 실행했습니다. 복잡한 워크플로를 처리하려면 입력에 따라 동적으로 작업을 선택할 수 있어야 합니다.

에이전트는 언어 모델을 사용하여 어떤 작업을 어떤 순서로 수행할지 결정합니다. 에이전트에게는 도구에 대한 액세스 권한이 주어지며, 최종 답변을 얻을 때까지 반복적으로 도구를 선택하고, 도구를 실행하고, 출력을 관찰합니다.

에이전트를 로드하려면 a(n)을 선택해야 합니다:

  • LLM/챗 모델: 에이전트를 구동하는 언어 모델입니다.
  • 도구: 특정 작업을 수행하는 함수입니다. 예를 들면 다음과 같습니다: Google 검색, 데이터베이스 조회, Python REPL, 기타 체인 등이 있습니다. 미리 정의된 도구 목록과 그 사양은 도구 문서를 참조하세요.
  • 상담원 이름: 지원되는 상담원 클래스를 참조하는 문자열입니다. 상담원 클래스는 언어 모델이 어떤 작업을 수행할지 결정하는 데 사용하는 프롬프트에 의해 크게 매개 변수화됩니다. 이 노트북은 가장 단순하고 높은 수준의 API에 초점을 맞추고 있으므로 지원되는 표준 상담원 사용법에 대해서만 다룹니다. 사용자 지정 에이전트를 구현하려면 여기를 참조하세요. 지원되는 상담원 목록과 그 사양은 여기를 참조하세요.

이 예에서는 검색 엔진을 쿼리하기 위해 SerpAPI를 사용하겠습니다.

SerpAPI Python 패키지를 설치해야 합니다:

pip install google-search-results

And set the SERPAPI_API_KEY environment variable.

거대 언어 모델(LLMs)

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

# The language model we're going to use to control the agent.
llm = OpenAI(temperature=0)

# The tools we'll give the Agent access to. Note that the 'llm-math' tool uses an LLM, so we need to pass that in.
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# Let's test it out!
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")
> Entering new AgentExecutor chain...

Thought: 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: San Francisco Temperature Yesterday. Maximum temperature yesterday: 57 °F (at 1:56 pm) Minimum temperature yesterday: 49 °F (at 1:56 am) Average temperature ...

Thought: I now have the temperature, so I can use the calculator to raise it to the .023 power.
Action: Calculator
Action Input: 57^.023
Observation: Answer: 1.0974509573251117

Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.

> Finished chain.
The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.

 

대화 모델(chat models)

에이전트(Agents)는 채팅 모델과 함께 사용할 수도 있으며, 에이전트 유형
'AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION'로 상담원을 초기화할 수 있습니다.

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

# The language model we're going to use to control the agent.
llm = OpenAI(temperature=0)

# The tools we'll give the Agent access to. Note that the 'llm-math' tool uses an LLM, so we need to pass that in.
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# Let's test it out!
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")
> Entering new AgentExecutor 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: Sudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.
Thought:I need to use a search engine to find Harry Styles' current age.
Action:
{
    "action": "Search",
    "action_input": "Harry Styles age"
}

Observation: 29 years
Thought:Now I need to calculate 29 raised to the 0.23 power.
Action:
{
    "action": "Calculator",
    "action_input": "29^0.23"
}

Observation: Answer: 2.169459462491557

Thought:I now know the final answer.
Final Answer: 2.169459462491557

> Finished chain.
'2.169459462491557'

 

 

#메모리(Memory)


지금까지 살펴본 체인과 에이전트는 상태 비저장형이었지만, 많은 애플리케이션에서 과거의 상호작용을 참조해야 할 필요가 있습니다. 예를 들어 챗봇이 과거 메시지의 맥락에서 새로운 메시지를 이해해야 하는 경우가 여기에 해당합니다.

메모리 모듈은 애플리케이션 상태를 유지할 수 있는 방법을 제공합니다. 기본 메모리 인터페이스는 간단합니다. 최근 실행된 입력과 출력에 따라 상태를 업데이트하고 저장된 상태를 사용하여 다음 입력을 수정(또는 컨텍스트화)할 수 있습니다.

여러 가지 내장 메모리 시스템이 있습니다. 이 중 가장 간단한 것은 버퍼 메모리로, 현재 입력에 마지막 몇 개의 입력/출력을 추가하는 것인데, 아래 예제에서는 이 메모리를 사용하겠습니다.

거대 언어 모델(LLMs)

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.

>> 'Hello! How are you today?'

이제 체인을 다시 실행하면

conversation.run("I'm doing well! Just having a conversation with an AI.")

모델에 전달되는 전체 프롬프트에는 첫 번째 상호 작용의 입력 및 출력과 함께 최신 입력이 포함되어 있음을 알 수 있습니다.

> 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:  Hello! How are you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:

> Finished chain.

>> "That's great! What would you like to talk about?"

 

대화 모델(chat models)

 채팅 모델로 초기화된 체인 및 상담원과 함께 메모리를 사용할 수 있습니다. 이것과 LLM용 메모리의 주요 차이점은 이전의 모든 메시지를 문자열로 압축하는 대신 고유한 메모리 개체로 보관할 수 있다는 점입니다.

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. Is there anything specific you'd 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 like this one. Is there anything else you'd like to know about me?