Created
April 14, 2023 14:56
-
-
Save koganei/3b6ba574434522f73f10a57ea804f70e to your computer and use it in GitHub Desktop.
Using a langchain tool in a Haystack agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_wolfram_alpha_tool(): | |
from haystack.agents import Tool | |
from walpha_tool.tool import WolframAlphaNode | |
node = WolframAlphaNode() | |
return Tool(name="WolframAlpha", | |
pipeline_or_node=node, | |
description="A wrapper around Wolfram Alpha. " # Taken verbatim from the langchain code, could be done automatically somehow | |
"Useful for when you need to answer questions about Math," | |
"Science, Technology, Culture, Society and Everyday Life." | |
"Input should be a search query." | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from langchain.agents import load_tools | |
from langchain.agents import initialize_agent | |
from langchain.agents import AgentType | |
from langchain.llms import OpenAI | |
from haystack.nodes.base import BaseComponent | |
class WolframAlphaNode(BaseComponent): | |
def __init__(self): | |
super(WolframAlphaNode, self).__init__() | |
self.agent = self.create_agent() | |
outgoing_edges = 1 | |
def run( | |
self, | |
query: str = None | |
): | |
print("running Wolfram Alpha") | |
try: | |
return self.agent.run(query) | |
except Exception as e: | |
print("Error: " + str(e)) | |
return "Sorry, an error has occured when using the tool." | |
def create_agent(self): | |
llm = OpenAI(temperature=0.2) | |
tools = load_tools( | |
["wolfram-alpha", "llm-math"], wolfram_alpha_appid=os.environ["WOLFRAM_ALPHA_APPID"], llm=llm) | |
agent = initialize_agent( | |
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) | |
print("running agent") | |
return agent | |
def run_batch( | |
self, | |
query: str = None, | |
**kwargs | |
): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment