LangChain 入門:開發者如何用積木式框架搭建自己的 AI 應用
LangChain Intro: How Developers Build Their Own AI Apps with a Modular Framework
LangChain 入門:開発者がモジュール式フレームワークで独自の AI アプリを構築する方法
用實際程式碼示範 LangChain 的 Chain、Memory 與 Tool,快速構建自訂 AI 工作流。
Learn LangChain’s Chain, Memory, and Tool concepts with real code examples to build custom AI workflows fast.
実際のコードで LangChain の Chain・Memory・Tool を解説し、カスタム AI ワークフローを素早く構築する。
這是《AI 工具實戰 30 天:從提示詞到 Agent,每天一個工具改變你的工作方式》系列第 18 篇,共 30 篇。上一篇我們探索了 AutoGPT 與 AgentGPT 如何讓 AI 自主執行多步驟任務。這一篇,我們進入開發者最關心的實作層面——用 LangChain 框架,從零開始搭建一個有記憶、能呼叫工具的 AI 應用。
This is Part 18 of 30 in the series “30 Days of AI Tools in Action: From Prompts to Agents, One Tool a Day to Transform Your Work.” Last time we explored how AutoGPT and AgentGPT let AI autonomously handle multi-step tasks. Today we go hands-on with LangChain — building an AI app from scratch that has memory and can call external tools.
これは「AI ツール実践 30 日間:プロンプトから Agent まで、毎日一つのツールで仕事を変える」シリーズの第 18 回(全 30 回)です。前回は AutoGPT と AgentGPT が AI に複数ステップのタスクを自律実行させる方法を探りました。今回は開発者が最も気になる実装面に踏み込み、LangChain フレームワークを使ってメモリと外部ツール呼び出しを備えた AI アプリをゼロから構築します。
LangChain 是什麼?為什麼開發者愛用它What Is LangChain and Why Developers Love ItLangChain とは何か?開発者に愛される理由
LangChain 是一個開源 Python(也支援 JavaScript)框架,核心理念是把 LLM 呼叫、提示詞模板、記憶體、外部工具等元件像積木一樣組合起來。你不需要自己處理 API 串接的細節,只需專注在「這個步驟要做什麼」。它的三大核心概念是:Chain(串接多個步驟)、Memory(讓對話有上下文記憶)、Tool(讓 AI 能呼叫搜尋、計算器、資料庫等外部能力)。
LangChain is an open-source Python (and JavaScript) framework built around one idea: composing LLM calls, prompt templates, memory, and external tools like building blocks. You stop worrying about raw API plumbing and focus on what each step should do. Its three core concepts are Chain (linking multiple steps), Memory (giving conversations context across turns), and Tool (letting AI call search engines, calculators, databases, and more).
LangChain はオープンソースの Python(JavaScript も対応)フレームワークで、LLM 呼び出し・プロンプトテンプレート・メモリ・外部ツールをブロックのように組み合わせることを核心思想としています。API の細かい接続処理を気にせず、「このステップで何をするか」に集中できます。三大コア概念は Chain(複数ステップの連結)、Memory(会話に文脈記憶を持たせる)、Tool(検索・計算機・データベースなど外部機能の呼び出し)です。
Chain:把多個步驟串成一條流水線Chain: Linking Multiple Steps into a PipelineChain:複数ステップをパイプラインに連結する
最基本的 Chain 是 LLMChain,把提示詞模板與模型綁在一起。以下是一個簡單範例:
“`python
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
llm = ChatOpenAI(model=”gpt-4o”, temperature=0.7)
prompt = ChatPromptTemplate.from_template(
“請用繁體中文,用一句話解釋 {concept} 的核心概念。”
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(concept=”量子糾纏”)
print(result)
“`
你可以把多個 Chain 用 SequentialChain 串接,讓第一步的輸出自動成為第二步的輸入,實現複雜的多步驟處理流程,例如「先摘要文章,再翻譯成英文,最後生成推文」。
The most basic Chain is LLMChain, which binds a prompt template to a model. Here’s a quick example:
“`python
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
llm = ChatOpenAI(model=”gpt-4o”, temperature=0.7)
prompt = ChatPromptTemplate.from_template(
“Explain {concept} in one sentence.”
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(concept=”quantum entanglement”)
print(result)
“`
You can wire multiple Chains together with SequentialChain so the output of step one automatically feeds into step two — perfect for pipelines like “summarize an article, translate it, then generate a tweet.”
最も基本的な Chain は LLMChain で、プロンプトテンプレートとモデルを結びつけます。簡単な例を示します:
“`python
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
llm = ChatOpenAI(model=”gpt-4o”, temperature=0.7)
prompt = ChatPromptTemplate.from_template(
“{concept} のコア概念を一文で説明してください。”
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(concept=”量子もつれ”)
print(result)
“`
SequentialChain を使えば複数の Chain を連結でき、ステップ 1 の出力が自動的にステップ 2 の入力になります。「記事を要約 → 英訳 → ツイート生成」のような複雑なパイプラインも簡単に実現できます。
Memory:讓 AI 記住對話歷史Memory: Giving Your AI a Conversation HistoryMemory:AI に会話履歴を持たせる
預設的 LLM 呼叫是無狀態的,每次都從零開始。LangChain 的 Memory 模組解決了這個問題。最常用的是 ConversationBufferMemory,它會把完整對話歷史附加到每次請求中:
“`python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory)
conversation.predict(input=”我叫小明,我是一名後端工程師。”)
response = conversation.predict(input=”你還記得我的職業嗎?”)
print(response) # AI 會正確回答「後端工程師」
“`
對於長對話,可以改用 ConversationSummaryMemory,讓 AI 自動摘要舊對話,避免 token 超出限制。
By default, LLM calls are stateless — every request starts fresh. LangChain’s Memory module fixes that. The most common option is ConversationBufferMemory, which appends the full conversation history to each request:
“`python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory)
conversation.predict(input=”My name is Alex and I’m a backend engineer.”)
response = conversation.predict(input=”Do you remember my job?”)
print(response) # AI correctly answers “backend engineer”
“`
For long conversations, switch to ConversationSummaryMemory so the AI auto-summarizes older turns and stays within token limits.
デフォルトでは LLM 呼び出しはステートレスで、毎回ゼロから始まります。LangChain の Memory モジュールがこれを解決します。最もよく使われるのは ConversationBufferMemory で、完全な会話履歴を各リクエストに付加します:
“`python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory)
conversation.predict(input=”私は田中で、バックエンドエンジニアです。”)
response = conversation.predict(input=”私の職業を覚えていますか?”)
print(response) # AI は正しく「バックエンドエンジニア」と答える
“`
長い会話には ConversationSummaryMemory を使うと、AI が古い会話を自動要約してトークン制限を回避できます。
Tool:讓 AI 呼叫真實世界的能力Tool: Connecting AI to Real-World CapabilitiesTool:AI に現実世界の能力を与える
Tool 是讓 AI 從「只會說話」變成「能做事」的關鍵。LangChain 內建了搜尋、計算器、Python REPL 等工具,也支援自訂工具。以下示範讓 AI 使用搜尋工具:
“`python
from langchain.agents import initialize_agent, Tool, AgentType
from langchain.tools import DuckDuckGoSearchRun
search = DuckDuckGoSearchRun()
tools = [
Tool(
name=”Search”,
func=search.run,
description=”當需要查詢最新資訊時使用”
)
]
agent = initialize_agent(
tools, llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
agent.run(“2025 年最熱門的 AI 框架是什麼?”)
“`
這個 Agent 會自動判斷何時需要搜尋、何時直接回答,整個推理過程透過 verbose=True 完整呈現,非常適合除錯與學習。
Tools are what transform AI from “just talking” to “actually doing things.” LangChain ships with built-in tools for search, calculators, Python REPL, and more — plus support for custom tools. Here’s an agent using a search tool:
“`python
from langchain.agents import initialize_agent, Tool, AgentType
from langchain.tools import DuckDuckGoSearchRun
search = DuckDuckGoSearchRun()
tools = [
Tool(
name=”Search”,
func=search.run,
description=”Use this to look up current information”
)
]
agent = initialize_agent(
tools, llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
agent.run(“What are the hottest AI frameworks in 2025?”)
“`
The agent decides on its own when to search and when to answer directly. With verbose=True, you see the full reasoning chain — great for debugging and learning.
Tool は AI を「話すだけ」から「実際に行動できる」存在に変える鍵です。LangChain には検索・計算機・Python REPL などのツールが組み込まれており、カスタムツールも作成できます。検索ツールを使う Agent の例を示します:
“`python
from langchain.agents import initialize_agent, Tool, AgentType
from langchain.tools import DuckDuckGoSearchRun
search = DuckDuckGoSearchRun()
tools = [
Tool(
name=”Search”,
func=search.run,
description=”最新情報を調べる必要があるときに使用”
)
]
agent = initialize_agent(
tools, llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
agent.run(“2025 年で最も注目されている AI フレームワークは何ですか?”)
“`
この Agent はいつ検索が必要か、いつ直接回答するかを自動判断します。verbose=True で推論プロセスが全て表示されるため、デバッグや学習に最適です。
實戰建議:從小 Chain 開始,逐步擴展Practical Advice: Start Small, Scale Up実践アドバイス:小さな Chain から始めて段階的に拡張する
LangChain 的學習曲線不算陡,但元件很多,容易迷失。建議的路徑是:先用 LLMChain 跑通一個最簡單的提示詞流程,再加入 Memory 讓它有記憶,最後引入 Tool 讓它能查資料。每個階段都先用 verbose=True 觀察 AI 的推理過程,確認行為符合預期再往下走。另外,LangChain 更新頻繁,建議鎖定版本(如 langchain==0.1.x)並參考官方 LCEL(LangChain Expression Language)文件,這是目前最推薦的現代寫法。
下一篇(第19篇)我們將進入 RAG(Retrieval-Augmented Generation)實戰,示範如何讓 AI 讀懂你的私有文件,打造企業專屬知識問答系統。
上一篇:AutoGPT 與 AgentGPT 初探:讓 AI 自主完成多步驟任務的第一次實驗
LangChain’s learning curve is manageable, but there are a lot of components and it’s easy to get lost. A solid path: start with LLMChain to get a basic prompt flow working, add Memory to give it context, then bring in Tools for external data. At each stage, use verbose=True to watch the AI’s reasoning and confirm it behaves as expected before moving on. LangChain updates frequently, so pin your version (e.g., langchain==0.1.x) and check the official LCEL (LangChain Expression Language) docs — it’s the modern, recommended way to write chains today.
Next up, Part 19 dives into RAG (Retrieval-Augmented Generation) — how to make AI read your private documents and build an enterprise-grade knowledge Q&A system.
LangChain の学習曲線はそれほど急ではありませんが、コンポーネントが多く迷いやすいです。推奨する進め方は、まず LLMChain で最もシンプルなプロンプトフローを動かし、次に Memory を追加して文脈を持たせ、最後に Tool を導入して外部データを取得できるようにすることです。各段階で verbose=True を使って AI の推論プロセスを観察し、期待通りの動作を確認してから次に進みましょう。LangChain は更新が頻繁なので、バージョンを固定し(例:langchain==0.1.x)、現在最も推奨されるモダンな書き方である公式 LCEL(LangChain Expression Language)ドキュメントを参照することをお勧めします。
次回(第 19 回)は RAG(Retrieval-Augmented Generation)の実践に入り、AI にプライベートドキュメントを読み込ませ、企業専用の知識 Q&A システムを構築する方法を紹介します。
