LangChain 아키텍처와 핵심 추상화
LLMs, ChatModels, PromptTemplates, OutputParsers, Runnables를 포함한 LangChain의 구성 요소 모델과 이들이 파이프라인으로 결합되는 방식을 이해합니다.
LangChain 아키텍처와 핵심 추상화은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Engineering Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What LangChain Actually Is
LangChain is a framework for building applications powered by language models. Rather than writing raw API calls and glue code yourself, LangChain provides reusable components that snap together into pipelines. It supports multiple LLM providers (OpenAI, Anthropic, Cohere, local models) through a unified interface, so switching providers requires minimal code changes.
The Component Model Overview
LangChain organizes its building blocks into distinct component categories. LLMs and ChatModels wrap model providers. PromptTemplates manage dynamic prompt construction. OutputParsers transform raw model text into structured Python objects. Runnables are the universal interface that ties everything together into composable pipelines.
LLMs vs ChatModels
LangChain distinguishes between two model interfaces. LLM takes a string prompt and returns a string completion — the older text-completion style. ChatModel takes a list of messages (system, human, AI) and returns a message object. Modern OpenAI, Anthropic, and Gemini models are all ChatModels. You should prefer ChatModel for new applications.
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
llm = ChatOpenAI(model='gpt-4o-mini')
response = llm.invoke([
SystemMessage(content='You are a helpful assistant.'),
HumanMessage(content='What is LangChain?')
])
print(response.content)PromptTemplates: Dynamic Prompts
PromptTemplate lets you define a prompt with placeholder variables that get filled in at runtime. ChatPromptTemplate does the same for chat-style prompts with multiple messages. Templates separate the prompt structure from the runtime values, making prompts reusable, testable, and easy to version-control.
from langchain_core.prompts import ChatPromptTemplate
template = ChatPromptTemplate.from_messages([
('system', 'You are an expert in {domain}.'),
('human', 'Explain {concept} in simple terms.')
])
# Fill in variables at runtime
messages = template.invoke({'domain': 'machine learning', 'concept': 'embeddings'})
print(messages)OutputParsers: Shaping Model Output
OutputParsers convert the raw string output from a model into structured Python types. StrOutputParser simply extracts the content string. JsonOutputParser parses JSON. PydanticOutputParser validates against a Pydantic schema. Parsers also generate format instructions that you can inject into prompts to guide the model toward the expected format.
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from pydantic import BaseModel
class MovieReview(BaseModel):
title: str
rating: int
summary: str
parser = JsonOutputParser(pydantic_object=MovieReview)
# parser.get_format_instructions() returns JSON schema instructions
print(parser.get_format_instructions()[:200])The Runnable Interface
Every LangChain component implements the Runnable interface, which defines three key methods: invoke() for synchronous single calls, stream() for token-by-token streaming, and batch() for processing multiple inputs in parallel. Because every component is a Runnable, they can all be composed uniformly using the pipe operator.
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model='gpt-4o-mini')
# Single call
result = llm.invoke('What is 2+2?')
# Streaming tokens
for chunk in llm.stream('Tell me a joke.'):
print(chunk.content, end='', flush=True)
# Batch processing
results = llm.batch(['What is Paris?', 'What is Rome?'])Composing with the Pipe Operator
The pipe operator (|) is syntactic sugar for creating RunnableSequence objects. When you write prompt | llm | parser, LangChain creates a chain where the output of each step flows into the input of the next. This is the core of LCEL — LangChain Expression Language — and replaces the older verbose chain classes.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_template('Summarize this in one sentence: {text}')
llm = ChatOpenAI(model='gpt-4o-mini')
parser = StrOutputParser()
# Chain composed with pipe operator
chain = prompt | llm | parser
result = chain.invoke({'text': 'LangChain is a framework for LLM applications...'})
print(result)Document Loaders and Text Splitters
For RAG applications, LangChain provides Document Loaders that read files in various formats (PDF, Word, HTML, CSV) and return a list of Document objects with page_content and metadata fields. Text Splitters then divide long documents into smaller chunks suitable for embedding and retrieval.
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
loader = PyPDFLoader('report.pdf')
docs = loader.load() # List of Document objects
splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50
)
chunks = splitter.split_documents(docs)
print(f'Split {len(docs)} pages into {len(chunks)} chunks')Vector Stores as Runnables
LangChain wraps vector databases (Chroma, Pinecone, pgvector) as VectorStore objects that expose a similarity_search() method. You can convert any VectorStore into a Retriever Runnable with .as_retriever(), making it composable in LCEL chains. The retriever takes a query string and returns the top-k most relevant documents.
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(chunks, embeddings)
# Convert to Retriever Runnable
retriever = vectorstore.as_retriever(
search_type='similarity',
search_kwargs={'k': 5}
)
results = retriever.invoke('How does LangChain work?')
for doc in results:
print(doc.page_content[:100])Callbacks and Observability
LangChain's callback system lets you hook into every event in a chain's execution: when an LLM starts, when tokens stream, when a chain finishes, when a tool is called. Built-in callbacks include StdOutCallbackHandler for console logging. Third-party integrations like LangSmith attach automatically via environment variables, capturing full execution traces without code changes.
from langchain.callbacks import StdOutCallbackHandler
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model='gpt-4o-mini',
callbacks=[StdOutCallbackHandler()]
)
# Now every call logs input/output automatically
# Or enable LangSmith tracing globally:
import os
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
os.environ['LANGCHAIN_API_KEY'] = 'your-key'Memory and State in Chains
By default, LangChain chains are stateless — each invocation is independent. To add conversational memory, you wrap a chain with a memory component that stores and injects conversation history. RunnableWithMessageHistory is the LCEL-native way to add memory, taking a get_session_history function that loads history by session ID.
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
store = {} # session_id -> ChatMessageHistory
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
with_history = RunnableWithMessageHistory(chain, get_session_history)
response = with_history.invoke(
{'input': 'Hi, my name is Alice'},
config={'configurable': {'session_id': 'user-1'}}
)Quick Check
Test your understanding of LangChain Architecture and Core Abstractions.
Lesson Recap
In this lesson you learned: LangChain's component model organizes LLMs, PromptTemplates, OutputParsers, and Retrievers as Runnables with a unified interface, the pipe operator (|) composes Runnables into sequential chains via LCEL, and callbacks enable observability at every step without changing business logic. Next up we explore building chains with LCEL in depth.
자주 묻는 질문
“LangChain 아키텍처와 핵심 추상화” 강의는 무료인가요?
네 — “LangChain 아키텍처와 핵심 추상화” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“LangChain 아키텍처와 핵심 추상화”에서 뭘 배우나요?
LLMs, ChatModels, PromptTemplates, OutputParsers, Runnables를 포함한 LangChain의 구성 요소 모델과 이들이 파이프라인으로 결합되는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“LangChain 아키텍처와 핵심 추상화” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- LangChain 아키텍처와 핵심 추상화
- LCEL로 체인 구축하기
- 분기 및 병렬 체인
- LangChain에서 출력 스트리밍하기