랭체인1.py

LangChain + Google Gemini를 활용한 기본 LLM 호출


개요

항목 내용
프레임워크 LangChain
LLM Google Gemini 2.5 Flash
핵심 개념 LCEL (LangChain Expression Language)

전체 소스 코드

# ⭐️ 1. API 키 설정
MyKey = "YOUR_GEMINI_API_KEY"  # 여기에 실제 키를 넣어 사용하세요.

import os
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from getpass import getpass

# ⭐️ API 키 설정 (키를 직접 입력하거나 환경 변수에 설정)
if "GEMINI_API_KEY" not in os.environ:
    os.environ["GEMINI_API_KEY"] = MyKey

# 1. 모델 인스턴스 생성
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash")

# 2. 프롬프트 템플릿 정의
prompt = ChatPromptTemplate.from_messages([
    ("system", "당신은 사용자에게 친절하고 유머러스하게 답변하는 챗봇입니다."),
    ("user", "{input}")
])

# 3. LCEL 체인 구축: 프롬프트 | LLM | 파서
# 이 파이프라인이 LLMChain을 대체합니다.
basic_chain = prompt | llm | StrOutputParser()

# 4. 체인 실행
question = "인공지능이란 무엇인지 아주 짧게 설명해줘."
response = basic_chain.invoke({"input": question})

print("--- 기본 LLM 호출 결과 ---")
print(response)

단계별 설명

Step 1: 라이브러리 임포트

from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
모듈 용도
ChatGoogleGenerativeAI Google Gemini 모델 래퍼
ChatPromptTemplate 프롬프트 템플릿 정의
StrOutputParser LLM 출력을 문자열로 파싱

Step 2: 프롬프트 템플릿

prompt = ChatPromptTemplate.from_messages([
    ("system", "당신은 친절한 챗봇입니다."),  # 시스템 메시지
    ("user", "{input}")                        # 사용자 입력 (변수)
])

역할 (Role) 종류:

Role 설명
system AI의 성격과 행동 방식 정의
user 사용자의 질문
assistant AI의 이전 응답 (대화 기록용)

Step 3: LCEL 체인 구축

basic_chain = prompt | llm | StrOutputParser()

LCEL (LangChain Expression Language)

파이프 연산자 |를 사용해 컴포넌트를 연결:

프롬프트 템플릿 → LLM 호출 → 출력 파싱
     prompt    →    llm    → StrOutputParser()

Step 4: 실행

response = basic_chain.invoke({"input": "질문 내용"})

invoke()에 딕셔너리로 변수 전달 → 최종 문자열 응답 반환


실행 방법

# 가상환경 활성화
conda activate myenv

# 필요 라이브러리 설치
pip install langchain langchain-google-genai google-generativeai

# 실행
python 랭체인1.py

출력 예시

--- 기본 LLM 호출 결과 ---
인공지능은 컴퓨터가 사람처럼 생각하고 학습하는 기술이야!
마치 로봇 친구가 공부해서 똑똑해지는 것과 같아~ 🤖