LangChain(랭체인)은 LLM(Language Model) 기반 애플리케이션을 더 쉽게, 더 유연하게 개발할 수 있도록 돕는 파이썬 프레임워크입니다
In [ ]:
In [1]:
from google.colab import drive
drive.mount('/content/drive')
Mounted at /content/drive
In [ ]:
!jupyter nbconvert --to html "/content/drive/MyDrive/Colab Notebooks/TEST/notebook_test.ipynb"
In [ ]:
!pip install groq
!pip install langchain-groq
랭체인(LangChain): 대규모 언어 모델을 활용한 혁신적인 프레임워크¶
groq api quickstart example https://console.groq.com/docs/quickstart
프롬프트 | llm | json 랭체인 생성
In [ ]:
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import JsonOutputParser
import json
# Initialize Groq LLM
llm = ChatGroq(
model_name="llama-3.3-70b-versatile",
temperature=0.7
)
# Define the expected JSON structure
parser = JsonOutputParser(pydantic_object={
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"features": {
"type": "array",
"items": {"type": "string"}
}
}
})
# Create a simple prompt
prompt = ChatPromptTemplate.from_messages([
("system", """Extract product details into JSON with this structure:
{{
"name": "product name here",
"price": number_here_without_currency_symbol,
"features": ["feature1", "feature2", "feature3"]
}}"""),
("user", "{input}")
])
# Create the chain that guarantees JSON output
chain = prompt | llm | parser
def parse_product(description: str) -> dict:
result = chain.invoke({"input": description})
print(json.dumps(result, indent=2))
# Example usage
description = """The Kees Van Der Westen Speedster is a high-end, single-group espresso machine known for its precision, performance,
and industrial design. Handcrafted in the Netherlands, it features dual boilers for brewing and steaming, PID temperature control for
consistency, and a unique pre-infusion system to enhance flavor extraction. Designed for enthusiasts and professionals, it offers
customizable aesthetics, exceptional thermal stability, and intuitive operation via a lever system. The pricing is approximatelyt $14,499
depending on the retailer and customization options."""
parse_product(description)
실습 예제¶
In [11]:
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
# ChatGroq 모델 초기화
llm = ChatGroq(
model="gemma2-9b-it",
temperature=0.7,
max_tokens=300,
api_key=""
)
In [12]:
# 프롬프트 템플릿 정의
prompt = ChatPromptTemplate.from_messages([
("system", "당신은 친절하고 유익한 AI 조수입니다. 한국의 역사와 문화에 대해 잘 알고 있습니다."),
("human", "{question}")
])
In [13]:
# Chain 생성
chain = prompt | llm
In [15]:
# 질문 리스트
questions = [
"한글의 창제 원리는 무엇인가요?",
"김치의 역사와 문화적 중요성에 대해 설명해주세요.",
"조선시대의 과거 제도에 대해 간단히 설명해주세요."
]
# 각 질문에 대한 답변 생성
for question in questions:
response = chain.invoke({"question": question})
print(f"질문: {question}")
# print(f"답변: {response['text']}\n")
print(response)
질문: 한글의 창제 원리는 무엇인가요?
content='네, 저는 한국의 역사와 문화에 대해 꽤 잘 알고 있어요! \n\n한글의 창제 원리는 **자연의 소리와 발음을 표현하는 것**에 있습니다. \n\n세종대왕은 백성들이 어려운 한자가 익숙하지 않아 글을 배우기 힘들다는 것을 알고, **모두가 쓸 수 있는 새로운 글자**를 만들고자 하였습니다. \n\n그래서 그는 자연의 소리, 즉 **발음을 기반으로 글자를 만들었다는 점**이 가장 중요한 창제 원리입니다. \n\n한글의 글자는 \n\n* **자음**과 **모음**이 조합되어 만들어지며, \n* **모음은 입 모양을**, \n* **자음은 기관의 위치와 움직임**을 나타냅니다.\n\n이렇게 자연의 소리와 발음을 직접적으로 표현하는 방식으로 만들어진 한글은 언어학적으로 매우 뛰어난 글자 체계로 평가받고 있습니다. 😊 \n\n\n더 궁금한 점이 있으면 질문해주세요!\n' additional_kwargs={} response_metadata={'token_usage': {'completion_tokens': 271, 'prompt_tokens': 49, 'total_tokens': 320, 'completion_time': 0.492727273, 'prompt_time': 0.00171614, 'queue_time': 0.25225183, 'total_time': 0.494443413}, 'model_name': 'gemma2-9b-it', 'system_fingerprint': 'fp_10c08bf97d', 'service_tier': 'on_demand', 'finish_reason': 'stop', 'logprobs': None} id='run--cc8659cd-0955-43b1-ae3c-d24437695e9d-0' usage_metadata={'input_tokens': 49, 'output_tokens': 271, 'total_tokens': 320}
질문: 김치의 역사와 문화적 중요성에 대해 설명해주세요.
content='안녕하세요! 한국의 역사와 문화에 대해 알고 싶으시군요! 김치는 한국을 대표하는 요리로, 그 역사와 문화적 중요성은 매우 깊습니다. \n\n**김치의 역사:**\n\n* **고대부터의 뿌리:** 김치의 역사는 2,000년 이상 전으로 거슬러 올라갑니다. 삼국시대에는 이미 배, 무, 갓 등을 발효시켜 먹던 흔적이 발견됩니다. 당나라 사서 《삼국유사》에는 "나라 사람들이 김치를 훌륭하게 만들어 먹는다"고 기록되어 있으며, 김치는 이미 당시부터 한국인의 식단에 깊숙이 자리 잡고 있었습니다.\n* **전통적인 발효식품:** 김치는 과거에는 겨울철 식량 저장을 위해 만들어졌습니다. 농작물을 발효시켜 보존하면서 영양소를 유지하고, 겨울철 풍족한 식탁을 유지할 수 있었습니다.\n* **다양한 변형:** 시간이 지남에 따라 김치는 지역과 계층에 따라 다양하게 변형되었습니다. 배김치, 무김치, 갓김치 등 지역별 특산물을 이용' additional_kwargs={} response_metadata={'token_usage': {'completion_tokens': 300, 'prompt_tokens': 53, 'total_tokens': 353, 'completion_time': 0.545454545, 'prompt_time': 0.001726339, 'queue_time': 0.255672046, 'total_time': 0.547180884}, 'model_name': 'gemma2-9b-it', 'system_fingerprint': 'fp_10c08bf97d', 'service_tier': 'on_demand', 'finish_reason': 'length', 'logprobs': None} id='run--1b661c4f-a390-4748-9def-fa5b00bfc789-0' usage_metadata={'input_tokens': 53, 'output_tokens': 300, 'total_tokens': 353}
질문: 조선시대의 과거 제도에 대해 간단히 설명해주세요.
content='조선시대 과거는 과거 시험을 통해 관리 인사를 선발하는 제도입니다. 조선 시대에는 **"과거"**라는 이름으로 불리며, 이는 뛰어난 학문적 능력을 가진 인재를 찾아 국가 관리자로 임명하는 중요한 시험이었습니다. \n\n**과거의 주요 특징은 다음과 같습니다:**\n\n* **출제 과목:** 주로 **"사서"** 또는 **"유교 사상"** 을 다루는 지식이 평가되었습니다. 시, 소설, 역사 등 다양한 분야에서 깊이 있는 지식을 요구했습니다.\n* **시험 과정:** 면접과 토론이 포함된 복잡하고 엄격한 시험 과정을 거쳐야 했습니다.\n\n* **과거의 중요성:** 과거 합격자는 조선 사회에서 높은 사회적 지위와 권력을 누렸습니다. \n\n* **집단 면접:** 주로 학교 교육을 받은 유생들이 모여 몸으로 뛰어 낸 능력을 보여주는 시험이었습니다.\n\n* **오언:** 과거 시험은 조선 사회의 가장 중요한 사회적 유형을 나타내는 중요한 기관이었습니다' additional_kwargs={} response_metadata={'token_usage': {'completion_tokens': 300, 'prompt_tokens': 55, 'total_tokens': 355, 'completion_time': 0.545454545, 'prompt_time': 0.00178654, 'queue_time': 0.25959757499999997, 'total_time': 0.547241085}, 'model_name': 'gemma2-9b-it', 'system_fingerprint': 'fp_10c08bf97d', 'service_tier': 'on_demand', 'finish_reason': 'length', 'logprobs': None} id='run--27152f70-7f96-4caf-ab3a-90749bf401ec-0' usage_metadata={'input_tokens': 55, 'output_tokens': 300, 'total_tokens': 355}
'인공지능 > LLM' 카테고리의 다른 글
| 2. RAG(Retrieval-Augmented Generation) (1) | 2025.07.27 |
|---|