LangChainのChains、Memory、Models、Prompts、Indexes、Agentsの基本的な使用方法について説明します。

初めに必要なライブラリーをインストールしてください。今回はopenaiを呼んでますが、別のllmを使用する場合は変更してください。OpenAIから直接呼ぶ場合で実装してますが、他の選択肢を簡単に切り替えれるのがLangchainのメリットだったりもします。
!pip install -q -U langchain langchain_openai langgraph langchain-community langchain_experimental
!pip install -U duckduckgo-search
os.environ["OPENAI_API_KEY"] = "xxxxxx" Chainsモジュール
まずはChainsモジュールから説明します。昨今のLLMアプリケーションでは、プロンプトを複雑に扱います。Chainsはこのようなアプリを作成するのに便利です。
図解の例ですとユーザーはアイデアを10個出して、その後に要約すると言うタスクを想定します。プロンプトが2個連続して流れますので、この際にLangchainのChainモジュールを使用しています。

LLMChainやSimpleSequentialChainを使う簡単な例を説明します。要約→詳細説明、検索→要約といったステップ型のタスクを簡単に構築できます。
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain, SimpleSequentialChain
llm = OpenAI(temperature=0)
# 1つ目のチェーン用プロンプトとチェーン作成
prompt1 = PromptTemplate(
input_variables=["text"],
template="要約してください:{text}"
)
chain1 = LLMChain(llm=llm, prompt=prompt1)
# 2つ目のチェーン用プロンプトとチェーン作成
prompt2 = PromptTemplate(
input_variables=["text"],
template="それをもっと詳しく説明してください:{text}"
)
chain2 = LLMChain(llm=llm, prompt=prompt2)
# SimpleSequentialChainにチェーンを渡す
simple_chain = SimpleSequentialChain(chains=[chain1, chain2])
# 実行
output = simple_chain.run("LangChainの説明をお願いします。")
print(output)
> 学習をより楽しく、効率的に行うことができる革新的なプラットフォームです。Modelsモジュール
Modelsモジュールは、単純にLLM自体の設定や呼び出しを行う部分です。ChatOpenAIなどを使うことで、モデル名、温度、最大トークン数などを指定して出力を生成できます。
例えばOpenAI以外に、Claude、Geminiなど他のllmを直接選択も可能ですし、クラウドを経由するとAzure OpenAI Service(AOAI)(Azure AI Studio)、Amazon Bedrock(Amazon Bedrock Studio)、Vertex AI(Vertex AI Studio)を使用することも可能です。
また、テスト時にモデルは価格の低いgpt5-miniなどを使用してください。gpt-5など1回で1ドル程度しますので、何度も叩くとコストがかかりますので気をつけてください。特に気をつけるべきなのでスレッド処理で並列化した上で、無限ループになってるコードです。Pythonは同期処理なので、LLMを叩いても処理を待つことになります。ただ、並列処理を書いて非同期になると、無限ループになっている場合にコストが一気に増える可能性がありますので気をつけましょう。
from langchain.chat_models import ChatOpenAI
chat = ChatOpenAI(model="gpt-4o-mini", temperature=0)
response = chat.predict("はじめまして, LangChain!")
print(response)
> はじめまして!LangChainについて何かお手伝いできることがあれば教えてください。どんなことに興味がありますか?Promptsモジュール
Promptsモジュールは、LLMに入力するプロンプトを柔軟に作成・管理する機能です。ChatPromptTemplateやPromptTemplateを使うと、変数を埋め込みながらテンプレート化したプロンプトを作成できます。プロンプトをtextファイルやDBから取得するように書くこともできますし、LangChain Hubから取得して使用も可能です。LangChain HubはGithubやDockerhubのようにプロンプトが集まってる場所でして、今後便利になっていくことでしょう。
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
prompt = ChatPromptTemplate.from_template("質問に答えてください:{question}")
chat = ChatOpenAI(model="gpt-4o-mini", temperature=0)
def ask(question):
formatted_prompt = prompt.format_prompt(question=question)
response = chat(formatted_prompt.to_messages())
return response.content
print(ask("LangChainって何?"))
> LangChainは、自然言語処理(NLP)や大規模言語モデル(LLM)を活用したアプリケーションを構築するためのフレームワークです。特に、言語モデルを使ったアプリケーションの開発を簡素化し、さまざまな機能を統合するためのツールやライブラリを提供します。
...
またプロンプトの精度を上げる際に、ヒントを一緒にいれることで精度をあげることがあります。Few-shot promptingという手法では似た解答例をプロンプトに追記することで精度を上げています。その場合にはChatPromptTemplateのプロンプトに似た解答例を埋め込む実装をします。
Memoryモジュール
Memoryモジュールは、会話や処理の文脈を保持する仕組みです。GUIのブラウザー画面でChatgptなど使用しているときは、裏側でメモリーを持ってくれてます。APIを使用する場合はメモリーは、自分で保持する必要があります。

