langchain-ai / langchain

🦜🔗 Build context-aware reasoning applications
https://python.langchain.com
MIT License
94.45k stars 15.27k forks source link

ReAct Agent doesn't execute #10976

Closed Tejaswgupta closed 10 months ago

Tejaswgupta commented 1 year ago

System Info

Name: langchain Version: 0.0.300 Summary: Building applications with LLMs through composability Home-page: https://github.com/langchain-ai/langchain Author: None Author-email: None License: MIT Location: /anaconda/envs/azureml_py38/lib/python3.8/site-packages Requires: requests, jsonpatch, dataclasses-json, numpy, tenacity, numexpr, aiohttp, langsmith, anyio, SQLAlchemy, pydantic, async-timeout, PyYAML Required-by: llama-index

Who can help?

No response

Information

Related Components

Reproduction

from langchain.llms import HuggingFaceTextGenInference

llm = HuggingFaceTextGenInference(
    inference_server_url="http://x.x.x.x:8080/",
    max_new_tokens=512,
    top_k=10,
    top_p=0.95,
    typical_p=0.95,
    temperature=0.6,
    # repetition_penalty=1.1,
)

from langchain.llms import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.agents.react.base import DocstoreExplorer

docstore = DocstoreExplorer(vectordb)
tools = [
    Tool(
        name="Search",
        func=docstore.search,
        description="useful for when you need to ask with search",
    ),
    Tool(
        name="Lookup",
        func=docstore.lookup,
        description="useful for when you need to ask with lookup",
    ),
]

react = initialize_agent(tools, model, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
react.run('Punishment for drinking and driving')

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/azureuser/cloudfiles/code/Users/Tejasw/langchain_retreival.ipynb Cell 34 line 1
----> 1 react.run('Punishment for drinking and driving')

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/chains/base.py:487, in Chain.run(self, callbacks, tags, metadata, *args, **kwargs)
    485     if len(args) != 1:
    486         raise ValueError("`run` supports only one positional argument.")
--> 487     return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[
    488         _output_key
    489     ]
    491 if kwargs and not args:
    492     return self(kwargs, callbacks=callbacks, tags=tags, metadata=metadata)[
    493         _output_key
    494     ]

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/chains/base.py:292, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)
    290 except BaseException as e:
    291     run_manager.on_chain_error(e)
--> 292     raise e
    293 run_manager.on_chain_end(outputs)
    294 final_outputs: Dict[str, Any] = self.prep_outputs(
    295     inputs, outputs, return_only_outputs
    296 )

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/chains/base.py:286, in Chain.__call__(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)
    279 run_manager = callback_manager.on_chain_start(
    280     dumpd(self),
    281     inputs,
    282     name=run_name,
    283 )
    284 try:
    285     outputs = (
--> 286         self._call(inputs, run_manager=run_manager)
    287         if new_arg_supported
    288         else self._call(inputs)
    289     )
    290 except BaseException as e:
    291     run_manager.on_chain_error(e)

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/agents/agent.py:1122, in AgentExecutor._call(self, inputs, run_manager)
   1120 # We now enter the agent loop (until it returns something).
   1121 while self._should_continue(iterations, time_elapsed):
-> 1122     next_step_output = self._take_next_step(
   1123         name_to_tool_map,
   1124         color_mapping,
   1125         inputs,
   1126         intermediate_steps,
   1127         run_manager=run_manager,
   1128     )
   1129     if isinstance(next_step_output, AgentFinish):
   1130         return self._return(
   1131             next_step_output, intermediate_steps, run_manager=run_manager
   1132         )

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/agents/agent.py:977, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager)
    975         tool_run_kwargs["llm_prefix"] = ""
    976     # We then call the tool on the tool input to get an observation
--> 977     observation = tool.run(
    978         agent_action.tool_input,
    979         verbose=self.verbose,
    980         color=color,
    981         callbacks=run_manager.get_child() if run_manager else None,
    982         **tool_run_kwargs,
    983     )
    984 else:
    985     tool_run_kwargs = self.agent.tool_run_logging_kwargs()

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/tools/base.py:360, in BaseTool.run(self, tool_input, verbose, start_color, color, callbacks, tags, metadata, run_name, **kwargs)
    358 except (Exception, KeyboardInterrupt) as e:
    359     run_manager.on_tool_error(e)
--> 360     raise e
    361 else:
    362     run_manager.on_tool_end(
    363         str(observation), color=color, name=self.name, **kwargs
    364     )

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/tools/base.py:332, in BaseTool.run(self, tool_input, verbose, start_color, color, callbacks, tags, metadata, run_name, **kwargs)
    329 try:
    330     tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input)
    331     observation = (
--> 332         self._run(*tool_args, run_manager=run_manager, **tool_kwargs)
    333         if new_arg_supported
    334         else self._run(*tool_args, **tool_kwargs)
    335     )
    336 except ToolException as e:
    337     if not self.handle_tool_error:

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/tools/base.py:511, in Tool._run(self, run_manager, *args, **kwargs)
    502 if self.func:
    503     new_argument_supported = signature(self.func).parameters.get("callbacks")
    504     return (
    505         self.func(
    506             *args,
    507             callbacks=run_manager.get_child() if run_manager else None,
    508             **kwargs,
    509         )
    510         if new_argument_supported
--> 511         else self.func(*args, **kwargs)
    512     )
    513 raise NotImplementedError("Tool does not support sync")

