🤖 AI/AI Agent 🤖 AI/AI Agent 🤖 AI/AI Agent

LangChain 實戰:開發者如何快速構建 AI 應用

深入 LangChain 核心模組,用真實程式碼範例帶你快速上手 AI 應用開發。

✍️ 峰値 PEAK · 2026年04月05日 · 约 22 分钟阅读 ~22 min read 約22分
cover 154

LangChain 實戰:開發者如何快速構建 AI 應用

LangChain in Practice: How Developers Can Build AI Apps Fast

LangChain実践:開発者が素早くAIアプリを構築する方法

深入 LangChain 核心模組,用真實程式碼範例帶你快速上手 AI 應用開發。

Explore LangChain’s core modules with real code examples to help developers build AI apps quickly and confidently.

LangChainのコアモジュールを実際のコード例で解説し、AIアプリ開発を素早く習得する。

這是《AI 工具實戰 30 天》系列第 17 篇,共 30 篇。如果你已經有 Python 基礎,並且想把 LLM 真正整合進自己的應用,LangChain 是目前最成熟的框架選擇之一。它不只是一個 API 封裝層,而是提供了一套完整的模組化架構,讓你可以像搭積木一樣組合出複雜的 AI 工作流。本篇將帶你走過幾個最常用的核心模組,並附上可直接執行的程式碼範例。

This is Part 17 of 30 in the AI Tools in Practice series. If you already know Python and want to integrate LLMs into real applications, LangChain is one of the most mature frameworks available. It’s not just an API wrapper — it provides a modular architecture that lets you compose complex AI workflows like building with blocks. This article walks through the most commonly used core modules with runnable code examples.

これは「AIツール実践30日間」シリーズの第17回(全30回)です。Pythonの基礎があり、LLMを実際のアプリに組み込みたい開発者にとって、LangChainは現在最も成熟したフレームワークの一つです。単なるAPIラッパーではなく、複雑なAIワークフローをブロックのように組み合わせられるモジュール式アーキテクチャを提供しています。本記事では、最もよく使われるコアモジュールを実行可能なコード例とともに解説します。

核心模組一:PromptTemplate 與 LLMChainCore Module 1: PromptTemplate and LLMChainコアモジュール1:PromptTemplateとLLMChain

PromptTemplate 讓你把提示詞參數化,避免硬編碼字串。搭配 LLMChain,可以快速建立一個可重用的推理單元。以下是一個簡單範例:

“`python
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model=”gpt-4o”, temperature=0.7)

prompt = PromptTemplate(
input_variables=[“product”],
template=”請用繁體中文為 {product} 寫一段 50 字的行銷文案。”
)

chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(product=”智慧型手錶”)
print(result)
“`

這個模式的優點是 prompt 與邏輯分離,方便測試與維護。

PromptTemplate lets you parameterize prompts instead of hardcoding strings. Combined with LLMChain, you get a reusable inference unit in just a few lines:

“`python
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model=”gpt-4o”, temperature=0.7)

prompt = PromptTemplate(
input_variables=[“product”],
template=”Write a 50-word marketing copy for {product}.”
)

chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(product=”smartwatch”)
print(result)
“`

The key benefit here is separation of prompt logic from application code, which makes testing and iteration much cleaner.

PromptTemplateを使うとプロンプトをパラメータ化でき、ハードコードを避けられます。LLMChainと組み合わせることで、再利用可能な推論ユニットを数行で構築できます:

“`python
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model=”gpt-4o”, temperature=0.7)

prompt = PromptTemplate(
input_variables=[“product”],
template=”{product}の50字マーケティングコピーを書いてください。”
)

chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(product=”スマートウォッチ”)
print(result)
“`

プロンプトとロジックを分離することで、テストと保守が格段に楽になります。

核心模組二:Memory 讓對話有記憶Core Module 2: Memory for Stateful Conversationsコアモジュール2:Memoryで会話に記憶を持たせる

預設的 LLM 呼叫是無狀態的,每次都是全新對話。LangChain 的 Memory 模組解決了這個問題。ConversationBufferMemory 是最直接的選擇,它會把完整對話歷史帶入每次請求:

“`python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory, verbose=True)

conversation.predict(input=”我叫 Alex,我在學 Python。”)
conversation.predict(input=”你還記得我的名字嗎?”)
“`

對於長對話場景,可以改用 ConversationSummaryMemory,它會自動摘要舊訊息,避免 token 超限。選擇哪種 Memory 取決於你的應用對上下文長度與精確度的需求。

LLM calls are stateless by default — every request starts fresh. LangChain’s Memory module fixes that. ConversationBufferMemory is the simplest option, carrying the full conversation history into each request:

“`python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory, verbose=True)

conversation.predict(input=”My name is Alex and I’m learning Python.”)
conversation.predict(input=”Do you remember my name?”)
“`

For longer conversations, switch to ConversationSummaryMemory, which auto-summarizes older messages to stay within token limits. The right choice depends on how much context precision your app needs.

LLMの呼び出しはデフォルトでステートレスで、毎回新しい会話として扱われます。LangChainのMemoryモジュールがこれを解決します。ConversationBufferMemoryは最もシンプルな選択肢で、完全な会話履歴を各リクエストに含めます:

“`python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory, verbose=True)

conversation.predict(input=”私はAlexといいます。Pythonを勉強しています。”)
conversation.predict(input=”私の名前を覚えていますか?”)
“`

