注: この記事は2026年7月にLangChain 0.3.xを使用して書かれました。将来のバージョンではAPIが変更される可能性があります — 動作しない場合は LangChain ドキュメント を確認してください。
LangChainの学習を始めたとき、私は圧倒されました。チェーン、エージェント、メモリ、リトリーバー、アウトプットパーサー — 数十もの抽象化があります。しかし気づきました:それらのほとんどは非推奨です。
LangGraph(同じチームによる)はオーケストレーションレイヤーを置き換えました。しかし、LangGraphノード内ではLangChainのコアビルディングブロックが必要です。そこで最低限学ぶ必要があるものを整理しました。
すべてを1つのファイルにまとめました。
重要な4つのこと
| # | トピック | LangGraphにおける重要性 |
|---|---|---|
| 1 | LLMのセットアップ | モデルと通信する必要があります |
| 2 | プロンプトテンプレート + LCEL | LCELのパイプ構文が引き継がれます |
| 3 | 構造化出力 | Pydanticモデルが古いアウトプットパーサーを置き換えます |
| 4 | ツール呼び出し | これが重要です — LangGraphエージェントはツール呼び出しループを中心に構築されています |
それぞれについて見ていきましょう。
1. LLMのセットアップ
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="llama-3.3-70b-versatile",
temperature=0.0,
api_key=os.environ["GROQ_API_KEY"],
base_url="https://api.groq.com/openai/v1",
)
Enter fullscreen mode Exit fullscreen mode
ChatOpenAIはOpenAI互換のAPIで動作します。ここではLlama 3.3を使った無料で高速な推論のためにGroqを使用しています。
2. プロンプトテンプレート + LCEL
from langchain_core.prompts import ChatPromptTemplate
template_string = """Translate the text that is delimited by triple backticks \
into a style that is {style}.
text: ```
{text}
Enter fullscreen mode Exit fullscreen mode
"""
prompt_template = ChatPromptTemplate.from_template(template_string)
chain = prompt_template | llm
response = chain.invoke({"style": "formal English", "text": "yo what's up"})```
パイプ(|)構文はLCEL(LangChain Expression Language)と呼ばれます。これは古いLLMChain、SequentialChainなどを置き換えます。シンプルで組み合わせ可能です。
3. 構造化出力
古い方法ではResponseSchema、StructuredOutputParserが必要で、プロンプトにフォーマット指示を注入する必要がありました。新しい方法はPydanticだけです:
from pydantic import BaseModel, Field
class ReviewInfo(BaseModel):
"""Information extracted from a product review."""
gift: bool = Field(description="Was the item purchased as a gift?")
delivery_days: int = Field(description="How many days to arrive? -1 if unknown.")
price_value: list[str] = Field(description="Sentences about value or price.")
structured_llm = llm.with_structured_output(ReviewInfo, method="function_calling")
result = (prompt | structured_llm).invoke({"text": review})
print(result.gift) # True (a real bool, not the string "true")
print(result.delivery_days) # 2 (a real int)
Enter fullscreen mode Exit fullscreen mode
各ステップの役割:
| ステップ | 役割 |
|---|---|
| Pydantic → JSONスキーマへの変換 | LangChain |
| スキーマの理解とJSONの生成 | LLM |
| JSONをPydanticオブジェクトにパース | LangChain |
プロンプトにフォーマット指示はもう必要ありません。LLMは「JSONを返す」という指示を見ることなく、内部でfunction callingを使用します。
4. ツール呼び出し — 重要なポイント
これはLangGraphが自動化するものです。手動で理解しておくとLangGraphがすぐに理解できます。
ツールの定義 — @toolデコレータ付きのPython関数:
from langchain_core.tools import tool
@tool
def get_current_weather(city: str) -> str:
"""Get the current weather for a given city."""
return {"berlin": "17°C, cloudy"}.get(city.lower(), "No data")
@tool
def get_population(city: str) -> int:
"""Get the approximate population of a city."""
return {"berlin": 3_700_000}.get(city.lower(), -1)
Enter fullscreen mode Exit fullscreen mode
@toolデコレータはこれらをBaseToolオブジェクトに変換します。docstringはLLMがいつ呼び出すかを判断するための説明になります。
ツールのバインドと呼び出し:
tools = [get_current_weather, get_population]
llm_with_tools = llm.bind_tools(tools)
messages = [HumanMessage("What's the weather and population in Berlin?")]
ai_response = llm_with_tools.invoke(messages)
print(ai_response.tool_calls)
# [{"name": "get_current_weather", "args": {"city": "Berlin"}, "id": "..."},
# {"name": "get_population", "args": {"city": "Berlin"}, "id": "..."}]
Enter fullscreen mode Exit fullscreen mode
LLMはツールを実行しません。ツールを実行するよう構造化されたリクエストを返します。
ツールの実行と結果の返送:
tool_map = {t.name: t for t in tools}
messages.append(ai_response)
for tc in ai_response.tool_calls:
result = tool_map[tc["name"]].invoke(tc["args"])
messages.append(ToolMessage(content=str(result), tool_call_id=tc["id"]))
final_response = llm_with_tools.invoke(messages)
print(final_response.content)
# "The weather in Berlin is 17°C and cloudy, with a population of 3.7 million."
Enter fullscreen mode Exit fullscreen mode
このループ — LLMが判断 → 実行 → 結果を返送 → 繰り返し — がLangGraphのToolNodeが自動化するものです。
スキップするもの
LangGraphに進む場合、以下のレガシーLangChain抽象化を学習する必要はありません:
-
LLMChain→ LCEL(prompt | llm)に置き換え -
SequentialChain→ LCELパイプに置き換え -
RouterChain→ LangGraphのブランチングに置き換え -
ConversationChain→ LangGraphの状態に置き換え -
AgentExecutor→ LangGraphエージェントループに置き換え
LangChainとLangGraphの関係
LangGraphはLangChainの置き換えではありません — その上に構築されています:
- LangChain Core → LLM、プロンプト、ツール、メッセージ (これらは引き続き使用)
- LangGraph → オーケストレーションレイヤー (これらのブロックの接続とループを制御)
LangGraphは2024年初頭に登場しました。これはLangChainの元々のエージェント/チェーン抽象化が柔軟性に欠け、カスタマイズが難しく、サイクルやブランチングをサポートせず、メモリが後付けだったためです。
コードの入手
すべてが1つのファイルです:github.com/santanu2908/langchain-essentials
git clone https://github.com/santanu2908/langchain-essentials.git
cd langchain-essentials
uv sync
# add your GROQ_API_KEY to .env
uv run main.py
Enter fullscreen mode Exit fullscreen mode
次回:LangGraph。この記事が役に立った場合は、フォローしてください — この旅も共有します。
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.