langchain について
LangChainは、ツールを使うエージェントやRAG、対話システムを構築する開発者向けのLLMアプリケーションフレームワークです。モデルの抽象化に加え、プロンプト、チェーン、メモリなどの要素を備えています。
主な機能
- 01ツール呼び出しエージェント
- 02RAGパイプライン
- 03切り替え可能なモデル抽象化
- 04会話メモリ
- 05ストリーミングと構造化出力
活用シーン
- 01LLMアプリの試作
- 02ツールを使うエージェントの構築
- 03文書に基づく質問応答
- 04会話履歴を持つチャットボットの作成
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ kalarislabs/ research-agent-skills --skill langchainインストール後、Claude Code で/langchainを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/agents.mdintegration.mdrag-retrieval-augmented-generation.mdrag.mdscripts/safe_arithmetic.py詳細
LangChain - エージェントとRAGでLLMアプリケーションを構築
LLMを活用したアプリケーションを構築するための、最も人気のあるフレームワークです。
LangChainを使う場面
LangChainを使う場面:
- ツール呼び出しと推論を行うエージェントを構築するとき(ReActパターン)
- RAG(検索拡張生成)パイプラインを実装するとき
- LLMプロバイダー(OpenAI、Anthropic、Google)を簡単に切り替える必要があるとき
- 会話メモリを備えたチャットボットを作成するとき
- LLMアプリケーションを迅速にプロトタイピングするとき
- LangSmithの可観測性を利用して本番環境にデプロイするとき
指標:
- 272,000+のリポジトリでLangChainが使用されています
- 500+のインテグレーション(モデル、ベクトルストア、ツール)
- 3,800+人のコントリビューター
代替手段を使う場面:
- LlamaIndex:RAGに特化しており、ドキュメントのQ&Aに適しています
- LangGraph:複雑なステートフルワークフローに適しており、より細かく制御できます
- Haystack:本番環境向けの検索パイプラインに適しています
- Semantic Kernel:Microsoftのエコシステムに適しています
クイックスタート
インストール
# Core library (Python 3.10+)
pip install -U langchain
# With OpenAI
pip install langchain-openai
# With Anthropic
pip install langchain-anthropic
# Common extras
pip install langchain-community # 500+ integrations
pip install langchain-chroma # Vector store
基本的なLLMの使用方法
from langchain_anthropic import ChatAnthropic
# Initialize model
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
# Simple completion
response = llm.invoke("Explain quantum computing in 2 sentences")
print(response.content)
エージェントの作成(ReActパターン)
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"It's sunny in {city}, 72°F"
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
# Create agent (<10 lines!)
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[get_weather, search_web],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({"messages": [{"role": "user", "content": "What's the weather in Paris?"}]})
print(result["messages"][-1].content)
基本概念
1. モデル - LLMの抽象化
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
# Swap providers easily
llm = ChatOpenAI(model="gpt-4o")
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp")
# Streaming
for chunk in llm.stream("Write a poem"):
print(chunk.content, end="", flush=True)
2. チェーン - 順次実行される操作
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
# Define prompt template
prompt = PromptTemplate(
input_variables=["topic"],
template="Write a 3-sentence summary about {topic}"
)
# Create chain
chain = LLMChain(llm=llm, prompt=prompt)
# Run chain
result = chain.run(topic="machine learning")
3. エージェント - ツールを使った推論
ReAct(推論+行動)パターン:
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain.tools import Tool
from scripts.safe_arithmetic import calculate
# Define custom tool
calculator = Tool(
name="Calculator",
func=lambda x: str(calculate(x)),
description="Useful for arithmetic with numbers and +, -, *, /."
)
# Create agent with tools
agent = create_tool_calling_agent(
llm=llm,
tools=[calculator, search_web],
prompt="Answer questions using available tools"
)
# Create executor
agent_executor = AgentExecutor(agent=agent, tools=[calculator], verbose=True)
# Run with reasoning
result = agent_executor.invoke({"input": "What is 25 * 17 + 142?"})
4. メモリ - 会話履歴
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
# Add memory to track conversation
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=True
)
# Multi-turn conversation
conversation.predict(input="Hi, I'm Alice")
conversation.predict(input="What's my name?") # Remembers "Alice"
RAG(検索拡張生成)
詳細、コード例、パラメーター表については、references/rag-retrieval-augmented-generation.mdを参照してください。この手順が該当する場合にお読みください。
高度なエージェントパターン
構造化出力
from langchain_core.pydantic_v1 import BaseModel, Field
# Define schema
class WeatherReport(BaseModel):
city: str = Field(description="City name")
temperature: float = Field(description="Temperature in Fahrenheit")
condition: str = Field(description="Weather condition")
# Get structured response
structured_llm = llm.with_structured_output(WeatherReport)
result = structured_llm.invoke("What's the weather in SF? It's 65F and sunny")
print(result.city, result.temperature, result.condition)
ツールの並列実行
from langchain.agents import create_tool_calling_agent
# Agent automatically parallelizes independent tool calls
agent = create_tool_calling_agent(
llm=llm,
tools=[get_weather, search_web, calculator]
)
# This will call get_weather("Paris") and get_weather("London") in parallel
result = agent.invoke({
"messages": [{"role": "user", "content": "Compare weather in Paris and London"}]
})
エージェント実行のストリーミング
# Stream agent steps
for step in agent_executor.stream({"input": "Research AI trends"}):
if "actions" in step:
print(f"Tool: {step['actions'][0].tool}")
if "output" in step:
print(f"Output: {step['output']}")
よくあるパターン
複数ドキュメントのQA
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
# Load multiple documents
docs = [
loader.load("https://docs.python.org"),
loader.load("https://docs.numpy.org")
]
# QA with source citations
chain = load_qa_with_sources_chain(llm, chain_type="stuff")
result = chain({"input_documents": docs, "question": "How to use numpy arrays?"})
print(result["output_text"]) # Includes source citations
エラー処理を備えたカスタムツール
from langchain.tools import tool
@tool
def risky_operation(query: str) -> str:
"""Perform a risky operation that might fail."""
try:
# Your operation here
result = perform_operation(query)
return f"Success: {result}"
except Exception as e:
return f"Error: {str(e)}"
# Agent handles errors gracefully
agent = create_agent(model=llm, tools=[risky_operation])
LangSmithによる可観測性
import os
# Enable tracing
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-api-key"
os.environ["LANGCHAIN_PROJECT"] = "my-project"
# All chains/agents automatically traced
agent = create_agent(model=llm, tools=[calculator])
result = agent.invoke({"input": "Calculate 123 * 456"})
# View traces at smith.langchain.com
ベクトルストア
Chroma(ローカル)
from langchain_chroma import Chroma
vectorstore = Chroma.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
persist_directory="./chroma_db"
)
Pinecone(クラウド)
from langchain_pinecone import PineconeVectorStore
vectorstore = PineconeVectorStore.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
index_name="my-index"
)
FAISS(類似検索)
from langchain_community.vectorstores import FAISS
vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
vectorstore.save_local("faiss_index")
# Load later
vectorstore = FAISS.load_local("faiss_index", OpenAIEmbeddings())
ドキュメントローダー
# Web pages
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://example.com")
# PDFs
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("paper.pdf")
# GitHub
from langchain_community.document_loaders import GithubFileLoader
loader = GithubFileLoader(repo="user/repo", file_filter=lambda x: x.endswith(".py"))
# CSV
from langchain_community.document_loaders import CSVLoader
loader = CSVLoader("data.csv")
テキストスプリッター
# Recursive (recommended for general text)
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
separators=["\n\n", "\n", " ", ""]
)
# Code-aware
from langchain.text_splitter import PythonCodeTextSplitter
splitter = PythonCodeTextSplitter(chunk_size=500)
# Semantic (by meaning)
from langchain_experimental.text_splitter import SemanticChunker
splitter = SemanticChunker(OpenAIEmbeddings())
ベストプラクティス
- シンプルに始める - ほとんどの場合は
create_agent()を使います - ストリーミングを有効にする - 長い応答のUXが向上します
- エラー処理を追加する - ツールは失敗することがあるため、適切に処理します
- LangSmithを使う - エージェントのデバッグに欠かせません
- チャンクサイズを最適化する - RAGでは500-1000文字が目安です
- プロンプトをバージョン管理する - 本番環境での変更を追跡します
- 埋め込みをキャッシュする - コストが高いため、可能な場合はキャッシュします
- コストを監視する - LangSmithでトークンの使用量を追跡します
パフォーマンスベンチマーク
| 操作 | レイテンシー | 備考 |
|---|---|---|
| 単純なLLM呼び出し | ~1-2s | プロバイダーによって異なります |
| ツールを1つ使うエージェント | ~3-5s | ReAct推論のオーバーヘッド |
| RAG検索 | ~0.5-1s | ベクトル検索+LLM |
| 1000件のドキュメントの埋め込み | ~10-30s | モデルによって異なります |
LangChainとLangGraphの比較
| 機能 | LangChain | LangGraph |
|---|---|---|
| 最適な用途 | 素早いエージェント、RAG | 複雑なワークフロー |
| 抽象化レベル | 高 | 低 |
| 開始に必要なコード | <10行 | ~30行 |
| 制御 | シンプル | 完全な制御 |
| ステートフルワークフロー | 限定的 | 標準対応 |
| 循環グラフ | いいえ | はい |
| Human-in-the-loop | 基本 | 高度 |
LangGraphを使う場面:
- サイクルを含むステートフルワークフローが必要なとき
- きめ細かな制御が必要なとき
- マルチエージェントシステムを構築するとき
- 複雑なロジックを持つ本番アプリを開発するとき
参考資料
- エージェントガイド - ReAct、ツール呼び出し、ストリーミング
- RAGガイド - ドキュメントローダー、リトリーバー、QAチェーン
- インテグレーションガイド - ベクトルストア、LangSmith、デプロイ
リソース
- GitHub: https://github.com/langchain-ai/langchain ⭐ 119,000+
- ドキュメント: https://docs.langchain.com
- APIリファレンス: https://reference.langchain.com/python
- LangSmith: https://smith.langchain.com(可観測性)
- バージョン: 0.3+(安定版)
- ライセンス: MIT
エージェントの作業手順
- 環境を確認します。 フレームワークのバージョン、モデルプロバイダー、API キー、レート制限を確認します。
- 入力を確定します。 データまたはユーザーに確認して、形式、識別子、パラメーターを確定します。結果に影響する値は推測せず、質問してください。
- まず小規模に実行します。 既知の入力で単一の呼び出しまたはチェーンをテストし、生の出力を確認します。
- 上記の指示と参考情報を使用して、タスク全体を実行します。
- 結果を検証します。 小規模なラベル付きデータセットで評価し、構造化出力がスキーマに沿っていることを確認して、プロンプトと応答を記録します。
- 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未解決の点を明示します。
| このような場合 | 対応方法 |
|---|---|
| 出力が期待されるスキーマと一致しない | 検証と再試行を追加する、スキーマを厳密にする、またはプロンプトを簡素化します。 |
| この手順に記載された関数、フラグ、エンドポイントがインストール済みバージョンにない | インストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認し、適宜対応してユーザーに伝えます。API を捏造してはいけません。 |
| 必須の入力、識別子、パラメーターが曖昧 | ユーザーに質問するか、実行前に仮定を明示します。 |
誠実性に関するルール
- 結果、パラメーター、識別子、引用、統計を捏造してはいけません。実行または検証できない場合は、その旨を明確に伝えます。
- ユーザーの同意なしに、個人情報や機密データを外部 API に送信してはいけません。
- ここに記載されたバージョン固有の情報は古くなっている可能性があります。インストール済みバージョンの公式ドキュメントで確認してください。
- 費用が発生する、共有 GPU やクラウドのクォータを消費する、個人データや患者データに触れる、または取り消せない操作を行う前に、ユーザーに確認してください。
関連スキル
llamaindex:RAG を使った LLM アプリケーションを構築するためのデータフレームワーク。autogpt-agents:継続的に動作する自律型 AI エージェントを構築・デプロイするためのプラットフォーム。chroma:AI アプリケーション向けのオープンソース埋め込みデータベース。
コメント
Markdown 対応