たとえば、"Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?'" のような値を設定すると、音楽関係の検索を実行する際に、このツールを優先的に利用するようになります
# OpenAI のラッパーをインポート
from langchain.llms import OpenAI
# LLM ラッパーを初期化
llm = OpenAI(temperature=0.7)
# SerpAPIWrapperのインポート
from langchain import SerpAPIWrapper, LLMMathChain
# serpapiのラッパーを初期化
search = SerpAPIWrapper()
# llm_math_chainのラッパーを初期化
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
# カスタムツールを定義して、ツール一覧に追加
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
),
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math"
)
]
# OpenAI のラッパーをインポート
from langchain.llms import OpenAI
# LLM ラッパーを初期化
llm = OpenAI(temperature=0.7)
# SerpAPIWrapperのインポート
from langchain import SerpAPIWrapper, LLMMathChain
# serpapiのラッパーを初期化
search = SerpAPIWrapper()
# llm_math_chainのラッパーを初期化
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
# BaseTool クラスのインポート
from langchain.agents import BaseTool
# 検索を行うツールを定義
class CustomSearchTool(BaseTool):
name = "Search"
description = "useful for when you need to answer questions about current events"
def _run(self, query: str) -> str:
"""Use the tool."""
return search.run(query)
async def _arun(self, query: str) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("BingSearchRun does not support async")
# 計算を行うツールを定義
class CustomCalculatorTool(BaseTool):
name = "Calculator"
description = "useful for when you need to answer questions about math"
def _run(self, query: str) -> str:
"""Use the tool."""
return llm_math_chain.run(query)
async def _arun(self, query: str) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("BingSearchRun does not support async")
# OpenAI のラッパーをインポート
from langchain.llms import OpenAI
# LLM ラッパーを初期化
llm = OpenAI(temperature=0.7)
# SerpAPIWrapperのインポート
from langchain import SerpAPIWrapper, LLMMathChain
# serpapiのラッパーを初期化
search = SerpAPIWrapper()
# llm_math_chainのラッパーを初期化
llm_math_chain = LLMMathChain(llm=llm)
# tool デコレーターをインポート
from langchain.agents import tool
# tool デコレーターを使ってツールを定義
@tool
def search_api(query: str) -> str:
"""useful for when you need to answer questions about current events"""
return search.run(query)
# ツール名や直接返すかどうかなどを指定する場合
@tool(name="Calculator", direct=False)
def calculator(query: str) -> str:
"""useful for when you need to answer questions about math"""
return llm_math_chain.run(query)