長い会話にはConversationSummaryMemoryが適しており、古いメッセージを自動要約してトークン制限を回避します。

核心模組三:RAG 架構與 VectorStoreCore Module 3: RAG Architecture with VectorStoreコアモジュール3:RAGアーキテクチャとVectorStore

RAG(Retrieval-Augmented Generation)是目前最實用的 LLM 應用模式之一。你可以把自己的文件向量化存入 VectorStore,讓模型在回答時先檢索相關段落,再生成答案。以下是使用 FAISS 的基本範例:

“`python
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA

raw_text = “LangChain 是一個用於構建 LLM 應用的框架…”
splitter = CharacterTextSplitter(chunk_size=200, chunk_overlap=20)
docs = splitter.create_documents([raw_text])

embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(docs, embeddings)

qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=vectorstore.as_retriever()
)
print(qa_chain.run(“LangChain 是什麼?”))
“`

這個模式讓你的 AI 應用能夠基於私有知識庫回答問題,是企業內部工具最常見的架構。

RAG (Retrieval-Augmented Generation) is one of the most practical LLM application patterns right now. You vectorize your own documents into a VectorStore, and the model retrieves relevant chunks before generating an answer. Here’s a basic example using FAISS:

“`python
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA

raw_text = “LangChain is a framework for building LLM applications…”
splitter = CharacterTextSplitter(chunk_size=200, chunk_overlap=20)
docs = splitter.create_documents([raw_text])

embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(docs, embeddings)

qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=vectorstore.as_retriever()
)
print(qa_chain.run(“What is LangChain?”))
“`

This pattern powers private knowledge base Q&A — the most common architecture for internal enterprise AI tools.

RAG(Retrieval-Augmented Generation)は現在最も実用的なLLMアプリケーションパターンの一つです。自分のドキュメントをVectorStoreにベクトル化して保存し、モデルが回答生成前に関連チャンクを検索します。FAISSを使った基本例:

“`python
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA

raw_text = “LangChainはLLMアプリ構築のためのフレームワークです…”
splitter = CharacterTextSplitter(chunk_size=200, chunk_overlap=20)
docs = splitter.create_documents([raw_text])

embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(docs, embeddings)

qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=vectorstore.as_retriever()
)
print(qa_chain.run(“LangChainとは何ですか?”))
“`

このパターンはプライベートナレッジベースのQ&Aを実現し、企業内部ツールで最もよく使われるアーキテクチャです。

實戰建議與下一步Practical Tips and Next Steps実践的なアドバイスと次のステップ

LangChain 的模組化設計讓你可以從小功能開始,逐步組合出完整應用。建議的學習路徑是:先掌握 PromptTemplate + LLMChain,再加入 Memory 處理多輪對話,最後引入 VectorStore 實現 RAG。每個模組都可以獨立測試,這讓除錯變得相對容易。需要注意的是,LangChain 版本迭代較快,建議鎖定版本號並定期查閱官方 changelog。下一篇我們將進入更貼近業務場景的實戰——AI 客服機器人從需求到上線的完整建置流程,敬請期待。

上一篇:用 n8n 打造你的第一個 AI Agent 工作流

下一篇(第18篇):AI 客服機器人實戰:從需求到上線的完整建置流程

LangChain’s modular design lets you start small and compose up to a full application. The recommended learning path: start with PromptTemplate + LLMChain, add Memory for multi-turn conversations, then bring in VectorStore for RAG. Each module is independently testable, which makes debugging much more manageable. One heads-up: LangChain iterates fast, so pin your version numbers and check the official changelog regularly. Next up, we’re getting into a real business scenario — a complete guide to building an AI customer service bot from requirements to production.

Previous: Build Your First AI Agent Workflow with n8n

Next (Part 18): AI Customer Service Bot: A Complete Build Guide from Requirements to Launch

LangChainのモジュール式設計により、小さな機能から始めて完全なアプリへと段階的に組み上げられます。推奨学習パスは:まずPromptTemplate + LLMChainを習得し、次にMemoryで多ターン会話を追加、最後にVectorStoreでRAGを実装する流れです。各モジュールは独立してテスト可能なため、デバッグも比較的容易です。注意点として、LangChainはバージョンアップが頻繁なので、バージョンを固定して公式changelogを定期的に確認することをお勧めします。次回はより実務に近いシナリオ——AIカスタマーサービスボットの要件定義から本番リリースまでの完全な構築フローを解説します。

前の記事:n8nで最初のAI Agentワークフローを構築する

次回(第18回):AIカスタマーサービスボット実践:要件定義からリリースまでの完全構築フロー

峰値
峰値 PEAK / 阿峰
全端开发者 · 套利交易员 · 在日创业者
Full-Stack Dev · Arb Trader · Japan-based Founder
フルスタック開発者 · アービトラージトレーダー · 在日起業家

在大阪构建系统、做套利交易、探索 AI Agent。相信系统的力量大于意志力。

Building systems, trading arb, exploring AI agents from Osaka. Systems over willpower.

大阪でシステムを構築し、アービトラージ取引を行い、AIエージェントを探求。システムは意志力を超える。

返回AI/AI Agent板块 Back to AI/AI Agent AI/AI Agentへ戻る 所有文章 →All Posts →すべての記事 →