forked from Archives/langchain
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
"""Tool for the Metaphor search API."""
|
|
|
|
from typing import Dict, List, Optional, Union
|
|
|
|
from langchain.callbacks.manager import (
|
|
AsyncCallbackManagerForToolRun,
|
|
CallbackManagerForToolRun,
|
|
)
|
|
from langchain.tools.base import BaseTool
|
|
from langchain.utilities.metaphor_search import MetaphorSearchAPIWrapper
|
|
|
|
|
|
class MetaphorSearchResults(BaseTool):
|
|
"""Tool that has capability to query the Metaphor Search API and get back json."""
|
|
|
|
name = "metaphor_search_results_json"
|
|
description = (
|
|
"A wrapper around Metaphor Search. "
|
|
"Input should be a Metaphor-optimized query. "
|
|
"Output is a JSON array of the query results"
|
|
)
|
|
api_wrapper: MetaphorSearchAPIWrapper
|
|
|
|
def _run(
|
|
self,
|
|
query: str,
|
|
num_results: int,
|
|
run_manager: Optional[CallbackManagerForToolRun] = None,
|
|
) -> Union[List[Dict], str]:
|
|
"""Use the tool."""
|
|
try:
|
|
return self.api_wrapper.results(query, num_results)
|
|
except Exception as e:
|
|
return repr(e)
|
|
|
|
async def _arun(
|
|
self,
|
|
query: str,
|
|
num_results: int,
|
|
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
|
|
) -> Union[List[Dict], str]:
|
|
"""Use the tool asynchronously."""
|
|
try:
|
|
return await self.api_wrapper.results_async(query, num_results)
|
|
except Exception as e:
|
|
return repr(e)
|