환경 설정 단계에서는 API 키를 로드하고, 필요한 라이브러리들을 불러옵니다.
from dotenv import load_dotenv
from langchain_teddynote import logging
import os
# 환경 변수 로드 (API 키 등)
load_dotenv()
# 모델 및 캐시 경로 설정
os.environ["TRANSFORMERS_CACHE"] = "./cache/"
os.environ["HF_HOME"] = "./cache/"
# LangSmith 추적 설정 (프로젝트 이름 입력)
logging.langsmith("CH04-Models")
LangSmith 추적을 시작합니다.
LangChain에서 사용할 OpenAI 모델을 로드합니다. 여기서는 ChatOpenAI
객체를 생성하여 모델을 준비합니다.
from langchain_openai import ChatOpenAI
# ChatOpenAI 객체 생성
gpt = ChatOpenAI(
temperature=0.7, # 창의성과 일관성을 조절
model_name="gpt-4o", # 모델명
)
프롬프트는 모델이 처리할 입력 형식을 정의합니다. 여기서는 흔히 사용되는 "질문-응답" 형식의 프롬프트 템플릿을 사용합니다.
from langchain.prompts import PromptTemplate
# 프롬프트 템플릿 정의
prompt = PromptTemplate.from_template(
"Q: {question}\nA:"
)
프롬프트와 모델을 연결하여 체인을 생성합니다. 이 단계에서 출력 파서를 포함시켜 응답을 처리할 수 있게 합니다.
from langchain_core.output_parsers import StrOutputParser
# 프롬프트와 모델을 연결하는 체인 생성
chain = prompt | gpt | StrOutputParser()
최종적으로 체인을 실행하여 결과를 출력합니다. 스트리밍 기능을 추가하여 응답을 실시간으로 확인할 수 있습니다.
from langchain_teddynote.messages import stream_response
# 체인 실행
response = chain.invoke({"question": "대한민국의 수도는 어디인가요?"})
print(response)
# 스트리밍 출력
answer = gpt.stream("사랑이 뭔가요?")
stream_response(answer)
아래는 수정된 전체 코드 예시로, 출력 파서와 스트리밍을 적절한 단계에 포함하고, 흔히 사용되는 프롬프트 템플릿을 반영하였습니다.
from dotenv import load_dotenv
from langchain_teddynote import logging
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_teddynote.messages import stream_response
import os
# 1. 환경 설정
load_dotenv()
# 모델 및 캐시 경로 설정
os.environ["TRANSFORMERS_CACHE"] = "./cache/"
os.environ["HF_HOME"] = "./cache/"
logging.langsmith("CH04-Models")
LangSmith 추적을 시작합니다.
# 2. 모델 로드 (ChatOpenAI 객체 생성)
gpt = ChatOpenAI(
temperature=0.7,
model_name="gpt-4o",
)
# 3. 프롬프트 구성
prompt = PromptTemplate.from_template(
"Q: {question}\nA:"
)
# 4. 체인 생성
chain = prompt | gpt | StrOutputParser()
# 5. 체인 실행
response = chain.invoke({"question": "대한민국의 수도는 어디인가요?"})
print(response)
# 스트리밍 출력
answer = gpt.stream("사랑이 뭔가요?")
stream_response(answer)
ChatOpenAI
객체를 생성.OPENAI_API_KEY
: OpenAI API 키 설정HUGGINGFACEHUB_API_TOKEN
: Hugging Face Hub API 토큰 설정LANGCHAIN_API_KEY
: LangSmith API 키 설정LANGCHAIN_TRACING_V2
: 추적 활성화 (true
또는 false
)LANGCHAIN_ENDPOINT
: LangSmith API 엔드포인트 설정LANGCHAIN_PROJECT
: 추적할 프로젝트 이름TRANSFORMERS_CACHE
: 모델 및 토크나이저 캐시 경로HF_HOME
: Hugging Face 홈 디렉토리 설정pip install langchain
pip install langchain-teddynote
pip install transformers
pip install huggingface_hub
logging.langsmith("ProjectName")
: 프로젝트 이름을 지정하여 로깅 시작모델 ID 지정:
model_id
: 사용하려는 모델의 ID (예: "beomi/llama-2-ko-7b"
)모델 로드 옵션:
task
: 수행할 작업 (예: "text-generation"
, "text-classification"
)
pipeline_kwargs
: 추가 파이프라인 옵션 (예: {"max_new_tokens": 512}
)
device
: GPU 사용 시 디바이스 번호 설정 (0
또는 -1
(CPU), "auto"
)
batch_size
: 배치 크기 설정 (예: 2
)
모델 로드 예시:
from langchain_community.llms import GPT4All
llm = GPT4All(
model="./models/EEVE-Korean-Instruct-10.8B-v1.0-Q8_0.gguf",
backend="gpu",
streaming=True,
callbacks=[StreamingStdOutCallbackHandler()],
)
프롬프트 템플릿:
template
: 프롬프트 템플릿 문자열 (예: "{country}의 수도는 어디인가요?"
)input_variables
: 프롬프트에서 사용할 변수 목록 (예: ["country"]
)프롬프트 템플릿 생성:
PromptTemplate.from_template()
: 템플릿에서 프롬프트 생성프롬프트 구성 예시:
from langchain_core.prompts import PromptTemplate
template = "{country}의 수도는 어디인가요?"
prompt_template = PromptTemplate.from_template(template)
체인 연결:
|
: 파이프 연산자로 프롬프트, 모델, 출력 파서를 연결출력 파서:
StrOutputParser()
: 문자열 출력을 위한 기본 파서체인 생성 예시:
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
model = ChatOpenAI(model_name="gpt-4")
chain = prompt_template | model | StrOutputParser()
chain.invoke({"input_variable": "value"})
: 단일 질의 실행chain.stream({"input_variable": "value"})
: 스트리밍 방식으로 질의 실행chain.batch([{"input_variable": "value1"}, {"input_variable": "value2"}])
: 배치 처리 방식으로 여러 질의 실행ainvoke
: 비동기 단일 호출astream
: 비동기 스트리밍 호출abatch
: 비동기 배치 호출response = chain.invoke({"country": "대한민국"})
print(response)
이 단계별로 세부 설정을 통해 LangChain 애플리케이션을 구성하고 실행할 수 있습니다. 각 단계의 옵션을 적절히 조정하여 모델의 동작을 최적화할 수 있습니다.
다음은 LangChain을 사용하여 LLM(대형 언어 모델) 애플리케이션을 구축할 때의 단계별 세부 설정 옵션들을 나열한 것입니다. 이 과정은 환경 설정부터 모델 로드, 프롬프트 구성, 체인 생성, 체인 실행까지 포함합니다.
OPENAI_API_KEY
: OpenAI API 키 설정HUGGINGFACEHUB_API_TOKEN
: Hugging Face Hub API 토큰 설정LANGCHAIN_API_KEY
: LangSmith API 키 설정LANGCHAIN_TRACING_V2
: 추적 활성화 (true
또는 false
)LANGCHAIN_ENDPOINT
: LangSmith API 엔드포인트 설정LANGCHAIN_PROJECT
: 추적할 프로젝트 이름TRANSFORMERS_CACHE
: 모델 및 토크나이저 캐시 경로HF_HOME
: Hugging Face 홈 디렉토리 설정pip install langchain
pip install langchain-teddynote
pip install transformers
pip install huggingface_hub
logging.langsmith("ProjectName")
: 프로젝트 이름을 지정하여 로깅 시작모델 ID 지정:
model_id
: 사용하려는 모델의 ID (예: "beomi/llama-2-ko-7b"
)모델 로드 옵션:
task
: 수행할 작업 (예: "text-generation"
, "text-classification"
)
pipeline_kwargs
: 추가 파이프라인 옵션 (예: {"max_new_tokens": 512}
)
device
: GPU 사용 시 디바이스 번호 설정 (0
또는 -1
(CPU), "auto"
)
batch_size
: 배치 크기 설정 (예: 2
)
모델 로드 예시:
from langchain_community.llms import GPT4All
llm = GPT4All(
model="./models/EEVE-Korean-Instruct-10.8B-v1.0-Q8_0.gguf",
backend="gpu",
streaming=True,
callbacks=[StreamingStdOutCallbackHandler()],
)
프롬프트 템플릿:
template
: 프롬프트 템플릿 문자열 (예: "{country}의 수도는 어디인가요?"
)input_variables
: 프롬프트에서 사용할 변수 목록 (예: ["country"]
)프롬프트 템플릿 생성:
PromptTemplate.from_template()
: 템플릿에서 프롬프트 생성프롬프트 구성 예시:
from langchain_core.prompts import PromptTemplate
template = "{country}의 수도는 어디인가요?"
prompt_template = PromptTemplate.from_template(template)
체인 연결:
|
: 파이프 연산자로 프롬프트, 모델, 출력 파서를 연결출력 파서:
StrOutputParser()
: 문자열 출력을 위한 기본 파서체인 생성 예시:
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
model = ChatOpenAI(model_name="gpt-4")
chain = prompt_template | model | StrOutputParser()
chain.invoke({"input_variable": "value"})
: 단일 질의 실행chain.stream({"input_variable": "value"})
: 스트리밍 방식으로 질의 실행chain.batch([{"input_variable": "value1"}, {"input_variable": "value2"}])
: 배치 처리 방식으로 여러 질의 실행ainvoke
: 비동기 단일 호출astream
: 비동기 스트리밍 호출abatch
: 비동기 배치 호출response = chain.invoke({"country": "대한민국"})
print(response)