대규모 언어 모델(Large Language Models, LLMs)¶
1. LLM이란?
- "Large Language Model"의 약자로, 대규모 언어 모델을 의미
- 대량의 텍스트 데이터에서 학습하여 자연어 이해(NLU, Natural Language Understanding)와 자연어 생성(NLG, Natural Language Generation) 능력을 발휘함
- 문맥을 이해하고, 질문에 답변하며, 문서를 요약하고, 새로운 텍스트를 생성하는 등 다양한 자연어 처리 작업에 사용됨
2. LLM의 등장
- 2020년 OpenAI의 GPT-3 발표로 LLM이 세계 무대에 전면적으로 등장함
- 2022년 하반기 GPT-3.5, 2023년 상반기 GPT-4 발표로 LLM 및 생성 AI에 대한 관심이 급증함
- OpenAI의 GPT 시리즈, Google의 Bard와 Gemini 등이 대표적임
3. LLM의 발전
- LLM은 인공 지능과 기계 학습, 특히 딥러닝 기술을 기반으로 개발됨
- LLM의 핵심 가치는 방대한 정보를 처리하고 이해할 수 있는 능력에 있음
- 챗봇, 번역, 콘텐츠 추천, 작문 등 다양한 분야에서 활용됨.
- 특정 분야의 지식을 학습하여 전문가 수준의 답변을 제공할 수도 있음 (RAG)
LangChain 소개¶
1. LangChain이란
- LLM을 활용하여 애플리케이션과 파이프라인을 신속하게 구축할 수 있는 프레임워크
- 챗봇, 질의응답(QA), 요약 등 다양한 용도로 활용
2. 주요 특징
- LLM 애플리케이연 개발에 필요한 다양한 구성 요소를 "연결(chain)"하는데 중점
- 다양한 LLM 모델, 프롬프트 템플릿, Retriever 등을 제공
- 사용자는 다양한 요소를 "연결(chain)"하는 방식으로 편리하게 시스템 개발 및 구현 가능
LangChian, 주요 LLM 라이브러리 설치¶
- langchain : LLM 애플리케이션 개발 프레임워크
- langchain-openai : LangChain 프레임워크 내에서 OpenAI의 모델을 손쉽게 사용할 수 있도록 하는 확장 패키지
- openai : OpenAI API를 통해 접근하고 사용할 수 있도록 해주는 공식 Python 클라이언트
- google-generativeai : 구글이 제공하는 생성 AI 모델을 지원하는 파이썬 클라이언트
- cohere : 자연어 이해 및 생성을 위한 AI 모델을 제공하는 Cohere 플랫폼의 파이썬 클라이언드
필요한 라이브러리를 먼저 설치한다. 랭체인은 프로젝트 변경이 자주 일어나는 편이다. 버전에 따라 구문이 자주 달라지기 때문에, 개발 단계에서도 버전을 고정해서 사용하는 것이 좋을 것 같다.
!pip install -q langchain==0.1.6 langchain-openai==0.0.5 langchain_google_genai==0.0.6 openai==1.12.0 google-generativeai==0.3.2 cohere==4.47
OpenAI 인증키 설정¶
- API 인증키 등록 : OpenAI 홈페이지
API를 사용하려면 인증키를 발급한다. 유료이기 때문에 결제 정보 등록이 필요하다.
import os
os.environ['OPENAI_API_KEY'] = 'OPENAI_API_KEY'
LLM Chain¶
- 프롬프트 템플릿에 있는 정보만을 사용하여 응답(가장 기본적인 형태)
- 사용자로부터의 입력(질문)을 받고, 미리 정의된 프롬프트 템플릿에 기반해 LLM이 응답을 생성
OpenAI의 기본 모델인 GPT-3.5를 지정하고, "2022 카타르 월드컵 우승 국가는?" 라는 질문을 해본다. 아직 카타르 월드컵이 열리지 않았다는 답변을 하고 있다. 최신 정보가 학습되지 않았다는 사실을 알 수 있다.
# GPT 3.5
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model_name='gpt-3.5-turbo-0125')
질문:
llm.invoke("Who won the Qatar World Cup in 2022?")
답변:
AIMessage(content='As of now, the Qatar World Cup in 2022 has not taken place yet. The tournament is scheduled to be held from November 21 to December 18, 2022.')
이번에는 GPT-4를 사용해서 같은 질문을 해본다. 답변을 보면 2021년 10월까지 학습한 정보를 기반으로 대답하고 있다. 2022년 정보까지는 학습이 되지 않은 것으로 보인다. (이처럼 최신 정보를 답변하지 못하는 약점이 있다. 이런 문제 해결을 위해 검색 API를 사용해서 최신 정보를 질문과 함께 제공하고 답변을 얻는 RAG 기법이 활용된다.)
# GPT 4
llm2 = ChatOpenAI(model_name='gpt-4')
질문:
llm2.invoke("Who won the Qatar World Cup in 2022?")
답변:
AIMessage(content='As of my knowledge up to October 2021, the Qatar World Cup in 2022 has not yet taken place. Therefore, the winner is not known.')
랭체인의 체인을 구성하는 간단한 예제를 만들어본다. 프롬프트 템플릿을 만들고 input 필드를 통해서 사용자의 입력을 받도록 한다.
# 프롬프트 템플릿
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You are an expert in renewable energy."),
("user", "{input}")
])
print(prompt)
input_variables=['input'] messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template='You are an expert in renewable energy.')), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input'], template='{input}'))]
앞에서 정의한 프롬프트와 llm 모델을 랭체인의 LCEL 문법을 활용하여 체인으로 연결한다. 사용자의 입력(input)이 프롬프트 템플릿으로 전달된다. input 필드에 사용자의 입력이 들어가서 프롬프트 텍스트가 완성된다. 프롬프트의 출력이 그 다음 순서의 체인 요소인 llm 모델의 입력으로 전달되고, 모델은 사용자의 입력에 대한 답변을 최종 출력한다.
# Chain 구성
chain = prompt | llm
chain.invoke({"input": "What are the most promising renewable energy sources for the future?"})
출력:
AIMessage(content="There are several renewable energy sources that show great promise for the future, including:\n\n1. Solar power: Solar energy is abundant, clean, and can be harnessed using photovoltaic cells or concentrated solar power systems. With advancements in technology and decreasing costs, solar power is becoming increasingly competitive with traditional fossil fuels.\n\n2. Wind power: Wind energy is another abundant and clean resource that can be harnessed to generate electricity. Wind turbines are becoming more efficient and cost-effective, making wind power a viable option for meeting energy needs.\n\n3. Hydropower: Hydropower, or energy generated from flowing water, is one of the oldest and most widely used renewable energy sources. With the potential for both large-scale hydroelectric dams and small-scale run-of-river projects, hydropower continues to be a reliable source of clean energy.\n\n4. Geothermal energy: Geothermal energy harnesses heat from the Earth's core to generate electricity or provide heating and cooling. This renewable energy source is reliable and available 24/7, making it a promising option for the future.\n\n5. Biomass: Biomass energy is derived from organic materials such as wood, agricultural residues, and waste. Biomass can be converted into biofuels, biogas, or used directly for heating and electricity generation, providing a versatile and sustainable energy source.\n\n6. Tidal and wave energy: Tidal and wave energy capture the power of ocean currents and waves to generate electricity. While still in the early stages of development, these technologies have the potential to provide a consistent and predictable source of renewable energy.\n\nOverall, a combination of these renewable energy sources, along with advancements in energy storage technologies and grid integration, will play a crucial role in transitioning to a more sustainable and decarbonized energy system in the future.")
Google Gemini¶
- API 인증키 등록 : Google AI 홈페이지
구글의 생성 AI인 Gemini를 사용해서 같은 작업을 처리해본다.
os.environ["GOOGLE_API_KEY"] = "GOOGLE_API_KEY"
모델 정의:
from langchain_google_genai.chat_models import ChatGoogleGenerativeAI
gemini = ChatGoogleGenerativeAI(
model="gemini-pro",
temperature=0.5,
convert_system_message_to_human=True,
)
질문:
gemini.invoke("Who won the Qatar World Cup in 2022?")
답변: (Gemini의 출력에는 최신 정보가 반영되는 것으로 보인다. 2022년 카타르 월드컵의 우승국가를 아르헨티나라고 정확하게 답변하고 있다.)
AIMessage(content='Argentina')
체인 구성:
gemini_chain = prompt | gemini
gemini_chain.invoke({"input": "What are the most promising renewable energy sources for the future?"})
최종 출력:
AIMessage(content="1. **Solar Energy:** \n - Solar photovoltaic (PV) systems convert sunlight directly into electricity. \n - Solar thermal systems use sunlight to heat water or air for various applications. \n - The cost of solar panels has been decreasing, making solar energy more affordable. \n\n\n2. **Wind Energy:** \n - Wind turbines harness the kinetic energy of the wind to generate electricity. \n - Offshore wind farms have the potential to provide large amounts of clean energy. \n - Floating wind turbines can access stronger winds and reduce visual impact. \n\n\n3. **Hydropower:** \n - Hydropower plants use the energy of flowing water to generate electricity. \n - Pumped-storage hydropower systems can store energy for later use. \n - Small-scale hydropower systems can be implemented in remote areas. \n\n\n4. **Geothermal Energy:** \n - Geothermal power plants use heat from the Earth's interior to generate electricity. \n - Geothermal energy can also be used for heating and cooling buildings. \n - Enhanced geothermal systems can access deeper and hotter resources. \n\n\n5. **Biomass Energy:** \n - Biomass power plants burn organic materials, such as wood, agricultural waste, or municipal solid waste, to generate electricity. \n - Biomass energy can also be used for heating and cooking. \n - Advanced biomass conversion technologies, such as gasification and pyrolysis, can improve efficiency and reduce emissions. \n\n\n6. **Ocean Energy:** \n - Ocean energy technologies harness the energy of waves, tides, and ocean currents to generate electricity. \n - Wave energy converters can capture the energy of surface waves. \n - Tidal turbines can extract energy from the movement of tides. \n - Ocean thermal energy conversion (OTEC) systems utilize the temperature difference between warm surface waters and cold deep waters to generate electricity. \n\n\n7. **Hydrogen Energy:** \n - Hydrogen fuel cells can generate electricity through a chemical reaction between hydrogen and oxygen. \n - Hydrogen can be produced from renewable energy sources, such as solar and wind, through electrolysis. \n - Hydrogen can be stored and transported, making it a versatile energy carrier.")