0Pricing
AI Engineering Academy · レッスン

LangChainのアーキテクチャとコア抽象化

LLM、ChatModels、PromptTemplates、OutputParsers、Runnablesなど、LangChainのコンポーネントモデルと、それらを組み合わせてパイプラインを構成する方法を理解します。

「LangChainのアーキテクチャとコア抽象化」はCoddyKit上の無料AI Engineering Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、AI Engineering Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Engineering Academyコースには全4レッスンが含まれています。

「LangChainのアーキテクチャとコア抽象化」で何を学びますか?

LLM、ChatModels、PromptTemplates、OutputParsers、Runnablesなど、LangChainのコンポーネントモデルと、それらを組み合わせてパイプラインを構成する方法を理解します。 ブラウザで直接実行するハンズオンコードでAI Engineering Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Engineering Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Engineering Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「LangChainのアーキテクチャとコア抽象化」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Engineering Academyレッスンでコードを書いて実行できますか?

はい。すべてのAI Engineering Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. LangChainのアーキテクチャとコア抽象化
  2. LCELでChainを構築する
  3. 分岐と並列Chain
  4. LangChainでの出力ストリーミング
← AI Engineering Academyに戻る