
안녕하세요!
오늘은 LangChain 라이브러리를 사용하여 순차적 체인을 구축하는 방법에 대해 쉽게 설명해 드리겠습니다. 또한, 마지막에는 작동 가능한 전체 실습 코드를 제공하겠습니다. 이 코드에서는 .env 파일에서 OPENAI_API_KEY를 불러와서 사용합니다.
순차적 체인(Sequential Chain)은 여러 개의 체인을 순서대로 연결하여 실행하는 방법입니다. 각 체인의 출력값을 다음 체인의 입력값으로 사용할 수 있으며, 이를 통해 복잡한 작업을 단계별로 처리할 수 있습니다.
우리는 직원 Joe Schmo의 성과 평가서를 가지고 있습니다. 이 평가서를 기반으로 다음과 같은 작업을 수행하려고 합니다:
먼저 필요한 라이브러리를 설치하고 임포트해야 합니다.
pip install langchain openai python-dotenv
이제 파이썬 코드에서 필요한 모듈을 임포트합니다.
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import SequentialChain, LLMChain
from dotenv import load_dotenv
import os
.env 파일에서 OpenAI API 키를 불러옵니다.
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
.env 파일은 다음과 같이 작성되어야 합니다.
OPENAI_API_KEY=your_openai_api_key_here
이제 ChatOpenAI 모델을 초기화합니다.
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
template1 = "이 직원의 성과 평가서를 요약해 주세요:\n{review}"
prompt1 = ChatPromptTemplate.from_template(template1)
chain_1 = LLMChain(
llm=llm,
prompt=prompt1,
output_key="review_summary"
)
template2 = "위의 요약을 기반으로 이 직원의 주요 약점을 식별해 주세요:\n{review_summary}"
prompt2 = ChatPromptTemplate.from_template(template2)
chain_2 = LLMChain(
llm=llm,
prompt=prompt2,
output_key="weaknesses"
)
template3 = "식별된 약점을 개선하기 위한 개인화된 계획을 작성해 주세요:\n{weaknesses}"
prompt3 = ChatPromptTemplate.from_template(template3)
chain_3 = LLMChain(
llm=llm,
prompt=prompt3,
output_key="final_plan"
)
이제 세 개의 체인을 순차적으로 연결합니다.
seq_chain = SequentialChain(
chains=[chain_1, chain_2, chain_3],
input_variables=['review'],
output_variables=['review_summary', 'weaknesses', 'final_plan'],
verbose=True
)
input_variables: 첫 번째 체인에 필요한 입력 변수입니다.output_variables: 최종적으로 얻고자 하는 출력 변수들입니다.verbose: 실행 과정을 출력할지 여부를 결정합니다.employee_review = '''
Employee Information:
Name: Joe Schmo
Position: Software Engineer
Date of Review: July 14, 2023
Strengths:
Joe is a highly skilled software engineer with a deep understanding of programming languages, algorithms, and software development best practices. His technical expertise shines through in his ability to efficiently solve complex problems and deliver high-quality code.
One of Joe's greatest strengths is his collaborative nature. He actively engages with cross-functional teams, contributing valuable insights and seeking input from others. His open-mindedness and willingness to learn from colleagues make him a true team player.
Joe consistently demonstrates initiative and self-motivation. He takes the lead in seeking out new projects and challenges, and his proactive attitude has led to significant improvements in existing processes and systems. His dedication to self-improvement and growth is commendable.
Another notable strength is Joe's adaptability. He has shown great flexibility in handling changing project requirements and learning new technologies. This adaptability allows him to seamlessly transition between different projects and tasks, making him a valuable asset to the team.
Joe's problem-solving skills are exceptional. He approaches issues with a logical mindset and consistently finds effective solutions, often thinking outside the box. His ability to break down complex problems into manageable parts is key to his success in resolving issues efficiently.
Weaknesses:
While Joe possesses numerous strengths, there are a few areas where he could benefit from improvement. One such area is time management. Occasionally, Joe struggles with effectively managing his time, resulting in missed deadlines or the need for additional support to complete tasks on time. Developing better prioritization and time management techniques would greatly enhance his efficiency.
Another area for improvement is Joe's written communication skills. While he communicates well verbally, there have been instances where his written documentation lacked clarity, leading to confusion among team members. Focusing on enhancing his written communication abilities will help him effectively convey ideas and instructions.
Additionally, Joe tends to take on too many responsibilities and hesitates to delegate tasks to others. This can result in an excessive workload and potential burnout. Encouraging him to delegate tasks appropriately will not only alleviate his own workload but also foster a more balanced and productive team environment.
'''
results = seq_chain({'review': employee_review})
print("요약:")
print(results['review_summary'])
print("\n약점:")
print(results['weaknesses'])
print("\n개인화된 개선 계획:")
print(results['final_plan'])
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import SequentialChain, LLMChain
from dotenv import load_dotenv
import os
# OpenAI API 키 로드
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# LLM 모델 초기화
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
# 첫 번째 체인: 성과 평가서 요약
template1 = "이 직원의 성과 평가서를 요약해 주세요:\n{review}"
prompt1 = ChatPromptTemplate.from_template(template1)
chain_1 = LLMChain(
llm=llm,
prompt=prompt1,
output_key="review_summary"
)
# 두 번째 체인: 약점 파악
template2 = "위의 요약을 기반으로 이 직원의 주요 약점을 식별해 주세요:\n{review_summary}"
prompt2 = ChatPromptTemplate.from_template(template2)
chain_2 = LLMChain(
llm=llm,
prompt=prompt2,
output_key="weaknesses"
)
# 세 번째 체인: 개선 계획 생성
template3 = "식별된 약점을 개선하기 위한 개인화된 계획을 작성해 주세요:\n{weaknesses}"
prompt3 = ChatPromptTemplate.from_template(template3)
chain_3 = LLMChain(
llm=llm,
prompt=prompt3,
output_key="final_plan"
)
# 순차적 체인 연결
seq_chain = SequentialChain(
chains=[chain_1, chain_2, chain_3],
input_variables=['review'],
output_variables=['review_summary', 'weaknesses', 'final_plan'],
verbose=True
)
# 직원 성과 평가서 입력
employee_review = '''
Employee Information:
Name: Joe Schmo
Position: Software Engineer
Date of Review: July 14, 2023
Strengths:
Joe is a highly skilled software engineer with a deep understanding of programming languages, algorithms, and software development best practices. His technical expertise shines through in his ability to efficiently solve complex problems and deliver high-quality code.
One of Joe's greatest strengths is his collaborative nature. He actively engages with cross-functional teams, contributing valuable insights and seeking input from others. His open-mindedness and willingness to learn from colleagues make him a true team player.
Joe consistently demonstrates initiative and self-motivation. He takes the lead in seeking out new projects and challenges, and his proactive attitude has led to significant improvements in existing processes and systems. His dedication to self-improvement and growth is commendable.
Another notable strength is Joe's adaptability. He has shown great flexibility in handling changing project requirements and learning new technologies. This adaptability allows him to seamlessly transition between different projects and tasks, making him a valuable asset to the team.
Joe's problem-solving skills are exceptional. He approaches issues with a logical mindset and consistently finds effective solutions, often thinking outside the box. His ability to break down complex problems into manageable parts is key to his success in resolving issues efficiently.
Weaknesses:
While Joe possesses numerous strengths, there are a few areas where he could benefit from improvement. One such area is time management. Occasionally, Joe struggles with effectively managing his time, resulting in missed deadlines or the need for additional support to complete tasks on time. Developing better prioritization and time management techniques would greatly enhance his efficiency.
Another area for improvement is Joe's written communication skills. While he communicates well verbally, there have been instances where his written documentation lacked clarity, leading to confusion among team members. Focusing on enhancing his written communication abilities will help him effectively convey ideas and instructions.
Additionally, Joe tends to take on too many responsibilities and hesitates to delegate tasks to others. This can result in an excessive workload and potential burnout. Encouraging him to delegate tasks appropriately will not only alleviate his own workload but also foster a more balanced and productive team environment.
'''
# 순차적 체인 실행
results = seq_chain({'review': employee_review})
# 결과 출력
print("요약:")
print(results['review_summary'])
print("\n약점:")
print(results['weaknesses'])
print("\n개인화된 개선 계획:")
print(results['final_plan'])
이렇게 LangChain의 순차적 체인을 사용하여 복잡한 작업을 단계별로 처리하고, 각 단계의 결과를 다음 단계의 입력으로 활용할 수 있습니다. 이 예제를 통해 순차적 체인의 개념과 활용 방법을 이해하셨기를 바랍니다.
참고: 이 코드를 실행하려면 OpenAI API 키가 필요하며, 사용 시 발생하는 비용에 유의하시기 바랍니다.