2024. 1. 8. 21:08ㆍlangchain
Langchain 소개
LangChain은 사용자가 LLM()Large Language Models)을 중심으로 앱과 파이프라인을 빠르게 구축할 수 있게 해주는 인기 있는 프레임워크입니다.
- Prompt template : 프롬프트 템플릿은 다양한 유형의 프롬프트에 대한 템플릿입니다. '챗봇'처럼요. 스타일 템플릿, ELI5 질문 답변 등
- LLM: GPT-3, BLOOM 등과 같은 대규모 언어 모델
- Agent : 에이전트는 LLM을 사용하여 어떤 조치를 취해야 할지 결정하고, 웹 검색이나 계산기와 같은 도구를 사용할 수 있으며, 모두 논리적 작업 루프로 패키징됩니다.
- Menory : 단기 기억, 장기 기억.
!python -m venv langchain
!source langchain/bin/activate
!pip install -qU langchain
LangChain에서 LLM 사용하기
LangChain은 Hugging Face 및 OpenAI와 같은 여러 LLM 제공업체를 지원합니다.
이러한 다양한 LLM 통합 중 몇 가지를 사용하는 방법을 학습하여 LangChain 탐색을 시작하겠습니다.
HuggingFace
!pip install -qU huggingface_hub
Hugging Face 모델의 경우 Hugging Face Hub API 토큰이 필요합니다. 먼저 HuggingFace.co에서 계정을 만들고 오른쪽 상단에 있는 프로필 > 설정 >을 클릭하고, 액세스 토큰 >을 클릭, 새 토큰 >을 클릭하세요. 역할을 쓰기 >로 설정하세요. 생성 > 아래 토큰을 복사하여 붙여넣으세요.
import os
os.environ['HUGGINGFACEHUB_API_TOKEN'] = 'Huggingface HUB API Tocken'
그런 다음 Hugging Face Hub에 내장된 Inference API를 사용하여 HF Hub 모델(여기에서는 google/flan-t5-x1 사용)을 사용하여 텍스트를 생성할 수 있습니다.
from langchain import PromptTemplate, HuggingFaceHub, LLMChain
# initialize HF LLM
flan_t5 = HuggingFaceHub(
repo_id="google/flan-t5-xl",
model_kwargs={"temperature":1e-10}
)
# build prompt template for simple question-answering
template = """Question: {question}
Answer: """
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(
prompt=prompt,
llm=flan_t5
)
question = "Which NFL team won the Super Bowl in the 2010 season?"
print(llm_chain.run(question))
여기서 사전에는 프롬프트 템플릿에 설정된 입력 변수가 포함되어야 합니다("question"). 이는 우리가 묻고 싶은 질문에 매핑됩니다.
qs = [
{'question': "Which NFL team won the Super Bowl in the 2010 season?"},
{'question': "If I am 6 ft 4 inches, how tall am I in centimeters?"},
{'question': "Who was the 12th person on the moon?"},
{'question': "How many eyes does a blade of grass have?"}
]
res = llm_chain.generate(qs)
res
LLM이므로 모든 질문을 한 번에 입력해 볼 수 있습니다.
multi_template = """Answer the following questions one at a time.
Questions:
{questions}
Answers:
"""
long_prompt = PromptTemplate(
template=multi_template,
input_variables=["questions"]
)
llm_chain = LLMChain(
prompt=long_prompt,
llm=flan_t5
)
qs_str = (
"Which NFL team won the Super Bowl in the 2010 season?\n" +
"If I am 6 ft 4 inches, how tall am I in centimeters?\n" +
"Who was the 12th person on the moon?" +
"How many eyes does a blade of grass have?"
)
print(llm_chain.run(qs_str))
하지만 이 모델에서는 그다지 잘 작동하지 않습니다. 곧 이 접근 방식이 다른 모델에서 더 잘 작동되는 것을 보시게 될 것입니다.
OpenAI
!pip install -qU openai
OpenAI의 생성 모델을 사용할 수도 있습니다. 과정은 비슷합니다. OpenAI 웹사이트에서 계정에 가입하여 검색할 수 있는 API 키를 제공하세요. 그런 다음 아래에 API 키를 전달합니다.
import os
os.environ['OPENAI_API_KEY'] = 'OpenAI API Key'
그런 다음 어떤 모델을 사용할지 결정합니다. 몇 가지 옵션이 있지만 text-davinci-003을 사용하겠습니다.
from langchain.llms import OpenAI
davinci = OpenAI(model_name='text-davinci-003')
앞의 Hugging Face 예와 동일한 간단한 질문-답변 프롬프트 템플릿을 사용하겠습니다. 유일한 변경 사항은 이제 OpenAI LLM davinci를 사용 했다는 것입니다.
llm_chain = LLMChain(
prompt=prompt,
llm=davinci
)
print(llm_chain.run(question))
generate를 사용하여 여러 질문에 대해서도 동일한 작업을 수행합니다.
qs = [
{'question': "Which NFL team won the Super Bowl in the 2010 season?"},
{'question': "If I am 6 ft 4 inches, how tall am I in centimeters?"},
{'question': "Who was the 12th person on the moon?"},
{'question': "How many eyes does a blade of grass have?"}
]
llm_chain.generate(qs)
아래 형식은 질문을 반복적으로 제공하지 않고 대신 하나의 청크로 제공합니다.
qs = [
"Which NFL team won the Super Bowl in the 2010 season?",
"If I am 6 ft 4 inches, how tall am I in centimeters?",
"Who was the 12th person on the moon?",
"How many eyes does a blade of grass have?"
]
print(llm_chain.run(qs))
이제 모든 질문에 대하여 한 번에 답변할 수 있습니다. 언급한 바와 같이 text-davinci-003과 같은 더 강력한 LLM이 이러한 더 복잡한 쿼리를 처리할 가능성이 더 높습니다.
multi_template = """Answer the following questions one at a time.
Questions:
{questions}
Answers:
"""
long_prompt = PromptTemplate(
template=multi_template,
input_variables=["questions"]
)
llm_chain = LLMChain(
prompt=long_prompt,
llm=davinci
)
qs_str = (
"Which NFL team won the Super Bowl in the 2010 season?\n" +
"If I am 6 ft 4 inches, how tall am I in centimeters?\n" +
"Who was the 12th person on the moon?" +
"How many eyes does a blade of grass have?"
)
print(llm_chain.run(qs_str))
'langchain' 카테고리의 다른 글
04-langchain-chat (0) | 2024.01.13 |
---|---|
03a-token-counter (0) | 2024.01.12 |
03-langchain-conversational-memory (2) | 2024.01.11 |
02-langchain-체인 (1) | 2024.01.10 |
01-langchain-prompt-templates (1) | 2024.01.09 |