<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>「Tool」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/tool/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 02 Nov 2025 21:01:30 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「Tool」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】LangChain: Agentを使って実行を自動化する</title>
		<link>https://tech.nkhn37.net/python-langchain-agent-basics/</link>
					<comments>https://tech.nkhn37.net/python-langchain-agent-basics/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Sat, 24 Aug 2024 20:00:00 +0000</pubDate>
				<category><![CDATA[LangChain]]></category>
		<category><![CDATA[Agent]]></category>
		<category><![CDATA[AgentExecutor]]></category>
		<category><![CDATA[ReAct]]></category>
		<category><![CDATA[Tool]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=11125</guid>

					<description><![CDATA[Python で大規模言語モデル（LLM: Large Language Model）を活用する際に使用できる LangChain で Agent 機能を使って実行を自動化する方法を解説します。 LangChain の  [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Python で大規模言語モデル（LLM: Large Language Model）を活用する際に使用できる <span class="marker"><strong>LangChain で Agent 機能を使って実行を自動化する方法</strong></span>を解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">LangChain の Agent 機能</h2>



<p class="wp-block-paragraph">LangChain は、大規模言語モデル（LLM: Large Language Model）を活用するためのオープンソース Python ライブラリです。LangChain では、LLM の複雑なタスクを実行することが可能です。</p>



<p class="wp-block-paragraph">LangChain には、PromptTemplate や OutptParser、Chain といった一連のワークフローを簡単に実現できる枠組みを提供してくれています。また、LangChain には<span class="marker"><strong>Agent</strong></span> 機能があり、複数の言語モデル、ツール、データベース、外部API等を統合して動的にタスク処理を行うことができるようになります。ここで動的にというのは、タスクを遂行するために LLM が最適な手段を選び、ステップごとに判断を行うプロセスのことを指します。</p>



<p class="wp-block-paragraph">LangChain の Agent 機能では、特定タスクに特化したスクリプトや従来のプログラムとは異なりより柔軟で適応的なアプローチを提供できる点が非常に強力です。</p>



<p class="wp-block-paragraph">この記事では、<span class="marker"><strong>LangChain で Agent 機能を使って実行を自動化する方法</strong></span>を紹介していきます。例として ReAct で思考しながらツールを選択する Agent の実装例を紹介します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">Agent 機能</h3>



<p class="wp-block-paragraph">LangChain の <span class="marker"><strong>Agent</strong></span> 機能では、ユーザーの質問に対して、どう行動するべきかをLLMが考えて行動を実行します。Agent の概要に関する公式ドキュメントは<a href="https://docs.langchain.com/oss/python/langchain/agents" target="_blank" rel="noreferrer noopener">こちら</a>を参照してください。</p>



<p class="wp-block-paragraph">ここで行動と言っているのは、インターネットサイトから情報を検索する、企業や個人固有のDBへアクセスする、外部で定義されているツールを使用するといった外部データソースへのアクセスを含んでいます。</p>



<p class="wp-block-paragraph">Agent 機能を構成する要素としては以下のようなものがあります。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>構成要素</th><th>概要</th></tr></thead><tbody><tr><td><code>Tool</code></td><td>ツールという名の通り、Agent 機能が呼び出す処理とその説明を保有するもので、LangChain は多くの <code>Tool</code> を提供しています。もちろん、独自の <code>Tool</code> を作成することも可能です。</td></tr><tr><td><code>AgentExecutor</code></td><td>Agent 機能が動作するための実行環境で、Agent が選択した処理の呼び出しを繰り返しつつ実行を行います。</td></tr></tbody></table></figure>



<h2 class="wp-block-heading jinr-heading d--bold">LangChain による Agent 実装</h2>



<p class="wp-block-paragraph">ここでは、Agent 実装例を紹介します。AI に思考をさせて <code>Tool</code> の中から必要な機能を呼び出し、実行するような ReAct Agent を作成してみましょう。まずは、ReAct の考え方を簡単に説明した後に、Python プログラムの実装例を紹介していきます。</p>



<p class="wp-block-paragraph">なお、以降で紹介する <code>AgentExecutor</code> による Agent 実装方法は広く使用されている方法ですが、より柔軟性や制御のしやすさを必要とするような場合は、LangGraph Agent の使用を検討することもできます。</p>



<p class="wp-block-paragraph">LangGraph は、複雑なワークフローや高度な制御が必要な場合に特に有用です。また、LangGraph については別途まとめてみたいと思います。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--simple-box1  "><div class="c--simple-box-inner">
<p class="wp-block-paragraph">この記事では各種パッケージを使用していますが、以下バージョンでの動作を確認しています。生成 AI の分野は進歩が速いため、API 等の変更により最新バージョンではプログラムがそのままでは動作しない可能性もありますので注意してください。</p>



<ul class="wp-block-list jinr-list">
<li>Python: 3.11.5</li>



<li>langchain: 0.2.11</li>



<li>langchain-core: 0.2.26</li>



<li>langchain-community: 0.2.10</li>



<li>langchain-openai: 0.1.16</li>
</ul>
</div></div></section>



<h3 class="wp-block-heading jinr-heading d--bold">ReAct Agent の実装</h3>



<p class="wp-block-paragraph">生成 AI では、プロンプトエンジニアリングと言って AI にどのように指示を与えるのかという技術が非常に重要になります。プロンプトエンジニアリングの技術の中には AI に思考させる <span class="marker"><strong>ReAct（Reasoning and Acting）</strong></span> という手法があります。</p>



<p class="wp-block-paragraph">ReAct では、モデルが思考を行い、結果に基づいて必要なツールを選択、アクションを実行します。ここで思考と言っているのは、LLM がどのツールを使うかを決定する過程（プロセス）のことを言っています。この ReAct により、複雑なタスクや段階的なプロセスを含むタスクにおいて効果的な結果を返す機能を実現できます。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>概念</th><th>概要</th></tr></thead><tbody><tr><td>推論（Reasoning）</td><td>モデルが与えられた情報や文脈に基づいて推論を行うステップです。この段階ではモデルがタスクに対する理解を示し、適切な結果を導くための情報を生成します。</td></tr><tr><td>行動（Acting）</td><td>推論結果に基づいて、具体的なアクションを取る段階です。これは実際のタスクを実行するための指示や操作を含みます。</td></tr></tbody></table></figure>



<h4 class="wp-block-heading jinr-heading d--bold">Agent 機能を利用した ReAct の実装</h4>



<p class="wp-block-paragraph">今回は、指定した地名の現在の天候と座標を確認をしてみましょう。なお、現在の天気予報や座標の取得には「<a href="https://tech.nkhn37.net/python-openweather-api/" target="_blank" rel="noreferrer noopener">OpenWeatherのAPI使用方法</a>」で紹介した OpenWeather のAPI を使ったプログラムを用意して <code>Tool</code> として使います。</p>



<p class="wp-block-paragraph">今回用意した各プログラムの実装例を紹介して、以降で詳細の説明をしていきます。</p>



<p class="wp-block-paragraph"><strong><code>config.ini</code></strong>：各種APIのキー等を保存する設定ファイル (<code>xxxx</code>には必要なキーを記載)</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[OPENAI]
key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[WEATHER_API]
key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
url_current_weather_data = https://api.openweathermap.org/data/2.5/weather
url_direct_geocoding = https://api.openweathermap.org/geo/1.0/direct
</pre>



<p class="wp-block-paragraph"><strong><code>get_current_weather.py</code></strong>：現在の天候を取得するクラスを含むプログラム</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import configparser

import requests


class GetWeather:
    def __init__(self) -> None:
        # APIキーの読み込み
        config = configparser.ConfigParser()
        config.read("./config.ini")
        self.api_key = config["WEATHER_API"]["key"]
        self.url_current_weather_data = config["WEATHER_API"][
            "url_current_weather_data"
        ]
        self.url_direct_geocoding = config["WEATHER_API"]["url_direct_geocoding"]

    def get_coordinate(self, location: str) -> dict:
        """地名の情報をもとに座標情報を取得する。

        :param location: 地名
        :return: 座標情報
        """
        # 座標情報取得のためのパラメータ設定
        params = {"q": location, "appid": self.api_key}
        # データの取得
        response = requests.get(self.url_direct_geocoding, params=params)
        geocode_result = response.json()

        return geocode_result[0]

    def get_current_weather(self, location: str) -> dict:
        """地名の情報をもとに現在の天気の情報を取得する。

        :param location: 地名
        :return: 現在の天気情報
        """
        # 地名情報から座標情報を取得
        geo_data = self.get_coordinate(location)
        lat = geo_data["lat"]
        lon = geo_data["lon"]

        # 天気情報取得のためのパラメータ設定
        params = {
            "lat": lat,
            "lon": lon,
            "units": "metric",
            "appid": self.api_key,
            "lang": "ja",
        }
        # 天気データの取得
        response = requests.get(self.url_current_weather_data, params=params)
        weather_result = response.json()

        return weather_result


if __name__ == "__main__":
    pass
</pre>



<p class="wp-block-paragraph"><strong><code>agent_basics.py</code></strong>：具体的に Agent を実行するプログラム</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import configparser

from langchain import hub
from langchain.agents import AgentExecutor, Tool, create_react_agent
from langchain_openai import ChatOpenAI

from get_current_weather import GetWeather

# コンフィグファイルからOpenAI用のキーを取得する
config = configparser.ConfigParser()
config.read("config.ini")

# llmの設定
llm = ChatOpenAI(openai_api_key=config["OPENAI"]["key"])

# GetWeatherクラスの生成
gw = GetWeather()

# Toolの生成
weather_tool = Tool(
    name="天気",
    func=gw.get_current_weather,
    description="地名を入力すると現在の天気の情報を取得する",
)
coordinate_tool = Tool(
    name="座標",
    func=gw.get_coordinate,
    description="地名を入力すると座標の情報を取得する",
)
tools = [weather_tool, coordinate_tool]

# プロンプトテンプレートを準備する。以下リンク先から取得。
# https://smith.langchain.com/hub/hwchase17/react
prompt = hub.pull("hwchase17/react")
print(prompt)

# Agentの生成
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=3,
)


result = agent_executor.invoke({"input": "名古屋の現在の天候と座標を教えてください。"})
print(result)
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果例】※読みやすいように適宜改行追加等しているため実出力とは異なります。
input_variables=['agent_scratchpad', 'input', 'tool_names', 'tools'] metadata={'lc_hub_owner': 'hwchase17', 'lc_hub_repo': 'react', 'lc_hub_commit_hash': 'd15fe3c426f1c4b3f37c9198853e4a86e20c425ca7f4752ec0c9b0e97ca7ea4d'}
template='Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!\

Question: {input}
Thought:{agent_scratchpad}'


> Entering new AgentExecutor chain...
We need to get the current weather and coordinates for Nagoya.
Action: 天気
Action Input: "Nagoya"
{'coord': {'lon': 136.8998, 'lat': 35.1851}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '厚い雲', 'icon': '04d'}], 'base': 'stations', 'main': {'temp': 30.82, 'feels_like': 37.71, 'temp_min': 28.9, 'temp_max': 31.14, 'pressure': 1012, 'humidity': 72, 'sea_level': 1012, 'grnd_level': 1010}, 'visibility': 10000, 'wind': {'speed': 0.35, 'deg': 33, 'gust': 1.07}, 'clouds': {'all': 88}, 'dt': 1724544537, 'sys': {'type': 2, 'id': 2001167, 'country': 'JP', 'sunrise': 1724530788, 'sunset': 1724578179}, 'timezone': 32400, 'id': 1856057, 'name': '名古屋市', 'cod': 200}

Now I need to get the coordinates for Nagoya.
Action: 座標
Action Input: "Nagoya"{'name': 'Nagoya', 'local_names': {'ca': 'Nagoya', 'fr': 'Nagoya', 'uk': 'Наґоя', 'sv': 'Nagoya', 'de': 'Nagoya', 'lt': 'Nagoja', 'sl': 'Nagoja', 'ko': '나고야 시', 'pl': 'Nagoja', 'oc': 'Nagoya', 'io': 'Nagoya', 'kn': 'ನಗೋಯ', 'km': 'ក្រុងណាហ្គោយ៉ា', 'eo': 'Nagojo', 'cs': 'Nagoja', 'nl': 'Nagoya', 'en': 'Nagoya', 'ja': '名古屋市', 'mr': 'नागोया', 'sr': 'Нагоја', 'he': 'נגויה', 'zh': '名古屋市', 'pt': 'Nagoia', 'ia': 'Nagoya', 'es': 'Nagoya', 'th': 'นาโงยะ', 'ru': 'Нагоя', 'et': 'Nagoya'}, 'lat': 35.1851045, 'lon': 136.8998438, 'country': 'JP'}I now know the final answer.
Final Answer: 名古屋市の現在の天候は、厚い雲で気温は30.82度です。座標は、緯度35.1851045、経度136.8998438です。

> Finished chain.
{'input': 'Nagoyaの現在の天候と座標を教えてください。', 'output': '名古屋市の現在の天候は、厚い雲で気温は30.82度です。座標は、緯度35.1851045、経度136.8998438です。'}</pre>



<h4 class="wp-block-heading jinr-heading d--bold">プログラム実装内容の詳細説明</h4>



<p class="wp-block-paragraph">ここからは上記プログラムの実装内容をポイントを絞って説明します。なお、この記事では Agent 機能の説明を中心にするため、OpenWeather API や OpenAI API に関する説明は省略します。必要に応じて以下のような記事も参考にしてください。</p>



<ul class="wp-block-list jinr-list">
<li><a href="https://tech.nkhn37.net/python-openweather-api/" target="_blank" rel="noreferrer noopener">OpenWeatherのAPI使用方法</a></li>



<li><a href="https://tech.nkhn37.net/python-langchain-overview/" target="_blank" rel="noreferrer noopener">LangChainで大規模言語モデル（LLM）を活用する</a></li>
</ul>



<h5 class="wp-block-heading jinr-heading d--bold">必要モジュールのインポートと LLM の準備</h5>



<p class="wp-block-paragraph">Agent 機能については、<code>langchain.agents</code> モジュールから <code>AgentExecutor</code>, <code>Tool</code>, <code>create_react_agent</code> をインポートしておきます。また、<code>llm</code> としてOpenAIの <code>ChatOpenAI</code> を用意しておきます。</p>



<h5 class="wp-block-heading jinr-heading d--bold"><code>Tool</code> の用意</h5>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># GetWeatherクラスの生成
gw = GetWeather()

# Toolの生成
weather_tool = Tool(
    name="天気",
    func=gw.get_current_weather,
    description="地名を入力すると現在の天気の情報を取得する",
)
coordinate_tool = Tool(
    name="座標",
    func=gw.get_coordinate,
    description="地名を入力すると座標の情報を取得する",
)
tools = [weather_tool, coordinate_tool]</pre>



<p class="wp-block-paragraph">LLM は上記部分で準備した <code>Tool</code> を使用します。今回は自分で独自に作った <code>GetWeather</code> というクラスの中のメソッドを <code>Tool</code> として登録しています。</p>



<ul class="wp-block-list jinr-list">
<li><code>weather_tool</code>：地名から天候の情報を返却するツール</li>



<li><code>coordinate_tool</code>：地名から座標を返却するツール</li>
</ul>



<p class="wp-block-paragraph"><code>Tool</code> には、該当する関数やメソッドを指定します。引数については以下の通りです。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>引数</th><th></th></tr></thead><tbody><tr><td><code>name</code></td><td>ツール名を示します。</td></tr><tr><td><code>func</code></td><td>ツールが実行する関数やメソッドを示します。</td></tr><tr><td><code>description</code></td><td>ツールで実行される関数やメソッドが何をするかといった <code>Tool</code> の詳細を示します。<br><span class="marker"><strong>Agent がどの <code>Tool</code> を選択するかの判断に重要な役割を果たすので詳細かつ正確に記述する必要があります</strong></span>。</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">用意したツールは「<code>tools=[weather_tool, coordinate_tool]</code>」のようにツールリストとしてまとめておきます。</p>



<h5 class="wp-block-heading jinr-heading d--bold">プロンプトの準備</h5>



<p class="wp-block-paragraph">ReAct のためのプロンプトテンプレートを用意します。プロンプトテンプレートを使用して自分で用意もできますが、LangChain では Hub で様々なプロンプトテンプレートが提供されています。今回は「hwchase17/react」という ReAct 用のプロンプトテンプレートを取得して使用させてもらうことにします。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># プロンプトテンプレートを準備する。以下リンク先から取得。
# https://smith.langchain.com/hub/hwchase17/react
prompt = hub.pull("hwchase17/react")
print(prompt)</pre>



<p class="wp-block-paragraph">「hwchase17/react」のプロンプトテンプレートは、実行結果例でも表示していますが以下のようになっています。<a href="https://smith.langchain.com/hub/hwchase17/react" target="_blank" rel="noreferrer noopener">こちら</a>を参考にしてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}
</pre>



