LangChainの使い方入門【AIエージェントをPythonで作る実践ガイド】

LangChainの使い方入門【AIエージェントをPythonで作る実践ガイド】 AIツール・レビュー

はじめに

LangChainはLLMを使ったアプリケーション開発を効率化するPythonフレームワークです。RAG・AIエージェント・チャットボットなどを素早く構築できます。2026年のAIエンジニア求人でLangChain経験を求めるケースが増えています。

LangChainのインストール

pip install langchain langchain-anthropic langchain-openai langchain-community

基本的な使い方:LLMに質問する

from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage

llm = ChatAnthropic(model='claude-sonnet-4-20250514')

messages = [
    SystemMessage(content='あなたはPythonの専門家です。簡潔に回答してください。'),
    HumanMessage(content='pandasでグループ集計する方法を教えてください')
]

response = llm.invoke(messages)
print(response.content)

プロンプトテンプレートの使い方

from langchain_core.prompts import ChatPromptTemplate

template = ChatPromptTemplate.from_messages([
    ('system', 'あなたは{role}の専門家です。'),
    ('human', '{question}')
])

# テンプレートを使い回せる
chain = template | llm

result = chain.invoke({
    'role': 'データサイエンティスト',
    'question': '機械学習で不均衡データを扱う方法は?'
})
print(result.content)

ツール(Tool)を使ったエージェント

from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate

@tool
def get_stock_info(product_id: str) -> str:
    """製品IDの在庫数を返す"""
    inventory = {'P001': 150, 'P002': 30, 'P003': 0}
    return f'{product_id}の在庫: {inventory.get(product_id, "不明")}個'

@tool
def create_order(product_id: str, quantity: int) -> str:
    """発注を作成する"""
    return f'{product_id}を{quantity}個発注しました(発注番号: PO-{hash(product_id) % 10000:04d})'

tools = [get_stock_info, create_order]

prompt = ChatPromptTemplate.from_messages([
    ('system', 'あなたは在庫管理AIです。適切なツールを使って回答してください。'),
    ('human', '{input}'),
    ('placeholder', '{agent_scratchpad}')
])

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = agent_executor.invoke({
    'input': 'P001とP002とP003の在庫を確認して、在庫が50個以下のものは100個発注してください'
})
print(result['output'])

会話履歴の管理(Memory)

from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

# セッションごとの履歴を管理
session_store = {}

def get_session_history(session_id: str):
    if session_id not in session_store:
        session_store[session_id] = InMemoryChatMessageHistory()
    return session_store[session_id]

with_history = RunnableWithMessageHistory(chain, get_session_history)

# 同じsession_idを使うと会話が継続される
result1 = with_history.invoke(
    {'question': 'Pythonでリストをソートする方法は?', 'role': 'Python専門家'},
    config={'configurable': {'session_id': 'user_001'}}
)
print(result1.content)

まとめ

LangChainは「LLM呼び出し→プロンプトテンプレート→ツール統合→エージェント構築」という流れで、AIアプリケーションを効率的に開発できます。まずはシンプルなLLM呼び出しから始めて、ツールを追加してエージェント化していくステップが現実的です。RAGやエージェント開発の経験は2026年の転職市場で差別化につながります。

💼 ITエンジニア転職特化

自分らしく働けるエンジニア転職を目指すなら【strategy career】

年収1000万・残業月30時間以下・リモート可の求人多数

💼 無料で転職相談する →

※アフィリエイト広告を含みます

※本記事にはアフィリエイトリンクが含まれます。

コメント

タイトルとURLをコピーしました