Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions libs/langchain/langchain/agents/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
**Agent** is a class that uses an LLM to choose a sequence of actions to take.
"""**Agent** is a class that uses an LLM to choose a sequence of actions to take.

In Chains, a sequence of actions is hardcoded. In Agents,
a language model is used as a reasoning engine to determine which actions
Expand Down
2 changes: 0 additions & 2 deletions libs/langchain/langchain/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,6 @@ def save(self, file_path: Union[Path, str]) -> None:

def tool_run_logging_kwargs(self) -> builtins.dict:
"""Return logging kwargs for tool run."""

return {}


Expand Down Expand Up @@ -1807,7 +1806,6 @@ async def astream(
Yields:
AddableDict: Addable dictionary.
"""

config = ensure_config(config)
iterator = AgentExecutorIterator(
self,
Expand Down
35 changes: 18 additions & 17 deletions libs/langchain/langchain/agents/agent_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ def __init__(
include_run_info: bool = False,
yield_actions: bool = False,
):
"""
"""Initialize the AgentExecutorIterator.

Initialize the AgentExecutorIterator with the given AgentExecutor,
inputs, and optional callbacks.

Expand Down Expand Up @@ -129,7 +130,8 @@ def color_mapping(self) -> dict[str, str]:
)

def reset(self) -> None:
"""
"""Reset the iterator to its initial state.

Reset the iterator to its initial state, clearing intermediate steps,
iterations, and time elapsed.
"""
Expand All @@ -141,9 +143,7 @@ def reset(self) -> None:
self.start_time = time.time()

def update_iterations(self) -> None:
"""
Increment the number of iterations and update the time elapsed.
"""
"""Increment the number of iterations and update the time elapsed."""
self.iterations += 1
self.time_elapsed = time.time() - self.start_time
logger.debug(
Expand Down Expand Up @@ -242,9 +242,10 @@ def __iter__(self: AgentExecutorIterator) -> Iterator[AddableDict]:
yield self._stop(run_manager)

async def __aiter__(self) -> AsyncIterator[AddableDict]:
"""
"""Create an async iterator for the AgentExecutor.

N.B. __aiter__ must be a normal method, so need to initialize async run manager
on first __anext__ call where we can await it
on first __anext__ call where we can await it.
"""
logger.debug("Initialising AgentExecutorIterator (async)")
self.reset()
Expand Down Expand Up @@ -326,7 +327,8 @@ def _process_next_step_output(
next_step_output: Union[AgentFinish, list[tuple[AgentAction, str]]],
run_manager: CallbackManagerForChainRun,
) -> AddableDict:
"""
"""Process the output of the next step.

