Skip to content

Commit

Permalink
Convert get_metaphor to Tool wrapping official metaphor client
Browse files Browse the repository at this point in the history
  • Loading branch information
kreneskyp committed Aug 29, 2023
1 parent 06187ea commit bdc7a33
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 19 deletions.
17 changes: 9 additions & 8 deletions ix/chains/fixture_src/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
GraphQLAPIWrapper,
LambdaWrapper,
PubMedAPIWrapper,
MetaphorSearchAPIWrapper,
)

from ix.api.chains.types import NodeTypeField
Expand Down Expand Up @@ -198,13 +197,15 @@
"class_path": "ix.tools.metaphor.get_metaphor",
"type": "tool",
"fields": TOOL_BASE_FIELDS
+ NodeTypeField.get_fields(
MetaphorSearchAPIWrapper,
include=[
"k",
"metaphor_api_key",
],
),
+ [
{
"name": "metaphor_api_key",
"label": "Metaphor API Key",
"type": "str",
"input_type": "secret",
"required": True,
}
],
}


Expand Down
34 changes: 23 additions & 11 deletions ix/tools/metaphor.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
from typing import Any
from langchain.utilities import MetaphorSearchAPIWrapper
from langchain.tools import BaseTool, MetaphorSearchResults # metaphorQueryRun
import os
from typing import Any, Optional

from ix.chains.asyncio import SyncToAsyncRun
from ix.chains.loaders.tools import extract_tool_kwargs
from asgiref.sync import sync_to_async
from langchain.tools import Tool
from metaphor_python import Metaphor

from ix.chains.loaders.tools import extract_tool_kwargs

class AsyncMetaphorQueryRun(SyncToAsyncRun, MetaphorSearchResults):
pass

def get_metaphor(metaphor_api_key: Optional[str], **kwargs: Any) -> Tool:
"""Metaphor search tool
def get_metaphor(**kwargs: Any) -> BaseTool:
Initializes a Metaphor client and returns a Tool object that can be used to run queries.
"""
tool_kwargs = extract_tool_kwargs(kwargs)
wrapper = MetaphorSearchAPIWrapper(**kwargs)
# metaphor_tool = MetaphorSearchResults(api_wrapper=search)
return AsyncMetaphorQueryRun(api_wrapper=wrapper, **tool_kwargs)
api_key = metaphor_api_key or os.environ.get("METAPHOR_API_KEY", None)
assert (
api_key is not None
), "Metaphor API key must be provided as metaphor_api_key or METAPHOR_API_KEY env var"

client = Metaphor(api_key=api_key)
return Tool(
name="metaphor_query",
description="Metaphor Search. Searches the web for pages that match a given query.",
func=client.search,
coroutine=sync_to_async(client.search),
**tool_kwargs
)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ jsonpath-ng==1.5.3
jsonschema==4.0.1
langchain==0.0.271
llama-cpp-python==0.1.79
metaphor-python==0.1.16
openai==0.27.8
openapi-schema-pydantic==1.2.4
pinecone-client==2.2.1
Expand Down

0 comments on commit bdc7a33

Please sign in to comment.