Package 설치 및 Llama 모델 선정
!pip install -q langchain langchain-huggingface
Package 먼저 설치해야 한다.
LangChain을 설치하고, langchain-hugginface를 해야 huggingface의 모델을 langchain과 사용 가능하다.
모델로는 Meta의 Llama-3.1-8B-Instruct 모델을 선정했다.
Meta의 Llama 라인업에는 3B, 8B, 70B, 405B 등 다양한 크기가 있는데, 이 중 추론 속도, 메모리 요구량, 성능이 균형적인 모델이 8B 정도의 사이즈이다.
또한 Instruct 버전은 정책, 결정, 요약이나 분석 작업에 즉시 활용이 가능하다.
특히 Llama-3.1의 Instrcut 버전은 정책 결정, 조건 기반 의사결정, Prompt Follwing 능력에서 매우 강하다.
마지막으로 Llama-3.1-8B는 INT4/INT8 quant로 돌리면 6~10GB의 VRAM이면 충분하다.
이 정도면 RTX 4090, 5090 스펙에서 Local로도 돌릴 수 있는 규모이다.
(70B 모델의 경우 40GB 이상의 VRAM이 필요한데, VRAM 사이즈를 마개조를 하지 않는 이상 시중 GPU로는 돌리기 어렵다)
Hugging Face 공식 문서 (https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct)
meta-llama/Llama-3.1-8B-Instruct · Hugging Face
The information you provide will be collected, stored, processed and shared in accordance with the Meta Privacy Policy. LLAMA 3.1 COMMUNITY LICENSE AGREEMENT Llama 3.1 Version Release Date: July 23, 2024 "Agreement" means the terms and conditions for use,
huggingface.co

(다운로드 수가 무려 500만을 넘는다)
Llama 모델의 접근 권한 요청
Meta에서 공개한 Llama 3.1 계열 모델은 Gated Repo로 설정되어 있어, 접근 권한을 따로 승인받아야 한다.
- 모델 페이지: meta-llama/Llama-3.1-8B-Instruct
해당 페이지로 들어가면, “Request Access” 버튼을 통해 접근 권한을 요청할 수 있다.

일반적으로 승인까지는 길면 수 시간, 짧으면 10분 안에도 완료될 수 있다. (본인의 경우 3분 정도만에 승인이 났다)
https://huggingface.co/settings/gated-repos (여기서 승인 여부 확인)
Hugging Face – The AI community building the future.
huggingface.co

터미널에서 토큰으로 로그인하고 모델 불러오기
IDE의 터미널에서 아래 명령어를 실행하여 로그인한다.
huggingface-cli login

