langchain icon indicating copy to clipboard operation
langchain copied to clipboard

PythonREPLTool._run() missing 1 required positional argument: 'query'

Open maver1ck opened this issue 1 year ago • 1 comments

Hi, I tried to use Python REPL tool with new Structured Tools Agent. (Langchain version 0.0.157) Code:

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math", "python_repl"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

prompt = """
Act as a Bank Analysts.
You have to analyze data of a customer with following features:
- man
- age: 40-50
- income: 5000 GBP
- lives in London

Monthly Spending in CSV format in GBP.
First row (header) have category names, next there is one row per month
####
Food and Dining,Shopping,Transportation,Travel,Bills and Utilities,Entertainment,Health and Wellness,Personal Care,Education,Children
200,150,100,500,300,100,75,50,250,200
250,175,125,0,300,100,75,50,250,200
300,200,150,0,300,125,100,50,250,200
275,225,175,0,300,150,100,75,0,200
225,250,200,0,300,175,125,100,0,200
250,225,225,0,300,200,150,125,0,200
300,200,250,500,300,225,175,125,0,200
275,175,225,0,300,200,200,100,0,200
225,150,200,0,300,175,200,75,250,200
250,225,175,0,300,150,175,75,250,200
300,250,150,0,300,125,125,50,250,200
275,200,125,0,300,100,100,50,0,200
####


Save this data to CSV file. Then analyze it and provide as many insights for this customer as possible.
Create bank recommendation for the customer. Also include some diagrams.
For reference average monthly spendings for customer with similar income is:
Food and Dining - 400
Shopping - 200
Transportation - 200,
Travel - 100
Bills and Utilities - 400
Entertainment - 100
Health and Wellness - 50
Personal Care - 25
Education - 100
Children - 200


"""
agent.run(prompt)

Debug:

Thought: I can use Python to analyze the CSV file and calculate the customer's average monthly spending for each category. Then, I can compare it to the average monthly spending for customers with similar income and provide recommendations based on the difference.

Action:
{
  "action": "Python REPL",
  "query": "import csv\n\nwith open('customer_spending.csv', 'r') as file:\n    reader = csv.reader(file)\n    headers = next(reader)\n    spending = {header: [] for header in headers}\n    for row in reader:\n        for i, value in enumerate(row):\n            spending[headers[i]].append(int(value))\n\naverage_spending = {}\nfor category, values in spending.items():\n    average_spending[category] = sum(values) / len(values)\n\nprint(average_spending)"
}

Exception:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[12], line 44
      1 prompt = """
      2 Act as a Bank Analysts.
      3 You have to analyze data of a customer with following features:
   (...)
     42 
     43 """
---> 44 agent.run(prompt)

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/chains/base.py:238, in Chain.run(self, callbacks, *args, **kwargs)
    236     if len(args) != 1:
    237         raise ValueError("`run` supports only one positional argument.")
--> 238     return self(args[0], callbacks=callbacks)[self.output_keys[0]]
    240 if kwargs and not args:
    241     return self(kwargs, callbacks=callbacks)[self.output_keys[0]]

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/chains/base.py:142, in Chain.__call__(self, inputs, return_only_outputs, callbacks)
    140 except (KeyboardInterrupt, Exception) as e:
    141     run_manager.on_chain_error(e)
--> 142     raise e
    143 run_manager.on_chain_end(outputs)
    144 return self.prep_outputs(inputs, outputs, return_only_outputs)

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/chains/base.py:136, in Chain.__call__(self, inputs, return_only_outputs, callbacks)
    130 run_manager = callback_manager.on_chain_start(
    131     {"name": self.__class__.__name__},
    132     inputs,
    133 )
    134 try:
    135     outputs = (
--> 136         self._call(inputs, run_manager=run_manager)
    137         if new_arg_supported
    138         else self._call(inputs)
    139     )
    140 except (KeyboardInterrupt, Exception) as e:
    141     run_manager.on_chain_error(e)

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/agents/agent.py:905, in AgentExecutor._call(self, inputs, run_manager)
    903 # We now enter the agent loop (until it returns something).
    904 while self._should_continue(iterations, time_elapsed):
