Open in Colab

Agents#

agentは実行するアクションとその順序を決定します。agentによってはツールを実行するものがあり、ここでは SerpApi を利用します。

API Key を取得し、環境変数 SERPAPI_API_KEY を設定します。

Pythonパッケージ google-search-results をインストールします。

pip install google-search-results
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI

modelと利用するtoolを読み込みます。

llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)

tool、model、agentを指定してagentを初期化します。

zero-shot-react-description

ReActフレームワークを使用して、ツールの説明のみに基づいて、どのツールを使用するかを決定します

react-docstore

ReActフレームワークを使用して、docstoreと対話します

self-ask-with-search

質問に対する事実上の答えを検索します

conversational-react-description

会話で使用します

agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

agentを実行します。

agent.run("東京と大阪の5月の平均気温の差はどれくらいですか?")
> Entering new AgentExecutor chain...
 I need to find the average temperature of Tokyo and Osaka in May.
Action: Search
Action Input: Tokyo and Osaka average temperature in May
Observation: Honshu is warm and sunny in May. Tokyo, Osaka, Kyoto, and Hiroshima have average highs of around 22°C (72°F). Temperatures get warmer in late May.
Thought: I need to calculate the difference between the two temperatures.
Action: Calculator
Action Input: 22°C - 22°C
Observation: Answer: 0
Thought: I now know the final answer.
Final Answer: The average temperature difference between Tokyo and Osaka in May is 0°C.

> Finished chain.
'The average temperature difference between Tokyo and Osaka in May is 0°C.'