<p class="wp-block-paragraph">このプロンプトテンプレートは ReAct を実装するためにQuestion、Thought、Action、Action Input、Observation、Thought、Final Answer というような思考の流れが記載されています。上記で用意した <code>Tool</code> の情報は <code>{tools}</code> に、呼び出す際の質問は <code>{input}</code> に埋め込まれて実行がされます。</p>



<h5 class="wp-block-heading jinr-heading d--bold">Agent の準備と実行</h5>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Agentの生成
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=3,
)


result = agent_executor.invoke({"input": "名古屋の現在の天候と座標を教えてください。"})
print(result)</pre>



<p class="wp-block-paragraph"><code>create_react_agent</code> を使って ReAct Agent を生成します。この Agent は、LLM やツール、プロンプトの情報を引数に取り、ReAct に基づいた Agent を構築します。</p>



<p class="wp-block-paragraph">Agent を実行するのが <span class="marker"><strong><code>AgentExecutor</code></strong></span> です。生成時に <code>create_react_agent</code> で生成した <code>agent</code> や、<code>Tool</code> リストである <code>tools</code> を指定します。</p>



<p class="wp-block-paragraph"><code>verbose=True</code> にしておくと ReAct の実行の流れを出力できるので設定しておくと動作確認に便利です。また、<code>max_iterations</code> は最大の思考回数を指定しています。</p>