이후 위에서 생성한 자신의 Hugging Face 계정 API 토큰을 입력한다.
HuggingFace API 토큰은 아래에서 발급받을 수 있다. (https://huggingface.co/settings/tokens)
Hugging Face – The AI community building the future.
huggingface.co
발급받은 토큰을 제대로 입력하면 아래와 같이 성공적으로 로그인이 되고, 모델을 다운로드받을 수 있다.

모델 다운로드의 경우 아래 코드를 통해 다운로드 받는다.
from langchain_huggingface import ChatHuggingFace, HuggingFacePipeline
from langchain_core.prompts import ChatPromptTemplate
# --- 모델 준비 ---
llm = HuggingFacePipeline.from_model_id(
model_id="meta-llama/Llama-3.1-8B-Instruct",
task="text-generation",
device=0,
pipeline_kwargs=dict(
max_new_tokens=64,
do_sample=False,
repetition_penalty=1.02,
),
)
다른 모델을 사용하는 경우 HuggingFace 페이지에 들어가서

모델 이름 복사 버튼을 누르고, model_id를 저장한 다음, model_id 부분에 붙여넣기를 하면 된다.

이 코드를 실행하면 HuggingFace Hub에서 Llama-3.1-8B-Instruct 모델과 관련 weight·tokenizer·config 파일이 자동으로 다운로드되고, 이후 로컬 디스크(cache 폴더)에 저장된 모델을 불러와 로딩한다. (로컬 캐시 위치: ~/.cache/huggingface/)
최초 실행 시에는 다운로드 시간이 필요하지만, 이후부터는 로컬 캐시에서 즉시 모델을 불러오기 때문에 속도가 빠르다.
Fetching 4 files: 0%| | 0/4 [00:00<?, ?it/s]
→ "모델 파일 4개를 다운로드 중이다" 라는 의미.
(보통 config.json, tokenizer.json, model.safetensors 등 총 4개)
여기서 max_new_tokens는 모델의 답변 길이를 조정하는 변수로, 이를 지정해주지 않으면 답변이 매우 짧게 나온다.
현재 필요한 Task가 긴 답변이 필요없어서 64로 지정하긴 했지만, LLM 모델을 사용하는 Task에 따라 Test를 하면서 max_new_tokens 사이즈를 적절히 수정을 해줘야 한다.

+ 추가로 LangChain이 아닌 transformer 패키지로 모델을 다운받는 경우는 HuggingFace 공식 페이지에 상세하게 나와있다.
https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct

오픈소스의 HuggingFacePipeline Wrapper 기반 방식 이해하기
LangChain의 HuggingFace는 클라우드 API로 모델을 호출하는 것과 약간의 차이가 있다.
보통 ChatGPT, Cluade Sonnet의 경우 LangChain 내부에서 이것을 자동으로 OpenAI / Anthropic / Google API wrapper로 연결해버린다. 이 경우에는 LLM 객체를 직접 생성하지 않아도 된다.
- "claude-sonnet-..."
- "gpt-4o"
- "gemini-pro"
- "openai/gpt-4o-mini"
# pip install -qU langchain "langchain[anthropic]"
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
# Run the agent
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
HuggingFace의 경우 곧바로 llm을 쓰는 것이 아니라. 모델을 ipeline을 통해 모델을 로딩을 한 다음에 chat_model에 담아준다.
이 chat_model을 invoke하는 식으로 동작한다.
즉, 이 방식은 LangChain이 직접 Hugging Face 모델을 로컬에서 로드해서 GPU로 실행하는 구조다.
- HuggingFacePipeline → 로컬 모델 (GPU 필요)
- create_agent(model="...") → 클라우드 API 모델 (OpenAI / Anthropic / Google 등)
이후 HuggingFacePipeline.from_model_id() 호출을 수행한다
llm = HuggingFacePipeline.from_model_id(
model_id="meta-llama/Llama-3.1-8B-Instruct",
task="text-generation",
device=0,
마지막으로 LangChain wrapper 생성하는데,
ChatHuggingFace(HuggingFacePipeline(...))
위 형태로 LangChain이 이 모델을 LLM처럼 호출할 수 있도록 wrapping하고 나면, .invoke(), .stream(), .batch()처럼 모델을 불러와 사용할 수 있게 된다.
chat_model = ChatHuggingFace(llm=llm)
ai_message = chat_model.invoke("What is Telecommunication?")
ai_message의 내용을 다음과 같이 확인할 수 있다.
print(ai_message.content)
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024
<|eot_id|><|start_header_id|>user<|end_header_id|>
What is Telecommunication?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Telecommunication refers to the exchange of information over a distance through the use of technology, such as the internet, telephone networks, radio waves, and other communication systems. It involves the transmission, reception, and processing of information in the form of text, voice, images, or data.
Telecommunication can be categorized into several
일단, max_new_tokens를 64로 설정해서, ai_message의 길이가 짤렸다. (대답을 하다가 말았다..)
max_new_tokens를 늘리면 정상적으로 출력된다.
신기하게 모델이 학습한 최신 날짜의 정보가 2023년 12월이라고 한다.
즉, 2024년부터의 정보를 물어보면, LLM이 해당 내용을 모르기 때문에 답변을 제대로 못한다는 것.
(이를 보완하기 위해 RAG가 나왔다)
또한 답변 앞에 <|eot_id|><|start_header_id|>user<|end_header_id|>와 같은 문자열이 붙어있는데, 이것이 open model의 전형적인 특징이다. user가 물어봤고, assitant가 대답한다는 내용이 들어가 있다.
그래서 Open Model을 써서 LLM 서비스를 구현하려면 답변 패턴을 본 다음에 파싱해서 우리가 원하는 답변만을 추출해야 한다.

RTX 5090의 기준으로 답변 하나를 생성하는데 3.9초가 걸렸다.
추가로 양자화를 진행하면 모델의 사이즈를 줄이고 답변 속도를 줄일 수 있다.
전체 코드 (Jupyter Notebook 환경 + RTX 5090)
import torch
print(torch.cuda.is_available())
print(torch.cuda.device_count())
>>> True
>>> 1
from langchain_huggingface import ChatHuggingFace, HuggingFacePipeline
from langchain_core.prompts import ChatPromptTemplate
# --- 모델 준비 ---
llm = HuggingFacePipeline.from_model_id(
model_id="meta-llama/Llama-3.1-8B-Instruct",
task="text-generation",
device=0,
pipeline_kwargs=dict(
max_new_tokens=64,
do_sample=False,
repetition_penalty=1.02,
),
)
>>> c:\Users\gksyb\anaconda3\envs\aiagent\lib\site-packages\tqdm\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
Loading checkpoint shards: 100%|██████████| 4/4 [00:10<00:00, 2.54s/it]
Device set to use cuda:0
The following generation flags are not valid and may be ignored: ['temperature', 'top_p']. Set `TRANSFORMERS_VERBOSITY=info` for more details.
chat_model = ChatHuggingFace(llm=llm)
ai_message = chat_model.invoke("What is Telecommunication?")
print(ai_message.content)
>>> <|begin_of_text|><|start_header_id|>system<|end_header_id|>
Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024
<|eot_id|><|start_header_id|>user<|end_header_id|>
What is Telecommunication?<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Telecommunication refers to the exchange of information over a distance through the use of technology, such as the internet, telephone networks, radio waves, and other communication systems. It involves the transmission, reception, and processing of information in the form of text, voice, images, or data.
Telecommunication can be categorized into several'Agentic AI 구축 > LangChain & LangGraph' 카테고리의 다른 글
| [LangGraph 기초 2] Edge의 개념 (병렬 실행과 분기) (0) | 2026.01.03 |
|---|---|
| [LangGraph 기초 1] Node와 State의 개념 (0) | 2026.01.03 |
| LangChain과 LangChain 생태계 총정리 (LangChain, LangGraph, LangSmith) (0) | 2025.12.16 |
| LangChain의 한계와 이를 보완하기 위한 LangGraph의 구조 (0) | 2025.11.19 |
| LangChain에서의 MCP 구현 설명 (@tool의 의미) (0) | 2025.11.05 |