--> 905     next_step_output = self._take_next_step(
    906         name_to_tool_map,
    907         color_mapping,
    908         inputs,
    909         intermediate_steps,
    910         run_manager=run_manager,
    911     )
    912     if isinstance(next_step_output, AgentFinish):
    913         return self._return(
    914             next_step_output, intermediate_steps, run_manager=run_manager
    915         )

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/agents/agent.py:783, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager)
    781         tool_run_kwargs["llm_prefix"] = ""
    782     # We then call the tool on the tool input to get an observation
--> 783     observation = tool.run(
    784         agent_action.tool_input,
    785         verbose=self.verbose,
    786         color=color,
    787         callbacks=run_manager.get_child() if run_manager else None,
    788         **tool_run_kwargs,
    789     )
    790 else:
    791     tool_run_kwargs = self.agent.tool_run_logging_kwargs()

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/tools/base.py:253, in BaseTool.run(self, tool_input, verbose, start_color, color, callbacks, **kwargs)
    251 except (Exception, KeyboardInterrupt) as e:
    252     run_manager.on_tool_error(e)
--> 253     raise e
    254 run_manager.on_tool_end(str(observation), color=color, name=self.name, **kwargs)
    255 return observation

File ~/.virtualenvs/langchain-playground-zonf/lib/python3.10/site-packages/langchain/tools/base.py:247, in BaseTool.run(self, tool_input, verbose, start_color, color, callbacks, **kwargs)
    244 try:
    245     tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input)
    246     observation = (
--> 247         self._run(*tool_args, run_manager=run_manager, **tool_kwargs)
    248         if new_arg_supported
    249         else self._run(*tool_args, **tool_kwargs)
    250     )
    251 except (Exception, KeyboardInterrupt) as e:
    252     run_manager.on_tool_error(e)

TypeError: PythonREPLTool._run() missing 1 required positional argument: 'query'

maver1ck avatar May 04 '23 14:05 maver1ck

Looks like no action input was directly provided:

Action:
{
  "action": "Python REPL",
  "query": "import csv\n\nwith open('customer_spending.csv', 'r') as file:\n    reader = csv.reader(file)\n    headers = next(reader)\n    spending = {header: [] for header in headers}\n    for row in reader:\n        for i, value in enumerate(row):\n            spending[headers[i]].append(int(value))\n\naverage_spending = {}\nfor category, values in spending.items():\n    average_spending[category] = sum(values) / len(values)\n\nprint(average_spending)"
}

May need some prompt engineering. This should look like

Action:
{
  "action": "Python REPL",
  "action_input": {"query": "import csv\n\nwith open('customer_spending.csv', 'r') as file:\n    reader = csv.reader(file)\n    headers = next(reader)\n    spending = {header: [] for header in headers}\n    for row in reader:\n        for i, value in enumerate(row):\n            spending[headers[i]].append(int(value))\n\naverage_spending = {}\nfor category, values in spending.items():\n    average_spending[category] = sum(values) / len(values)\n\nprint(average_spending)"
}
}

vowelparrot avatar May 04 '23 18:05 vowelparrot

Hi, @maver1ck! I'm Dosu, and I'm helping the LangChain team manage their backlog. I wanted to let you know that we are marking this issue as stale.

From what I understand, you reported an issue regarding the Python REPL tool missing a required positional argument 'query' in the _run() method, which resulted in a TypeError. User vowelparrot suggested in the comments that this issue may be due to the lack of an action input provided. They provided an example of how the action input should be structured to include the 'query' argument.

I wanted to check with you if this issue is still relevant to the latest version of the LangChain repository. If it is, please let the LangChain team know by commenting on the issue. Otherwise, feel free to close the issue yourself. If we don't hear back from you, the issue will be automatically closed in 7 days.

Thank you for your contribution to the LangChain repository! Let us know if you have any further questions or concerns.

dosubot[bot] avatar Sep 01 '23 16:09 dosubot[bot]

Seeing this too - any fix?

raihaan123 avatar Oct 09 '23 14:10 raihaan123

@raihaan123 I came across with this problem, but in doing my own custom agent, and found a solution given in that issue. But, I'm not sure if that helps your situation.

jamshid17 avatar Oct 12 '23 12:10 jamshid17