Process the output of the next step,
handling AgentFinish and tool return cases.
"""
Expand Down Expand Up @@ -354,7 +356,8 @@ async def _aprocess_next_step_output(
next_step_output: Union[AgentFinish, list[tuple[AgentAction, str]]],
run_manager: AsyncCallbackManagerForChainRun,
) -> AddableDict:
"""
"""Process the output of the next async step.

Process the output of the next async step,
handling AgentFinish and tool return cases.
"""
Expand All @@ -378,7 +381,8 @@ async def _aprocess_next_step_output(
return AddableDict(intermediate_step=next_step_output)

def _stop(self, run_manager: CallbackManagerForChainRun) -> AddableDict:
"""
"""Stop the iterator.

Stop the iterator and raise a StopIteration exception with the stopped response.
"""
logger.warning("Stopping agent prematurely due to triggering stop condition")
Expand All @@ -391,7 +395,8 @@ def _stop(self, run_manager: CallbackManagerForChainRun) -> AddableDict:
return self._return(output, run_manager=run_manager)

async def _astop(self, run_manager: AsyncCallbackManagerForChainRun) -> AddableDict:
"""
"""Stop the async iterator.

Stop the async iterator and raise a StopAsyncIteration exception with
the stopped response.
"""
Expand All @@ -408,9 +413,7 @@ def _return(
output: AgentFinish,
run_manager: CallbackManagerForChainRun,
) -> AddableDict:
"""
Return the final output of the iterator.
"""
"""Return the final output of the iterator."""
returned_output = self.agent_executor._return( # noqa: SLF001
output,
self.intermediate_steps,
Expand All @@ -425,9 +428,7 @@ async def _areturn(
output: AgentFinish,
run_manager: AsyncCallbackManagerForChainRun,
) -> AddableDict:
"""
Return the final output of the async iterator.
"""
"""Return the final output of the async iterator."""
returned_output = await self.agent_executor._areturn( # noqa: SLF001
output,
self.intermediate_steps,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ def create_conversational_retrieval_agent(
defaults to False.
max_token_limit: The max number of tokens to keep around in memory.
Defaults to 2000.
**kwargs: Additional keyword arguments to pass to the AgentExecutor.

Returns:
An agent executor initialized appropriately
"""

if remember_intermediate_steps:
memory: BaseMemory = AgentTokenBufferMemory(
memory_key=memory_key,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_csv_agent":
msg = (
"This agent has been moved to langchain experiment. "
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"""NASA Toolkit"""
"""NASA Toolkit."""
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_pandas_dataframe_agent":
msg = (
"This agent has been moved to langchain experiment. "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_python_agent":
msg = (
"This agent has been moved to langchain experiment. "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_spark_dataframe_agent":
msg = (
"This agent has been moved to langchain experiment. "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

def __getattr__(name: str) -> Any:
"""Get attr name."""

if name == "create_xorbits_agent":
msg = (
"This agent has been moved to langchain experiment. "
Expand Down
1 change: 0 additions & 1 deletion libs/langchain/langchain/agents/chat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ def create_prompt(
Returns:
A prompt template.
"""

tool_strings = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])
tool_names = ", ".join([tool.name for tool in tools])
format_instructions = format_instructions.format(tool_names=tool_names)
Expand Down
4 changes: 1 addition & 3 deletions libs/langchain/langchain/agents/chat/output_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ def get_format_instructions(self) -> str:
return self.format_instructions

def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
"""Parse the output from the agent into
an AgentAction or AgentFinish object.
"""Parse the output from the agent into an AgentAction or AgentFinish object.

Args:
text: The text to parse.
Expand All @@ -39,7 +38,6 @@ def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
OutputParserException: If the output could not be parsed.
ValueError: If the action could not be found.
"""

includes_answer = FINAL_ANSWER_ACTION in text
try:
found = self.pattern.search(text)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,14 @@ def get_format_instructions(self) -> str:
return self.format_instructions

def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
"""Parse the output from the agent into
an AgentAction or AgentFinish object.
"""Parse the output from the agent into an AgentAction or AgentFinish object.

Args:
text: The text to parse.

Returns:
An AgentAction or AgentFinish object.
"""

if f"{self.ai_prefix}:" in text:
return AgentFinish(
{"output": text.split(f"{self.ai_prefix}:")[-1].strip()},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def _convert_agent_action_to_messages(

Args:
agent_action: Agent action to convert.
observation: The result of the tool invocation.

Returns:
AIMessage or the previous messages plus a FunctionMessage that corresponds to
Expand All @@ -34,9 +35,11 @@ def _create_function_message(
observation: Any,
) -> FunctionMessage:
"""Convert agent action and observation into a function message.

Args:
agent_action: the tool invocation request from the agent.
observation: the result of the tool invocation.

Returns:
FunctionMessage that corresponds to the original tool invocation.

Expand Down
1 change: 1 addition & 0 deletions libs/langchain/langchain/agents/format_scratchpad/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def _create_tool_message(
Args:
agent_action: the tool invocation request from the agent.
observation: the result of the tool invocation.

Returns:
ToolMessage that corresponds to the original tool invocation.

Expand Down
38 changes: 19 additions & 19 deletions libs/langchain/langchain/agents/json_chat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def create_json_chat_agent(
tools_renderer: ToolsRenderer = render_text_description,
template_tool_response: str = TEMPLATE_TOOL_RESPONSE,
) -> Runnable:
"""Create an agent that uses JSON to format its logic, build for Chat Models.
r"""Create an agent that uses JSON to format its logic, build for Chat Models.

Args:
llm: LLM to use as the agent.
Expand Down Expand Up @@ -93,27 +93,27 @@ def create_json_chat_agent(

system = '''Assistant is a large language model trained by OpenAI.

Assistant is designed to be able to assist with a wide range of tasks, from answering \
simple questions to providing in-depth explanations and discussions on a wide range of \
topics. As a language model, Assistant is able to generate human-like text based on \
the input it receives, allowing it to engage in natural-sounding conversations and \
Assistant is designed to be able to assist with a wide range of tasks, from answering
simple questions to providing in-depth explanations and discussions on a wide range of
topics. As a language model, Assistant is able to generate human-like text based on
the input it receives, allowing it to engage in natural-sounding conversations and
provide responses that are coherent and relevant to the topic at hand.

Assistant is constantly learning and improving, and its capabilities are constantly \
evolving. It is able to process and understand large amounts of text, and can use this \
knowledge to provide accurate and informative responses to a wide range of questions. \
Additionally, Assistant is able to generate its own text based on the input it \
receives, allowing it to engage in discussions and provide explanations and \
Assistant is constantly learning and improving, and its capabilities are constantly
evolving. It is able to process and understand large amounts of text, and can use this
knowledge to provide accurate and informative responses to a wide range of questions.
Additionally, Assistant is able to generate its own text based on the input it
receives, allowing it to engage in discussions and provide explanations and
descriptions on a wide range of topics.

Overall, Assistant is a powerful system that can help with a wide range of tasks \
and provide valuable insights and information on a wide range of topics. Whether \
you need help with a specific question or just want to have a conversation about \
Overall, Assistant is a powerful system that can help with a wide range of tasks
and provide valuable insights and information on a wide range of topics. Whether
you need help with a specific question or just want to have a conversation about
a particular topic, Assistant is here to assist.'''

human = '''TOOLS
------
Assistant can ask the user to use tools to look up information that may be helpful in \
Assistant can ask the user to use tools to look up information that may be helpful in
answering the users original question. The tools the human can use are:

{tools}
Expand All @@ -129,25 +129,25 @@ def create_json_chat_agent(

```json
{{
"action": string, \\ The action to take. Must be one of {tool_names}
"action_input": string \\ The input to the action
"action": string, \\\\ The action to take. Must be one of {tool_names}
"action_input": string \\\\ The input to the action
}}
```

**Option #2:**
Use this if you want to respond directly to the human. Markdown code snippet formatted \
Use this if you want to respond directly to the human. Markdown code snippet formatted
in the following schema:

```json
{{
"action": "Final Answer",
"action_input": string \\ You should put what you want to return to use here
"action_input": string \\\\ You should put what you want to return to use here
}}
```

USER'S INPUT
--------------------
Here is the user's input (remember to respond with a markdown code snippet of a json \
Here is the user's input (remember to respond with a markdown code snippet of a json
blob with a single action, and NOTHING else):

{input}'''
Expand Down
3 changes: 1 addition & 2 deletions libs/langchain/langchain/agents/mrkl/output_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ def get_format_instructions(self) -> str:
return self.format_instructions

def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
"""Parse the output from the agent into
an AgentAction or AgentFinish object.
"""Parse the output from the agent into an AgentAction or AgentFinish object.

Args:
text: The text to parse.
Expand Down
4 changes: 2 additions & 2 deletions libs/langchain/langchain/agents/openai_assistant/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,14 +302,14 @@ def invoke(
attachments: A list of files attached to the message, and the
tools they should be added to.
config: Runnable config. Defaults to None.
**kwargs: Additional arguments.

Return:
If self.as_agent, will return
Union[List[OpenAIAssistantAction], OpenAIAssistantFinish].
Otherwise, will return OpenAI types
Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]].
"""

config = ensure_config(config)
callback_manager = CallbackManager.configure(
inheritable_callbacks=config.get("callbacks"),
Expand Down Expand Up @@ -390,6 +390,7 @@ async def acreate_assistant(
model: Assistant model to use.
async_client: AsyncOpenAI client.
Will create default async_client if not specified.
**kwargs: Additional arguments.

Returns:
AsyncOpenAIAssistantRunnable configured to run using the created assistant.
Expand Down Expand Up @@ -442,7 +443,6 @@ async def ainvoke(
Otherwise, will return OpenAI types
Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]].
"""

config = config or {}
callback_manager = CallbackManager.configure(
inheritable_callbacks=config.get("callbacks"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ def input_keys(self) -> list[str]:
@property
def functions(self) -> list[dict]:
"""Get functions."""

return [dict(convert_to_openai_function(t)) for t in self.tools]

def plan(
Expand Down Expand Up @@ -309,7 +308,6 @@ def create_openai_functions_agent(
ValueError: If `agent_scratchpad` is not in the prompt.

Example:

Creating an agent with no memory

.. code-block:: python
Expand Down
Loading