File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/langchain/agents/react/base.py:77, in DocstoreExplorer.search(self, term)
     75 def search(self, term: str) -> str:
     76     """Search for a term in the docstore, and if found save."""
---> 77     result = self.docstore.search(term)
     78     if isinstance(result, Document):
     79         self.document = result

TypeError: search() missing 1 required positional argument: 'search_type'

Expected behavior

Should successfully execute.

dosubot[bot] commented 1 year ago

🤖

Hello,

The error message you're seeing is due to the search method in the DocstoreExplorer class requiring a search_type argument that is not being provided.

In your code, you're initializing the Search tool with the docstore.search function:

Tool(
    name="Search",
    func=docstore.search,
    description="useful for when you need to ask with search",
),

However, the search method in the DocstoreExplorer class requires two arguments: term and search_type. You're providing the term argument when you call react.run('Punishment for drinking and driving'), but the search_type argument is missing.

To resolve this issue, you need to ensure that the search_type argument is provided when the search method is called. This could be done by modifying the Tool object to accept arguments, or by providing a default search_type in the search method definition.

Please note that the exact solution would depend on the rest of your code and how the Tool object is used. If you need further assistance, please provide more details about your implementation and how you're using the Tool object.

Best, Dosu

Sources


This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.

Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

If you want to continue the conversation, start your reply with @dosu-bot.

Tejaswgupta commented 1 year ago

@dosu-bot Looking at libs/langchain/langchain/agents/react/base.py DocstoreExplorer doesn't have a requirement for search_type.

class DocstoreExplorer:
    """Class to assist with exploration of a document store."""

    def __init__(self, docstore: Docstore):
        """Initialize with a docstore, and set initial document to None."""
        self.docstore = docstore
        self.document: Optional[Document] = None
        self.lookup_str = ""
        self.lookup_index = 0

    def search(self, term: str) -> str:
        """Search for a term in the docstore, and if found save."""
        result = self.docstore.search(term)
        if isinstance(result, Document):
            self.document = result
            return self._summary
        else:
            self.document = None
            return result

    def lookup(self, term: str) -> str:
        """Lookup a term in document (if saved)."""
        if self.document is None:
            raise ValueError("Cannot lookup without a successful search first")
        if term.lower() != self.lookup_str:
            self.lookup_str = term.lower()
            self.lookup_index = 0
        else:
            self.lookup_index += 1
        lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()]
        if len(lookups) == 0:
            return "No Results"
        elif self.lookup_index >= len(lookups):
            return "No More Results"
        else:
            result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})"
            return f"{result_prefix} {lookups[self.lookup_index]}"

    @property
    def _summary(self) -> str:
        return self._paragraphs[0]

    @property
    def _paragraphs(self) -> List[str]:
        if self.document is None:
            raise ValueError("Cannot get paragraphs without a document")
        return self.document.page_content.split("\n\n")
dosubot[bot] commented 1 year ago

🤖

Hello,

Thank you for reaching out and providing a detailed description of your issue. The error message you're seeing, TypeError: search() missing 1 required positional argument: 'search_type', suggests that the search() function is expecting an argument named search_type that isn't being provided.

However, based on the code you've shared, it seems that the search() function in the DocstoreExplorer class doesn't require a search_type argument. It only requires a term argument. This suggests that the error might be originating from somewhere else in your code.

The search_type argument is used in the similarity_search_with_score and _raw_similarity_search_with_score methods of the OpenSearchVectorSearch class, not in the DocstoreExplorer class. It's used to specify the type of search to be performed and can take one of three values: "approximate_search", "script_scoring", or "painless_scripting".

I recommend checking the rest of your code to ensure that the search() function is being called correctly. If you're using the OpenSearchVectorSearch class or a similar class that requires a search_type argument, make sure you're providing that argument when calling the search() function.

If you're still encountering this issue after checking your code, could you please provide more information about the context in which you're using the DocstoreExplorer class? Specifically, it would be helpful to know more about the vectordb object that you're passing to the DocstoreExplorer constructor, as well as any other parts of your code that interact with the DocstoreExplorer instance.

I hope this helps, and I look forward to your response.

Sources


This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.

Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

If you want to continue the conversation, start your reply with @dosu-bot.

dosubot[bot] commented 10 months ago

Hi, @Tejaswgupta

I'm helping the LangChain team manage their backlog and am marking this issue as stale. From what I understand, you reported a TypeError in the search method of the DocstoreExplorer, and there was a discussion about the potential cause of the error. However, the issue remains unresolved.

Could you please confirm if this issue is still relevant to the latest version of the LangChain repository? If it is, kindly let the LangChain team know by commenting on the issue. Otherwise, feel free to close the issue yourself, or it will be automatically closed in 7 days.

Thank you for your understanding and cooperation.