<p class="wp-block-paragraph">Agent 実行時には、<code>invoke</code> メソッドを使用して実行します。その際にプロンプトの <code>{input}</code> に質問内容が渡せるように指定します。</p>



<h5 class="wp-block-heading jinr-heading d--bold">実行結果の内容</h5>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">> Entering new AgentExecutor chain...
We need to get the current weather and coordinates for Nagoya.
Action: 天気
Action Input: "Nagoya"
{'coord': {'lon': 136.8998, 'lat': 35.1851}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '厚い雲', 'icon': '04d'}], 'base': 'stations', 'main': {'temp': 30.82, 'feels_like': 37.71, 'temp_min': 28.9, 'temp_max': 31.14, 'pressure': 1012, 'humidity': 72, 'sea_level': 1012, 'grnd_level': 1010}, 'visibility': 10000, 'wind': {'speed': 0.35, 'deg': 33, 'gust': 1.07}, 'clouds': {'all': 88}, 'dt': 1724544537, 'sys': {'type': 2, 'id': 2001167, 'country': 'JP', 'sunrise': 1724530788, 'sunset': 1724578179}, 'timezone': 32400, 'id': 1856057, 'name': '名古屋市', 'cod': 200}

Now I need to get the coordinates for Nagoya.
Action: 座標
Action Input: "Nagoya"
{'name': 'Nagoya', 'local_names': {'ca': 'Nagoya', 'fr': 'Nagoya', 'uk': 'Наґоя', 'sv': 'Nagoya', 'de': 'Nagoya', 'lt': 'Nagoja', 'sl': 'Nagoja', 'ko': '나고야 시', 'pl': 'Nagoja', 'oc': 'Nagoya', 'io': 'Nagoya', 'kn': 'ನಗೋಯ', 'km': 'ក្រុងណាហ្គោយ៉ា', 'eo': 'Nagojo', 'cs': 'Nagoja', 'nl': 'Nagoya', 'en': 'Nagoya', 'ja': '名古屋市', 'mr': 'नागोया', 'sr': 'Нагоја', 'he': 'נגויה', 'zh': '名古屋市', 'pt': 'Nagoia', 'ia': 'Nagoya', 'es': 'Nagoya', 'th': 'นาโงยะ', 'ru': 'Нагоя', 'et': 'Nagoya'}, 'lat': 35.1851045, 'lon': 136.8998438, 'country': 'JP'}I now know the final answer.
Final Answer: 名古屋市の現在の天候は、厚い雲で気温は30.82度です。座標は、緯度35.1851045、経度136.8998438です。

> Finished chain.
{'input': 'Nagoyaの現在の天候と座標を教えてください。', 'output': '名古屋市の現在の天候は、厚い雲で気温は30.82度です。座標は、緯度35.1851045、経度136.8998438です。'}</pre>



<p class="wp-block-paragraph">実行結果を見てみましょう。上記を見てもらうと分かるように「We need to get the current weather and coordinates for Nagoya.」から始まり、まず天気ツールが使用されてインプットに <code>"Nagoya"</code> が入力されて結果が返ってきています。「{&#8216;coord&#8217;: {&#8216;lon&#8217;: 136.8998, &#8216;lat&#8217;: 35.1851}, &#8216;weather&#8217;: [{&#8216;id&#8217;: 804, &#8216;main&#8217;: &#8216;Clouds&#8217;, &#8216;description&#8217;: &#8216;厚い雲&#8217;, &#8216;icon&#8217;: &#8217;04d&#8217;}],…」という部分は、<code>weather_tool</code> に設定した <code>gw.get_current_weather</code> からの返却値です。</p>



<p class="wp-block-paragraph">次に、「Now I need to get the coordinates for Nagoya.」というように座標ツールが使われます。こちらも同様に <code>"Nagoya"</code> が入力されて、「{&#8216;name&#8217;: &#8216;Nagoya&#8217;, &#8216;local_names&#8217;: {&#8216;ca&#8217;: &#8216;Nagoya&#8217;,…」という結果が返ってきます。これは、<code>coordinate_tool</code> に設定した <code>gw.get_coordinate</code> からの返却値です。</p>



<p class="wp-block-paragraph">そして最後に Finished Answer で、各ツールから取得した結果をまとめた回答文が作られて Finished Chain となっています。このように AI が自動的に思考し、ツールを選択し実行するような一連の流れを ReAct Agent で実装できました。</p>



<p class="wp-block-paragraph">今回は ReAct Agent の一例として紹介しましたが、それ以外にも Agent 機能を使用、実装することで LLM の活用の幅を大きく広げることができます。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">Python で大規模言語モデル（LLM: Large Language Model）を活用する際に使用できる <span class="marker"><strong>LangChain で Agent 機能を使って実行を自動化する方法</strong></span>を解説しました。</p>



<p class="wp-block-paragraph">Agent 機能とは、複数の言語モデル、ツール、データベース、外部 API 等を統合して動的にタスク処理を行うことができるようにするための機能です。</p>



<p class="wp-block-paragraph">この記事では、Agent の実装例の一つとして ReAct Agent の実装例を紹介し、自分で作成した天候や座標の取得機能をツールとして LLM と連携する例を紹介しました。今回の ReAct Agent 以外にももちろん色々な Agent 機能があります。</p>



<p class="wp-block-paragraph">LangChain の Agent 機能は、LLM と連携した機能開発を効率化できる機能ですので、是非皆さんも色々と調べて実装してみてもらえればと思います。</p>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>




<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-langchain-agent-basics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-06-16 19:14:37 by W3 Total Cache
-->