python-3.xlangchainpy-langchain

load_tool does not recognize python_repl in langchain


I am using Langchain to connect to OpenAi and some basic python calculation. below is the code i am using:

from langchain.llms.fake import FakeListLLM
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
tools = load_tools(["python_repl"])
responses=["Action: Python REPL\nAction Input: print(2 + 2)",
"Final Answer: 4"
]
llm = FakeListLLM(responses=responses)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, 
verbose=True)
agent.run("whats 2 + 2").   

I am referred to the langchain document and the code seems to be fine, there is no sysntexical error. in another code i called another library and created a new object here as:

from langchain_experimental.utilities import PythonREPL
python_repl = PythonREPL()

This code when ran on a simple instance runs:
example:

python_repl.run("print(10+34)")

But when i try to call python_repl from load_tool it throws error as ValueError: Got unknown tool python_repl. what is missed in the above code block.


Solution

  • I believe this code as printed in the book "Generative AI with LangChain" relies on and older version of langchain. langchain[docarray]==0.0.284 to be exact.

    I suggest setting up a conda environment for the book as there seemed to be breaking changes.

    If on the other hand you would want to use the newest LangChain version, this would work:

    from langchain.agents import load_tools
    from langchain.agents import initialize_agent
    from langchain.agents import AgentType, Tool
    from langchain.utilities import PythonREPL
    from langchain_experimental.tools import PythonREPLTool
    
    agent = initialize_agent(
        tools=[PythonREPLTool()],
        llm=llm,
    )
    
    agent.invoke("what is 2 + 2?")ython_repl",
        description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",
        func=python_repl.run,
    )
    
    agent = initialize_agent(
        tools=[python_repl],
        llm=llm,
    )
    
    agent.invoke("what is 2 + 2?")