오늘의 TIL (LangChain 기초)


🔹 LangChain이란?

LangChain은 **대규모 언어 모델(LLM)**을 쉽게 활용할 수 있도록 도와주는 프레임워크다.
ChatGPT 같은 AI 모델을 활용하여 챗봇, 검색 시스템, 문서 요약, 질의응답 시스템 등을 만들 때 유용하다.

LangChain의 핵심 기능

  • LLM(예: OpenAI, Hugging Face)과 연결
  • 프롬프트 관리 (효율적인 질문 생성)
  • 대화 기억 기능 (메모리)
  • 여러 기능을 조합하여 실행하는 체인 기능

🔹 LangChain 설치 및 기본 설정

1️⃣ LangChain 설치

pip install langchain openai

2️⃣ OpenAI API 연결

import openai
from langchain.llms import OpenAI

openai.api_key = "YOUR_OPENAI_API_KEY"

llm = OpenAI(model_name="text-davinci-003")
response = llm("LangChain이 뭐야?")
print(response)

→ ChatGPT처럼 LLM을 활용하여 질문에 대한 답변을 받을 수 있다.


🔹 LangChain 기본 개념

개념 설명

LLM OpenAI, Hugging Face와 같은 AI 모델을 사용
Prompt Template 프롬프트(질문)를 템플릿으로 저장하고 활용
Memory 이전 대화 내용을 기억하여 맥락 유지
Chain 여러 기능을 조합하여 실행

🔹 LangChain 주요 기능 사용법

1️⃣ 프롬프트 템플릿 (Prompt Template)

프롬프트를 미리 정의해 두고, 원하는 내용만 채워 넣을 수 있다.

from langchain.prompts import PromptTemplate

template = PromptTemplate(
    input_variables=["topic"],
    template="'{topic}'에 대해 설명해줘."
)

prompt = template.format(topic="LangChain")
print(prompt)  # 'LangChain'에 대해 설명해줘.

2️⃣ 체인 (Chain)

프롬프트와 AI 모델을 연결하여 질문을 처리한다.

from langchain.chains import LLMChain
from langchain.llms import OpenAI

llm = OpenAI()
prompt = PromptTemplate(
    input_variables=["question"],
    template="질문: {question}"
)

chain = LLMChain(llm=llm, prompt=prompt)
response = chain.run("LangChain이 뭐야?")
print(response)

3️⃣ 메모리 (Memory)

이전 대화를 기억하여 맥락을 유지할 수 있다.

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
from langchain.llms import OpenAI

llm = OpenAI()
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory)

response1 = conversation.predict(input="안녕! 너는 누구야?")
response2 = conversation.predict(input="내가 방금 한 말을 기억해?")
print(response1)
print(response2)

오늘의 배운 점 & 느낀 점

1. LangChain을 사용하면 ChatGPT 같은 AI 서비스를 쉽게 만들 수 있다.
2.프롬프트 템플릿, 체인, 메모리를 활용하여 AI가 더 자연스럽게 대화할 수 있도록 할 수 있다.

+ Recent posts