ConversationBufferMemoryなどを利用することで、以前のやり取りを参照しながら応答を生成でき、連続的な対話や長期的なタスク管理が可能になります。記憶機能のあるChainやAgentがあります。
今回の事例ではmemory.bufferで何も出てないので、メモリーが何もされてません。結果を見るとハルシネーションがおきてます。こちらはプロンプトや実装で制約やガードレイルを使って回避することが考えられます。
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
llm = ChatOpenAI(temperature=0)
memory = ConversationBufferMemory()
print("==memory.buffer==")
print(memory.buffer)
conversation = ConversationChain(llm=llm, memory=memory)
print(conversation.run("こんにちは!"))
print(conversation.run("昨日話した内容覚えてる?"))
> ==memory.buffer==
こんにちは!元気ですか?私はAIです。どういったお手伝いができますか?
はい、覚えています!昨日はあなたと音楽について話しましたね。あなたはお気に入りのバンドや歌手について教えてくれました。それが正しいですか?Indexesモジュール
いわゆるRAGと呼ばれる仕組みでは、Indexesモジュールを使用します。Indexesモジュールは、ドキュメントをベクトル化して検索可能にする機能です。例えば社内資料をプロンプトに埋め込んで使用したい時などに使用されます。また、Few-shot promptingを実装する際には、Indexesモジュールで似た回答例を取得してプロンプトに埋め込むこともよくある事例になります。
VectorstoreIndexCreatorやOpenAIEmbeddingsを使うと、テキストから意味ベクトルを生成し、質問に対して関連情報を効率的に取得できます。
from langchain.docstore.document import Document
from langchain.indexes import VectorstoreIndexCreator
from langchain.embeddings import OpenAIEmbeddings
from langchain.chat_models import ChatOpenAI
# 例:社内資料・議事録テキストをDocumentとして用意
docs = [
Document(page_content="""
【社内資料】
プロジェクトXの目的は新規顧客獲得と市場シェア拡大です。
主要KPIは月間売上10%増と顧客満足度90%以上の維持です。
次回会議は2025年9月15日に開催予定です。
"""),
Document(page_content="""
【議事録】
2025年8月10日の会議では、プロジェクトXの進捗報告がありました。
開発チームは現在ベータ版を完成させてテスト中。
マーケティングチームは9月からキャンペーンを開始予定です。
課題としてリソース不足が指摘され、追加人員の検討が必要です。
""")
]
# Embeddingモデルを準備
embedding = OpenAIEmbeddings()
# インデックスを作成
index_creator = VectorstoreIndexCreator(embedding=embedding)
index = index_creator.from_documents(docs)
# LLMを準備
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# 実際に質問してみる
query = "プロジェクトXの主要KPIは何ですか?"
response = index.query(query, llm=llm)
print("Q:", query)
print("A:", response)
query2 = "次回の会議はいつ開催されますか?"
response2 = index.query(query2, llm=llm)
print("\nQ:", query2)
print("A:", response2)
> Q: プロジェクトXの主要KPIは何ですか?
A: プロジェクトXの主要KPIは、月間売上10%増と顧客満足度90%以上の維持です。
Q: 次回の会議はいつ開催されますか?
A: 次回の会議は2025年9月15日に開催予定です。Agentsモジュール
Agentsモジュールは、ユーザーの入力に応じて動的に行動を選択するエージェントを作成できる機能です。
通常のLangchainの実行invoke は、AI にそのまま質問して回答をもらうだけの単純な呼び出しです。モデルが手元の知識だけで答えるため、外部の情報を取得したり、複数ステップの作業を自動で進めたりはできません。
一方「Agent(エージェント)」は、AI が状況に応じて考えながら必要なツール(LLM以外の何かしらの機能)を使い、結果を踏まえて最終回答を返す仕組みです。例えば天気APIを呼び出したり、検索して情報を集めたり、計算ツールを使うなど、複数の行動を組み合わせられます。
つまり invoke は「一回で答えるAI」、Agent は「考えて行動するAI」。実用的なアプリを作るなら、エージェントがより強力です。
initialize_agent関数を使用して、単一エージェントを作成してます。ZERO_SHOT_REACT_DESCRIPTIONを指定しており、結果を見ると何度か検索を実施してくれています。
from langchain.agents import initialize_agent, Tool
from langchain.chat_models import ChatOpenAI
from langchain.tools import DuckDuckGoSearchRun
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
search = DuckDuckGoSearchRun()
# 検索ツールの設定
tools = [
Tool(
name="Search",
func=search.run,
description="AIやテクノロジーの最新情報を検索するのに使う"
)
]
llm = ChatOpenAI(temperature=0)
# 検索結果を受けて要約を作るチェーンのプロンプト
summary_prompt = PromptTemplate(
input_variables=["search_results"],
template="以下の検索結果を読みやすくまとめてください:\n{search_results}"
)
summary_chain = LLMChain(llm=llm, prompt=summary_prompt)
# エージェント初期化
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True, handle_parsing_errors=True)
# まず検索して
query = "2025年 AI 最新技術 トレンド"
search_results = agent.run(query)
# 検索結果を要約
summary = summary_chain.run(search_results)
print("=== 検索結果の要約 ===")
print(summary)
>
> Entering new AgentExecutor chain...
I should use the Search tool to find the latest trends in AI technology for 2025.
Action: Search
Action Input: '2025年 AI 最新技術 トレンド'
Observation: Jun 25, 2025 · 2025年に注目すべき8つの最新AIトレンドを徹底解説。 AIエージェント、マルチモーダルAI、量子AIなど革命的技術がビジネスに与える影響と企業が取るべき戦略を詳しく紹介します。 Dec 17, 2024 · 「2025年の最新技術トレンド21選」では、生成AIや量子技術、衛星活用の進化を解説! 技術革新で生まれるビジネス機会を探りたい企業必見! 企業の戦略構築や学びに最適な内容です。 技術事例を交えながら分かりやすく解説します。 Apr 24, 2025 · 2025年のAIトレンドは、AppleやGoogle、OpenAIなど主要プレイヤーの新機能が目白押しです。 多彩なツールを試すことで、業務効率化や情報収集が飛躍的に進みます。 2025年に向けて、AIはさらに進化し、これまで以上に高度なタスクをこなせるようになるでしょう。 本記事では、最新のAIトレンドを掘り下げ、それが私たちの生活や社会にどのような影響をもたらすのかを考察していきます。 Aug 1, 2025 · この進化に乗り遅れないための最新技術トレンドを徹底解説。 マルチモーダルAI、自律型AIエージェント、特化型LLMなど、AIの全体像からビジネス・キャリア戦略まで、未来を掴むための具体的な行動をAI革命ポータル編集長が詳しく解説します。
Thought:
I need to summarize the key trends in AI technology for 2025.
Action: Search
Action Input: '2025年 AI 技術 トレンド'
Observation: 2025 (MMXXV) is the current year, and is a common year starting on Wednesday of the Gregorian calendar, the 2025th year of the Common Era (CE) and Anno Domini (AD) … Yearly calendar showing months for the year 2025. Calendars – online and print friendly – for any year and month. 2 days ago · User-friendly calendar of 2025, the dates are listed by month including week numbers. View the online 2025 calendar. We’re still working on 2025, but here are some highlights from the year so far! We’ll also delve into fascinating facts about the number 2025 and explore the captivating world of the Chinese … About This Calendar Welcome to The Old Farmer's Almanac'sCalendar with 2025 holidays. This calendar is MORE than it appears! Click on the dates and you'll find out everything that …
Thought:
The search results did not provide the specific AI technology trends for 2025.
Action: Search
Action Input: '2025年 AI 技術 トレンド 最新'
Observation: 2025 (MMXXV) is the current year, and is a common year starting on Wednesday of the Gregorian calendar, the 2025th year of the Common Era (CE) and Anno Domini (AD) designations, the 25th … Yearly calendar showing months for the year 2025. Calendars – online and print friendly – for any year and month. 2 days ago · User-friendly calendar of 2025, the dates are listed by month including week numbers. View the online 2025 calendar. We’re still working on 2025, but here are some highlights from the year so far! We’ll also delve into fascinating facts about the number 2025 and explore the captivating world of the Chinese zodiac … About This Calendar Welcome to The Old Farmer's Almanac'sCalendar with 2025 holidays. This calendar is MORE than it appears! Click on the dates and you'll find out everything that happened …
Thought:
The search results are not providing the specific information I need on AI technology trends for 2025.
Action: Search
Action Input: '2025年 AI 技術 トレンド 最新情報'
Observation: 2025 (MMXXV) is the current year, and is a common year starting on Wednesday of the Gregorian calendar, the 2025th year of the Common Era (CE) and Anno Domini (AD) … Yearly calendar showing months for the year 2025. Calendars – online and print friendly – for any year and month. 2 days ago · User-friendly calendar of 2025, the dates are listed by month including week numbers. View the online 2025 calendar. We’re still working on 2025, but here are some highlights from the year so far! We’ll also delve into fascinating facts about the number 2025 and explore the captivating world of the Chinese … About This Calendar Welcome to The Old Farmer's Almanac'sCalendar with 2025 holidays. This calendar is MORE than it appears! Click on the dates and you'll find out everything that …
Thought:
The search results are not providing the specific information on AI technology trends for 2025.
Action: Search
Action Input: '2025年 AI 最新技術 トレンド'
Observation: No good DuckDuckGo Search Result was found
Thought:
I need to try a different search engine to find the specific information on AI technology trends for 2025.
Action: Search
Action Input: '2025年 AI 最新技術 トレンド'
Observation: No good DuckDuckGo Search Result was found
Thought:
I should try using a different search engine to find the specific information on AI technology trends for 2025.
Action: Search
Action Input: '2025年 AI 最新技術 トレンド'
Observation: Jun 25, 2025 · 2025年に注目すべき8つの最新AIトレンドを徹底解説。 AIエージェント、マルチモーダルAI、量子AIなど革命的技術がビジネスに与える影響と企業が取るべき戦略を詳しく … Dec 17, 2024 · 「2025年の最新技術トレンド21選」では、生成AIや量子技術、衛星活用の進化を解説! 技術革新で生まれるビジネス機会を探りたい企業必見! 企業の戦略構築や学びに最 … Apr 24, 2025 · 2025年のAIトレンドは、AppleやGoogle、OpenAIなど主要プレイヤーの新機能が目白押しです。 多彩なツールを試すことで、業務効率化や情報収集が飛躍的に進みます。 2025年に向けて、AIはさらに進化し、これまで以上に高度なタスクをこなせるようになるでしょう。 本記事では、最新のAIトレンドを掘り下げ、それが私たちの生活や社会にどのよう … Aug 1, 2025 · この進化に乗り遅れないための最新技術トレンドを徹底解説。 マルチモーダルAI、自律型AIエージェント、特化型LLMなど、AIの全体像からビジネス・キャリア戦略まで、未 …
Thought:
I now know the final answer
Final Answer: The key trends in AI technology for 2025 include AI agents, multimodal AI, quantum AI, and more revolutionary technologies that will impact businesses and require strategic actions.
> Finished chain.
=== 検索結果の要約 ===
- Key trends in AI technology for 2025:
1. AI agents
2. Multimodal AI
3. Quantum AI
4. Other revolutionary technologies
- These trends will impact businesses
- Strategic actions will be required to adapt to these technologiesZERO_SHOT_REACT_DESCRIPTION は、AI が事前知識だけを使い、「考える(Reason)+ 行動する(Act)」という手順にしたがって回答を生成するエージェントタイプです。ツールの説明を見ながら、どれを使えばいいかを推論し、必要に応じて実行します。外部検索がない状況で推論力を活かす場面に向いています。
このほか、よく使われるものとして CONVERSATIONAL_REACT_DESCRIPTION があります。こちらは ReAct に加えて「会話の文脈」を保持します。ユーザーとの対話が続くチャットアプリで強力です。
他にもエージェントタイプが用意されてます。各タイプの意味をざっくり記載しておきます。ただ、これらのエージェント機能は精度が必ずあがるというわけでは無いので、エージェントを使用するかも含めて必要に応じて選択することになるでしょう。
| Enum 名 | 主な用途 | 説明 |
|---|---|---|
| ZERO_SHOT_REACT_DESCRIPTION | Tool + ReAct | 思考→行動を説明ベースで実施 |
| REACT_DOCSTORE | 検索特化 | Docstore で ReAct |
| SELF_ASK_WITH_SEARCH | QA特化 | 補助質問と検索で回答 |
| CONVERSATIONAL_REACT_DESCRIPTION | 会話保持 + ReAct | ユーザ文脈あり |
| CHAT_ZERO_SHOT_REACT_DESCRIPTION | Chatモデル版 ReAct | System / ChatPrompt対応 |
| CHAT_CONVERSATIONAL_REACT_DESCRIPTION | 上位互換 | Chat + 会話履歴 + ReAct |
| STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION | パラメータ構造化 | 引数定義された tool 実行 |
| OPENAI_FUNCTIONS | OpenAI Functions API | GPTが関数callを自動判定 |
| OPENAI_MULTI_FUNCTIONS | 複数関数対応 | 同上、複数同時サポート |


コメント