The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(langchain): add ruff rules D (except D100 and D104) (#31994)
Christophe Bornetc3b28c769ad2
diff --git a/libs/langchain/langchain/agents/__init__.py b/libs/langchain/langchain/agents/__init__.pyindex f182b3b6b7..b71570735e 100644--- a/libs/langchain/langchain/agents/__init__.py+++ b/libs/langchain/langchain/agents/__init__.py@@ -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 actionsdiff --git a/libs/langchain/langchain/agents/agent.py b/libs/langchain/langchain/agents/agent.pyindex f695a6d616..9d0db3ad8f 100644--- a/libs/langchain/langchain/agents/agent.py+++ b/libs/langchain/langchain/agents/agent.py@@ -366,7 +366,6 @@ class BaseMultiActionAgent(BaseModel):def tool_run_logging_kwargs(self) -> builtins.dict:"""Return logging kwargs for tool run."""-return {}@@ -1807,7 +1806,6 @@ class AgentExecutor(Chain):Yields:AddableDict: Addable dictionary."""-config = ensure_config(config)iterator = AgentExecutorIterator(self,diff --git a/libs/langchain/langchain/agents/agent_iterator.py b/libs/langchain/langchain/agents/agent_iterator.pyindex 34479ab857..6d6adab5af 100644--- a/libs/langchain/langchain/agents/agent_iterator.py+++ b/libs/langchain/langchain/agents/agent_iterator.py@@ -55,7 +55,8 @@ class AgentExecutorIterator:include_run_info: bool = False,yield_actions: bool = False,):- """+ """Initialize the AgentExecutorIterator.+Initialize the AgentExecutorIterator with the given AgentExecutor,inputs, and optional callbacks.@@ -129,7 +130,8 @@ class AgentExecutorIterator:)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."""@@ -141,9 +143,7 @@ class AgentExecutorIterator: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 += 1self.time_elapsed = time.time() - self.start_timelogger.debug(@@ -242,9 +242,10 @@ class AgentExecutorIterator: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()@@ -326,7 +327,8 @@ class AgentExecutorIterator: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."""@@ -354,7 +356,8 @@ class AgentExecutorIterator: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."""@@ -378,7 +381,8 @@ class AgentExecutorIterator: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")@@ -391,7 +395,8 @@ class AgentExecutorIterator: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 withthe stopped response."""@@ -408,9 +413,7 @@ class AgentExecutorIterator: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: SLF001output,self.intermediate_steps,@@ -425,9 +428,7 @@ class AgentExecutorIterator: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: SLF001output,self.intermediate_steps,diff --git a/libs/langchain/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.py b/libs/langchain/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.pyindex cd970ba17a..593b8d7f0d 100644--- a/libs/langchain/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.py+++ b/libs/langchain/langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.py@@ -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,diff --git a/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.pyindex c877de1257..647c525b7d 100644--- a/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py+++ b/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py@@ -3,7 +3,6 @@ from typing import Anydef __getattr__(name: str) -> Any:"""Get attr name."""-if name == "create_csv_agent":msg = ("This agent has been moved to langchain experiment. "diff --git a/libs/langchain/langchain/agents/agent_toolkits/nasa/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/nasa/__init__.pyindex a13c3ec706..c70f769f29 100644--- a/libs/langchain/langchain/agents/agent_toolkits/nasa/__init__.py+++ b/libs/langchain/langchain/agents/agent_toolkits/nasa/__init__.py@@ -1 +1 @@-"""NASA Toolkit"""+"""NASA Toolkit."""diff --git a/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.pyindex 4ed1ad4a19..f767ee56a6 100644--- a/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py+++ b/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py@@ -3,7 +3,6 @@ from typing import Anydef __getattr__(name: str) -> Any:"""Get attr name."""-if name == "create_pandas_dataframe_agent":msg = ("This agent has been moved to langchain experiment. "diff --git a/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/python/__init__.pyindex 674f38e96c..bc39e1fd17 100644--- a/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py+++ b/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py@@ -3,7 +3,6 @@ from typing import Anydef __getattr__(name: str) -> Any:"""Get attr name."""-if name == "create_python_agent":msg = ("This agent has been moved to langchain experiment. "diff --git a/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.pyindex 5be92f2379..a0a95ce96b 100644--- a/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py+++ b/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py@@ -3,7 +3,6 @@ from typing import Anydef __getattr__(name: str) -> Any:"""Get attr name."""-if name == "create_spark_dataframe_agent":msg = ("This agent has been moved to langchain experiment. "diff --git a/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.pyindex 04c235e9bd..2b5d7a21df 100644--- a/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py+++ b/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py@@ -3,7 +3,6 @@ from typing import Anydef __getattr__(name: str) -> Any:"""Get attr name."""-if name == "create_xorbits_agent":msg = ("This agent has been moved to langchain experiment. "diff --git a/libs/langchain/langchain/agents/chat/base.py b/libs/langchain/langchain/agents/chat/base.pyindex a19fb899c9..19cdfde799 100644--- a/libs/langchain/langchain/agents/chat/base.py+++ b/libs/langchain/langchain/agents/chat/base.py@@ -105,7 +105,6 @@ class ChatAgent(Agent):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)diff --git a/libs/langchain/langchain/agents/chat/output_parser.py b/libs/langchain/langchain/agents/chat/output_parser.pyindex 69c71ed32c..b0bd71de64 100644--- a/libs/langchain/langchain/agents/chat/output_parser.py+++ b/libs/langchain/langchain/agents/chat/output_parser.py@@ -26,8 +26,7 @@ class ChatOutputParser(AgentOutputParser):return self.format_instructionsdef 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.@@ -39,7 +38,6 @@ class ChatOutputParser(AgentOutputParser):OutputParserException: If the output could not be parsed.ValueError: If the action could not be found."""-includes_answer = FINAL_ANSWER_ACTION in texttry:found = self.pattern.search(text)diff --git a/libs/langchain/langchain/agents/conversational/output_parser.py b/libs/langchain/langchain/agents/conversational/output_parser.pyindex 695c580849..a228ece64f 100644--- a/libs/langchain/langchain/agents/conversational/output_parser.py+++ b/libs/langchain/langchain/agents/conversational/output_parser.py@@ -22,8 +22,7 @@ class ConvoOutputParser(AgentOutputParser):return self.format_instructionsdef 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.@@ -31,7 +30,6 @@ class ConvoOutputParser(AgentOutputParser):Returns:An AgentAction or AgentFinish object."""-if f"{self.ai_prefix}:" in text:return AgentFinish({"output": text.split(f"{self.ai_prefix}:")[-1].strip()},diff --git a/libs/langchain/langchain/agents/format_scratchpad/openai_functions.py b/libs/langchain/langchain/agents/format_scratchpad/openai_functions.pyindex 7487ef29af..efd2884955 100644--- a/libs/langchain/langchain/agents/format_scratchpad/openai_functions.py+++ b/libs/langchain/langchain/agents/format_scratchpad/openai_functions.py@@ -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@@ -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.diff --git a/libs/langchain/langchain/agents/format_scratchpad/tools.py b/libs/langchain/langchain/agents/format_scratchpad/tools.pyindex 2f12e1f3e9..b42fe4533d 100644--- a/libs/langchain/langchain/agents/format_scratchpad/tools.py+++ b/libs/langchain/langchain/agents/format_scratchpad/tools.py@@ -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.diff --git a/libs/langchain/langchain/agents/json_chat/base.py b/libs/langchain/langchain/agents/json_chat/base.pyindex 29f929952c..ee15126697 100644--- a/libs/langchain/langchain/agents/json_chat/base.py+++ b/libs/langchain/langchain/agents/json_chat/base.py@@ -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.@@ -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 andprovide 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 anddescriptions 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 abouta 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 inanswering the users original question. The tools the human can use are:{tools}@@ -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 formattedin 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 jsonblob with a single action, and NOTHING else):{input}'''diff --git a/libs/langchain/langchain/agents/mrkl/output_parser.py b/libs/langchain/langchain/agents/mrkl/output_parser.pyindex 388e28f6f2..888bb66367 100644--- a/libs/langchain/langchain/agents/mrkl/output_parser.py+++ b/libs/langchain/langchain/agents/mrkl/output_parser.py@@ -30,8 +30,7 @@ class MRKLOutputParser(AgentOutputParser):return self.format_instructionsdef 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.diff --git a/libs/langchain/langchain/agents/openai_assistant/base.py b/libs/langchain/langchain/agents/openai_assistant/base.pyindex 83a0829818..2266ee6459 100644--- a/libs/langchain/langchain/agents/openai_assistant/base.py+++ b/libs/langchain/langchain/agents/openai_assistant/base.py@@ -302,6 +302,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):attachments: A list of files attached to the message, and thetools they should be added to.config: Runnable config. Defaults to None.+ **kwargs: Additional arguments.Return:If self.as_agent, will return@@ -309,7 +310,6 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):Otherwise, will return OpenAI typesUnion[List[ThreadMessage], List[RequiredActionFunctionToolCall]]."""-config = ensure_config(config)callback_manager = CallbackManager.configure(inheritable_callbacks=config.get("callbacks"),@@ -390,6 +390,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):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.@@ -442,7 +443,6 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):Otherwise, will return OpenAI typesUnion[List[ThreadMessage], List[RequiredActionFunctionToolCall]]."""-config = config or {}callback_manager = CallbackManager.configure(inheritable_callbacks=config.get("callbacks"),diff --git a/libs/langchain/langchain/agents/openai_functions_agent/base.py b/libs/langchain/langchain/agents/openai_functions_agent/base.pyindex 807be61e8c..2ef0060ff3 100644--- a/libs/langchain/langchain/agents/openai_functions_agent/base.py+++ b/libs/langchain/langchain/agents/openai_functions_agent/base.py@@ -92,7 +92,6 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent):@propertydef functions(self) -> list[dict]:"""Get functions."""-return [dict(convert_to_openai_function(t)) for t in self.tools]def plan(@@ -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:: pythondiff --git a/libs/langchain/langchain/agents/openai_tools/base.py b/libs/langchain/langchain/agents/openai_tools/base.pyindex 89ff92b733..942e2dfe35 100644--- a/libs/langchain/langchain/agents/openai_tools/base.py+++ b/libs/langchain/langchain/agents/openai_tools/base.py@@ -26,6 +26,7 @@ def create_openai_tools_agent(tools: Tools this agent has access to.prompt: The prompt to use. See Prompt section below for more on the expectedinput variables.+ strict: Whether strict mode should be used for OpenAI tools.Returns:A Runnable sequence representing an agent. It takes as input all the same inputdiff --git a/libs/langchain/langchain/agents/output_parsers/tools.py b/libs/langchain/langchain/agents/output_parsers/tools.pyindex b7ec8a47aa..81502ede6d 100644--- a/libs/langchain/langchain/agents/output_parsers/tools.py+++ b/libs/langchain/langchain/agents/output_parsers/tools.py@@ -16,7 +16,7 @@ from langchain.agents.agent import MultiActionAgentOutputParserclass ToolAgentAction(AgentActionMessageLog):- """ "Tool agent action."""+ """Tool agent action."""tool_call_id: str"""Tool call that this message is responding to."""diff --git a/libs/langchain/langchain/agents/react/agent.py b/libs/langchain/langchain/agents/react/agent.pyindex 59bda46d68..b4257bf1c1 100644--- a/libs/langchain/langchain/agents/react/agent.py+++ b/libs/langchain/langchain/agents/react/agent.py@@ -23,7 +23,7 @@ def create_react_agent(*,stop_sequence: Union[bool, list[str]] = True,) -> Runnable:- """Create an agent that uses ReAct prompting.+ r"""Create an agent that uses ReAct prompting.Based on paper "ReAct: Synergizing Reasoning and Acting in Language Models"(https://arxiv.org/abs/2210.03629)@@ -78,7 +78,7 @@ def create_react_agent("input": "what's my name?",# Notice that chat_history is a string# since this prompt is aimed at LLMs, not chat models- "chat_history": "Human: My name is Bob\\nAI: Hello Bob!",+ "chat_history": "Human: My name is Bob\nAI: Hello Bob!",})diff --git a/libs/langchain/langchain/agents/structured_chat/output_parser.py b/libs/langchain/langchain/agents/structured_chat/output_parser.pyindex 151e7f12e3..f240cbf062 100644--- a/libs/langchain/langchain/agents/structured_chat/output_parser.py+++ b/libs/langchain/langchain/agents/structured_chat/output_parser.py@@ -93,6 +93,7 @@ class StructuredChatOutputParserWithRetries(AgentOutputParser):Args:llm: The language model to use.base_parser: An optional StructuredChatOutputParser to use.+Returns:An instance of StructuredChatOutputParserWithRetries."""diff --git a/libs/langchain/langchain/agents/xml/base.py b/libs/langchain/langchain/agents/xml/base.pyindex 9ecf167bf3..4d03cd0e45 100644--- a/libs/langchain/langchain/agents/xml/base.py+++ b/libs/langchain/langchain/agents/xml/base.py@@ -121,7 +121,7 @@ def create_xml_agent(*,stop_sequence: Union[bool, list[str]] = True,) -> Runnable:- """Create an agent that uses XML to format its logic.+ r"""Create an agent that uses XML to format its logic.Args:llm: LLM to use as the agent.@@ -168,7 +168,7 @@ def create_xml_agent("input": "what's my name?",# Notice that chat_history is a string# since this prompt is aimed at LLMs, not chat models- "chat_history": "Human: My name is Bob\\nAI: Hello Bob!",+ "chat_history": "Human: My name is Bob\nAI: Hello Bob!",})diff --git a/libs/langchain/langchain/callbacks/streaming_aiter_final_only.py b/libs/langchain/langchain/callbacks/streaming_aiter_final_only.pyindex dbf125bd17..bfe8a45945 100644--- a/libs/langchain/langchain/callbacks/streaming_aiter_final_only.py+++ b/libs/langchain/langchain/callbacks/streaming_aiter_final_only.py@@ -12,6 +12,7 @@ DEFAULT_ANSWER_PREFIX_TOKENS = ["Final", "Answer", ":"]class AsyncFinalIteratorCallbackHandler(AsyncIteratorCallbackHandler):"""Callback handler that returns an async iterator.+Only the final output of the agent will be iterated."""diff --git a/libs/langchain/langchain/callbacks/streaming_stdout_final_only.py b/libs/langchain/langchain/callbacks/streaming_stdout_final_only.pyindex 17b1fd050f..a154dfcf59 100644--- a/libs/langchain/langchain/callbacks/streaming_stdout_final_only.py+++ b/libs/langchain/langchain/callbacks/streaming_stdout_final_only.py@@ -11,6 +11,7 @@ DEFAULT_ANSWER_PREFIX_TOKENS = ["Final", "Answer", ":"]class FinalStreamingStdOutCallbackHandler(StreamingStdOutCallbackHandler):"""Callback handler for streaming in agents.+Only works with agents using LLMs that support streaming.Only the final output of the agent will be streamed.@@ -77,7 +78,6 @@ class FinalStreamingStdOutCallbackHandler(StreamingStdOutCallbackHandler):@overridedef on_llm_new_token(self, token: str, **kwargs: Any) -> None:"""Run on new LLM token. Only available when streaming is enabled."""-# Remember the last n tokens, where n = len(answer_prefix_tokens)self.append_to_last_tokens(token)diff --git a/libs/langchain/langchain/callbacks/streamlit/__init__.py b/libs/langchain/langchain/callbacks/streamlit/__init__.pyindex 90319bb310..a36aaa2f9d 100644--- a/libs/langchain/langchain/callbacks/streamlit/__init__.py+++ b/libs/langchain/langchain/callbacks/streamlit/__init__.py@@ -42,7 +42,7 @@ def StreamlitCallbackHandler( # noqa: N802An optional custom LLMThoughtLabeler instance. If unspecified, the handlerwill use the default thought labeling logic. Defaults to None.- Returns+ Returns:-------A new StreamlitCallbackHandler instance.diff --git a/libs/langchain/langchain/callbacks/tracers/logging.py b/libs/langchain/langchain/callbacks/tracers/logging.pyindex 94e42c8049..13e4cb0459 100644--- a/libs/langchain/langchain/callbacks/tracers/logging.py+++ b/libs/langchain/langchain/callbacks/tracers/logging.py@@ -22,14 +22,13 @@ class LoggingCallbackHandler(FunctionCallbackHandler):extra: Optional[dict] = None,**kwargs: Any,) -> None:- """- Initialize the LoggingCallbackHandler.+ """Initialize the LoggingCallbackHandler.Args:logger: the logger to use for logginglog_level: the logging level (default: logging.INFO)extra: the extra context to log (default: None)- **kwargs:+ **kwargs: additional keyword arguments."""log_method = getattr(logger, logging.getLevelName(level=log_level).lower())diff --git a/libs/langchain/langchain/chains/base.py b/libs/langchain/langchain/chains/base.pyindex 06de4a737d..c4dd698996 100644--- a/libs/langchain/langchain/chains/base.py+++ b/libs/langchain/langchain/chains/base.py@@ -394,7 +394,8 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):tags: List of string tags to pass to all callbacks. These will be passed inaddition to tags passed to the chain during construction, but onlythese runtime tags will propagate to calls to other objects.- metadata: Optional metadata associated with the chain. Defaults to None+ metadata: Optional metadata associated with the chain. Defaults to None.+ run_name: Optional name for this run of the chain.include_run_info: Whether to include run info in the response. Defaultsto False.@@ -445,7 +446,8 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):tags: List of string tags to pass to all callbacks. These will be passed inaddition to tags passed to the chain during construction, but onlythese runtime tags will propagate to calls to other objects.- metadata: Optional metadata associated with the chain. Defaults to None+ metadata: Optional metadata associated with the chain. Defaults to None.+ run_name: Optional name for this run of the chain.include_run_info: Whether to include run info in the response. Defaultsto False.@@ -599,6 +601,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):tags: List of string tags to pass to all callbacks. These will be passed inaddition to tags passed to the chain during construction, but onlythese runtime tags will propagate to calls to other objects.+ metadata: Optional metadata associated with the chain.**kwargs: If the chain expects multiple inputs, they can be passed indirectly as keyword arguments.@@ -674,6 +677,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):tags: List of string tags to pass to all callbacks. These will be passed inaddition to tags passed to the chain during construction, but onlythese runtime tags will propagate to calls to other objects.+ metadata: Optional metadata associated with the chain.**kwargs: If the chain expects multiple inputs, they can be passed indirectly as keyword arguments.diff --git a/libs/langchain/langchain/chains/combine_documents/base.py b/libs/langchain/langchain/chains/combine_documents/base.pyindex 00ec94f064..99bfcdb9f3 100644--- a/libs/langchain/langchain/chains/combine_documents/base.py+++ b/libs/langchain/langchain/chains/combine_documents/base.py@@ -92,8 +92,9 @@ class BaseCombineDocumentsChain(Chain, ABC):context limit.Args:- docs: List[Document], a list of documents to use to calculate the- total prompt length.+ docs: a list of documents to use to calculate the total prompt length.+ **kwargs: additional parameters that may be needed to calculate the+ prompt length.Returns:Returns None if the method does not depend on the prompt length,diff --git a/libs/langchain/langchain/chains/combine_documents/map_rerank.py b/libs/langchain/langchain/chains/combine_documents/map_rerank.pyindex d0d5aba469..7f7a67fd17 100644--- a/libs/langchain/langchain/chains/combine_documents/map_rerank.py+++ b/libs/langchain/langchain/chains/combine_documents/map_rerank.py@@ -28,7 +28,7 @@ from langchain.output_parsers.regex import RegexParser),)class MapRerankDocumentsChain(BaseCombineDocumentsChain):- """Combining documents by mapping a chain over them, then reranking results.+ r"""Combining documents by mapping a chain over them, then reranking results.This algorithm calls an LLMChain on each input document. The LLMChain is expectedto have an OutputParser that parses the result into both an answer (``answer_key``)diff --git a/libs/langchain/langchain/chains/combine_documents/refine.py b/libs/langchain/langchain/chains/combine_documents/refine.pyindex 337ce2b6ef..4f0b9ce5ab 100644--- a/libs/langchain/langchain/chains/combine_documents/refine.py+++ b/libs/langchain/langchain/chains/combine_documents/refine.py@@ -183,8 +183,7 @@ class RefineDocumentsChain(BaseCombineDocumentsChain):callbacks: Callbacks = None,**kwargs: Any,) -> tuple[str, dict]:- """Async combine by mapping a first chain over all, then stuffing- into a final chain.+ """Combine by mapping a first chain over all, then stuffing into a final chain.Args:docs: List of documents to combinediff --git a/libs/langchain/langchain/chains/combine_documents/stuff.py b/libs/langchain/langchain/chains/combine_documents/stuff.pyindex 03e94c3a4b..7d9414e061 100644--- a/libs/langchain/langchain/chains/combine_documents/stuff.py+++ b/libs/langchain/langchain/chains/combine_documents/stuff.py@@ -31,7 +31,7 @@ def create_stuff_documents_chain(document_separator: str = DEFAULT_DOCUMENT_SEPARATOR,document_variable_name: str = DOCUMENTS_KEY,) -> Runnable[dict[str, Any], Any]:- """Create a chain for passing a list of Documents to a model.+ r"""Create a chain for passing a list of Documents to a model.Args:llm: Language model.@@ -64,7 +64,7 @@ def create_stuff_documents_chain(from langchain.chains.combine_documents import create_stuff_documents_chainprompt = ChatPromptTemplate.from_messages(- [("system", "What are everyone's favorite colors:\\n\\n{context}")]+ [("system", "What are everyone's favorite colors:\n\n{context}")])llm = ChatOpenAI(model="gpt-3.5-turbo")chain = create_stuff_documents_chain(llm, prompt)@@ -77,7 +77,6 @@ def create_stuff_documents_chain(chain.invoke({"context": docs})""" # noqa: E501-_validate_prompt(prompt, document_variable_name)_document_prompt = document_prompt or DEFAULT_DOCUMENT_PROMPT_output_parser = output_parser or StrOutputParser()@@ -234,8 +233,8 @@ class StuffDocumentsChain(BaseCombineDocumentsChain):context limit.Args:- docs: List[Document], a list of documents to use to calculate the- total prompt length.+ docs: a list of documents to use to calculate the total prompt length.+ **kwargs: additional parameters to use to get inputs to LLMChain.Returns:Returns None if the method does not depend on the prompt length,diff --git a/libs/langchain/langchain/chains/constitutional_ai/__init__.py b/libs/langchain/langchain/chains/constitutional_ai/__init__.pyindex 37198a1fbe..4041b11d17 100644--- a/libs/langchain/langchain/chains/constitutional_ai/__init__.py+++ b/libs/langchain/langchain/chains/constitutional_ai/__init__.py@@ -1,2 +1,5 @@-"""The Chain runs self-critique based on the Constitutional AI method proposed by \-(Bai et al., 2022)."""+"""Constitutional AI.++The Chain runs self-critique based on the Constitutional AI method proposed by+(Bai et al., 2022).+"""diff --git a/libs/langchain/langchain/chains/constitutional_ai/base.py b/libs/langchain/langchain/chains/constitutional_ai/base.pyindex e302087b61..99aab97c6d 100644--- a/libs/langchain/langchain/chains/constitutional_ai/base.py+++ b/libs/langchain/langchain/chains/constitutional_ai/base.py@@ -24,7 +24,7 @@ from langchain.chains.llm import LLMChainremoval="1.0",)class ConstitutionalChain(Chain):- """Chain for applying constitutional principles.+ r'''Chain for applying constitutional principles... note::This class is deprecated. See below for a replacement implementation using@@ -59,28 +59,28 @@ class ConstitutionalChain(Chain):llm = ChatOpenAI(model="gpt-4o-mini")class Critique(TypedDict):- \"\"\"Generate a critique, if needed.\"\"\"+ """Generate a critique, if needed."""critique_needed: Annotated[bool, ..., "Whether or not a critique is needed."]critique: Annotated[str, ..., "If needed, the critique."]critique_prompt = ChatPromptTemplate.from_template("Critique this response according to the critique request. "- "If no critique is needed, specify that.\\n\\n"- "Query: {query}\\n\\n"- "Response: {response}\\n\\n"+ "If no critique is needed, specify that.\n\n"+ "Query: {query}\n\n"+ "Response: {response}\n\n""Critique request: {critique_request}")revision_prompt = ChatPromptTemplate.from_template(- "Revise this response according to the critique and reivsion request.\\n\\n"- "Query: {query}\\n\\n"- "Response: {response}\\n\\n"- "Critique request: {critique_request}\\n\\n"- "Critique: {critique}\\n\\n"+ "Revise this response according to the critique and reivsion request.\n\n"+ "Query: {query}\n\n"+ "Response: {response}\n\n"+ "Critique request: {critique_request}\n\n"+ "Critique: {critique}\n\n""If the critique does not identify anything worth changing, ignore the ""revision request and return 'No revisions needed'. If the critique ""does identify something worth changing, revise the response based on "- "the revision request.\\n\\n"+ "the revision request.\n\n""Revision Request: {revision_request}")@@ -98,12 +98,12 @@ class ConstitutionalChain(Chain):async def generate_response(state: State):- \"\"\"Generate initial response.\"\"\"+ """Generate initial response."""response = await chain.ainvoke(state["query"])return {"response": response, "initial_response": response}async def critique_and_revise(state: State):- \"\"\"Critique and revise response according to principles.\"\"\"+ """Critique and revise response according to principles."""critiques_and_revisions = []response = state["initial_response"]for principle in state["constitutional_principles"]:@@ -189,7 +189,7 @@ class ConstitutionalChain(Chain):constitutional_chain.run(question="What is the meaning of life?")- """ # noqa: E501+ ''' # noqa: E501chain: LLMChainconstitutional_principles: list[ConstitutionalPrinciple]diff --git a/libs/langchain/langchain/chains/constitutional_ai/principles.py b/libs/langchain/langchain/chains/constitutional_ai/principles.pyindex 3e098786aa..f0243558be 100644--- a/libs/langchain/langchain/chains/constitutional_ai/principles.py+++ b/libs/langchain/langchain/chains/constitutional_ai/principles.py@@ -1,5 +1,7 @@-"""Constitutional principles from https://arxiv.org/pdf/2212.08073.pdf (Bai et al. 2022)-UnifiedObjectives v0.2 principles ("uo-*") adapted from https://examine.dev/docs/Unified_objectives.pdf (Samwald et al. 2023)+"""Constitutional principles.++Constitutional principles from https://arxiv.org/pdf/2212.08073.pdf (Bai et al. 2022)+UnifiedObjectives v0.2 principles ("uo-*") adapted from https://examine.dev/docs/Unified_objectives.pdf (Samwald et al. 2023)."""from langchain.chains.constitutional_ai.models import ConstitutionalPrinciplediff --git a/libs/langchain/langchain/chains/conversational_retrieval/base.py b/libs/langchain/langchain/chains/conversational_retrieval/base.pyindex b43f376937..06c7be0f76 100644--- a/libs/langchain/langchain/chains/conversational_retrieval/base.py+++ b/libs/langchain/langchain/chains/conversational_retrieval/base.py@@ -261,7 +261,7 @@ class BaseConversationalRetrievalChain(Chain):removal="1.0",)class ConversationalRetrievalChain(BaseConversationalRetrievalChain):- """Chain for having a conversation based on retrieved documents.+ r"""Chain for having a conversation based on retrieved documents.This class is deprecated. See below for an example implementation using`create_retrieval_chain`. Additional walkthroughs can be found atdiff --git a/libs/langchain/langchain/chains/flare/__init__.py b/libs/langchain/langchain/chains/flare/__init__.pyindex 10a700d8b9..2b9c352f5a 100644--- a/libs/langchain/langchain/chains/flare/__init__.py+++ b/libs/langchain/langchain/chains/flare/__init__.py@@ -1 +1 @@-"""Adapted from https://github.com/jzbjyb/FLARE"""+"""Adapted from https://github.com/jzbjyb/FLARE."""diff --git a/libs/langchain/langchain/chains/flare/base.py b/libs/langchain/langchain/chains/flare/base.pyindex 34a31b2a1e..207b58b664 100644--- a/libs/langchain/langchain/chains/flare/base.py+++ b/libs/langchain/langchain/chains/flare/base.py@@ -95,7 +95,9 @@ def _low_confidence_spans(class FlareChain(Chain):- """Chain that combines a retriever, a question generator,+ """Flare chain.++ Chain that combines a retriever, a question generator,and a response generator.See [Active Retrieval Augmented Generation](https://arxiv.org/abs/2305.06983) paper.diff --git a/libs/langchain/langchain/chains/llm_math/base.py b/libs/langchain/langchain/chains/llm_math/base.pyindex b5e0e19faa..12c0621b99 100644--- a/libs/langchain/langchain/chains/llm_math/base.py+++ b/libs/langchain/langchain/chains/llm_math/base.py@@ -70,7 +70,7 @@ class LLMMathChain(Chain):Expression should be a single line mathematical expressionthat solves the problem.- Examples:+ Examples:"37593 * 67" for "37593 times 67""37593**(1/5)" for "37593^(1/5)"\"\"\"diff --git a/libs/langchain/langchain/chains/loading.py b/libs/langchain/langchain/chains/loading.pyindex e6d6c359fa..5372b767db 100644--- a/libs/langchain/langchain/chains/loading.py+++ b/libs/langchain/langchain/chains/loading.py@@ -244,7 +244,7 @@ def _load_reduce_documents_chain(config: dict, **kwargs: Any) -> ReduceDocumentsdef _load_llm_bash_chain(config: dict, **kwargs: Any) -> Any:- """Load LLM Bash chain from config dict"""+ """Load LLM Bash chain from config dict."""msg = ("LLMBash Chain is not available through LangChain anymore. ""The relevant code can be found in langchain_experimental, "diff --git a/libs/langchain/langchain/chains/openai_functions/base.py b/libs/langchain/langchain/chains/openai_functions/base.pyindex d7bd76b3a9..93cff12f4e 100644--- a/libs/langchain/langchain/chains/openai_functions/base.py+++ b/libs/langchain/langchain/chains/openai_functions/base.py@@ -78,6 +78,7 @@ def create_openai_fn_chain(passed in and they are not pydantic.BaseModels, the chain output willinclude both the name of the function that was returned and the argumentsto pass to the function.+ **kwargs: Additional keyword arguments to pass to LLMChain.Returns:An LLMChain that will pass in the given functions to the model when run.@@ -171,6 +172,7 @@ def create_structured_output_chain(will be inferred from the function types. If pydantic.BaseModels are passedin, then the OutputParser will try to parse outputs using those. Otherwisemodel outputs will simply be parsed as JSON.+ **kwargs: Additional keyword arguments to pass to LLMChain.Returns:An LLMChain that will pass the given function to the model.diff --git a/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py b/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.pyindex f5a7704957..8e2f9aa7dc 100644--- a/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py+++ b/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py@@ -58,8 +58,11 @@ class FactWithEvidence(BaseModel):class QuestionAnswer(BaseModel):- """A question and its answer as a list of facts each one should have a source.- each sentence contains a body and a list of sources."""+ """A question and its answer as a list of facts.++ Each fact should have a source.+ Each sentence contains a body and a list of sources.+ """question: str = Field(..., description="Question that was asked")answer: list[FactWithEvidence] = Field(diff --git a/libs/langchain/langchain/chains/openai_functions/extraction.py b/libs/langchain/langchain/chains/openai_functions/extraction.pyindex ac5bdba41e..40ac610dcf 100644--- a/libs/langchain/langchain/chains/openai_functions/extraction.py+++ b/libs/langchain/langchain/chains/openai_functions/extraction.py@@ -92,6 +92,7 @@ def create_extraction_chain(schema: The schema of the entities to extract.llm: The language model to use.prompt: The prompt to use for extraction.+ tags: Optional list of tags to associate with the chain.verbose: Whether to run in verbose mode. In verbose mode, some intermediatelogs will be printed to the console. Defaults to the global `verbose` value,accessible via `langchain.globals.get_verbose()`.diff --git a/libs/langchain/langchain/chains/openai_functions/openapi.py b/libs/langchain/langchain/chains/openai_functions/openapi.pyindex 64b863af1c..7fab3b7aaf 100644--- a/libs/langchain/langchain/chains/openai_functions/openapi.py+++ b/libs/langchain/langchain/chains/openai_functions/openapi.py@@ -82,8 +82,10 @@ def _openapi_params_to_json_schema(params: list[Parameter], spec: OpenAPISpec) -def openapi_spec_to_openai_fn(spec: OpenAPISpec,) -> tuple[list[dict[str, Any]], Callable]:- """Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI- functions.+ """OpenAPI spec to OpenAI function JSON Schema.++ Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI+ functions.Args:spec: OpenAPI spec to convert.@@ -345,8 +347,13 @@ def get_openapi_chain(`ChatOpenAI(model="gpt-3.5-turbo-0613")`.prompt: Main prompt template to use.request_chain: Chain for taking the functions output and executing the request.+ params: Request parameters.+ headers: Request headers.+ verbose: Whether to run the chain in verbose mode.+ llm_chain_kwargs: LLM chain additional keyword arguments.+ **kwargs: Additional keyword arguments to pass to the chain.- """ # noqa: E501+ """ # noqa: E501,D301try:from langchain_community.utilities.openapi import OpenAPISpecexcept ImportError as e:diff --git a/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py b/libs/langchain/langchain/chains/openai_functions/qa_with_structure.pyindex b704eed49d..f0ee8a8e4b 100644--- a/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py+++ b/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py@@ -43,8 +43,10 @@ def create_qa_with_structure_chain(prompt: Optional[Union[PromptTemplate, ChatPromptTemplate]] = None,verbose: bool = False, # noqa: FBT001,FBT002) -> LLMChain:- """Create a question answering chain that returns an answer with sources- based on schema.+ """Create a question answering chain with structure.++ Create a question answering chain that returns an answer with sources+ based on schema.Args:llm: Language model to use for the chain.@@ -52,8 +54,10 @@ def create_qa_with_structure_chain(output_parser: Output parser to use. Should be one of `pydantic` or `base`.Default to `base`.prompt: Optional prompt to use for the chain.+ verbose: Whether to run the chain in verbose mode.Returns:+ The question answering chain."""if output_parser == "pydantic":diff --git a/libs/langchain/langchain/chains/openai_functions/tagging.py b/libs/langchain/langchain/chains/openai_functions/tagging.pyindex 721bcddbaf..ee19eadeb0 100644--- a/libs/langchain/langchain/chains/openai_functions/tagging.py+++ b/libs/langchain/langchain/chains/openai_functions/tagging.py@@ -51,38 +51,42 @@ def create_tagging_chain(prompt: Optional[ChatPromptTemplate] = None,**kwargs: Any,) -> Chain:- """Create a chain that extracts information from a passage- based on a schema.+ """Create tagging chain from schema.- This function is deprecated. Please use `with_structured_output` instead.- See example usage below:+ Create a chain that extracts information from a passage+ based on a schema.- .. code-block:: python+ This function is deprecated. Please use `with_structured_output` instead.+ See example usage below:- from typing_extensions import Annotated, TypedDict- from langchain_anthropic import ChatAnthropic+ .. code-block:: python- class Joke(TypedDict):- \"\"\"Tagged joke.\"\"\"+ from typing_extensions import Annotated, TypedDict+ from langchain_anthropic import ChatAnthropic- setup: Annotated[str, ..., "The setup of the joke"]- punchline: Annotated[str, ..., "The punchline of the joke"]+ class Joke(TypedDict):+ \"\"\"Tagged joke.\"\"\"- # Or any other chat model that supports tools.- # Please reference to to the documentation of structured_output- # to see an up to date list of which models support- # with_structured_output.- model = ChatAnthropic(model="claude-3-haiku-20240307", temperature=0)- structured_llm = model.with_structured_output(Joke)- structured_llm.invoke(- "Why did the cat cross the road? To get to the other "- "side... and then lay down in the middle of it!"- )+ setup: Annotated[str, ..., "The setup of the joke"]+ punchline: Annotated[str, ..., "The punchline of the joke"]++ # Or any other chat model that supports tools.+ # Please reference to to the documentation of structured_output+ # to see an up to date list of which models support+ # with_structured_output.+ model = ChatAnthropic(model="claude-3-haiku-20240307", temperature=0)+ structured_llm = model.with_structured_output(Joke)+ structured_llm.invoke(+ "Why did the cat cross the road? To get to the other "+ "side... and then lay down in the middle of it!"+ )Read more here: https://python.langchain.com/docs/how_to/structured_output/Args:schema: The schema of the entities to extract.llm: The language model to use.+ prompt: The prompt template to use for the chain.+ kwargs: Additional keyword arguments to pass to the chain.Returns:Chain (LLMChain) that can be used to extract information from a passage.@@ -122,36 +126,40 @@ def create_tagging_chain_pydantic(prompt: Optional[ChatPromptTemplate] = None,**kwargs: Any,) -> Chain:- """Create a chain that extracts information from a passage- based on a pydantic schema.-- This function is deprecated. Please use `with_structured_output` instead.- See example usage below:-- .. code-block:: python-- from pydantic import BaseModel, Field- from langchain_anthropic import ChatAnthropic-- class Joke(BaseModel):- setup: str = Field(description="The setup of the joke")- punchline: str = Field(description="The punchline to the joke")-- # Or any other chat model that supports tools.- # Please reference to to the documentation of structured_output- # to see an up to date list of which models support- # with_structured_output.- model = ChatAnthropic(model="claude-3-opus-20240229", temperature=0)- structured_llm = model.with_structured_output(Joke)- structured_llm.invoke(- "Why did the cat cross the road? To get to the other "- "side... and then lay down in the middle of it!"- )+ """Create tagging chain from pydantic schema.++ Create a chain that extracts information from a passage+ based on a pydantic schema.++ This function is deprecated. Please use `with_structured_output` instead.+ See example usage below:++ .. code-block:: python++ from pydantic import BaseModel, Field+ from langchain_anthropic import ChatAnthropic++ class Joke(BaseModel):+ setup: str = Field(description="The setup of the joke")+ punchline: str = Field(description="The punchline to the joke")++ # Or any other chat model that supports tools.+ # Please reference to to the documentation of structured_output+ # to see an up to date list of which models support+ # with_structured_output.+ model = ChatAnthropic(model="claude-3-opus-20240229", temperature=0)+ structured_llm = model.with_structured_output(Joke)+ structured_llm.invoke(+ "Why did the cat cross the road? To get to the other "+ "side... and then lay down in the middle of it!"+ )Read more here: https://python.langchain.com/docs/how_to/structured_output/Args:pydantic_schema: The pydantic schema of the entities to extract.llm: The language model to use.+ prompt: The prompt template to use for the chain.+ kwargs: Additional keyword arguments to pass to the chain.Returns:Chain (LLMChain) that can be used to extract information from a passage.diff --git a/libs/langchain/langchain/chains/openai_functions/utils.py b/libs/langchain/langchain/chains/openai_functions/utils.pyindex 086d5b36bd..2cd87a44c1 100644--- a/libs/langchain/langchain/chains/openai_functions/utils.py+++ b/libs/langchain/langchain/chains/openai_functions/utils.py@@ -2,9 +2,7 @@ from typing import Anydef _resolve_schema_references(schema: Any, definitions: dict[str, Any]) -> Any:- """- Resolve the $ref keys in a JSON schema object using the provided definitions.- """+ """Resolve the $ref keys in a JSON schema object using the provided definitions."""if isinstance(schema, list):for i, item in enumerate(schema):schema[i] = _resolve_schema_references(item, definitions)diff --git a/libs/langchain/langchain/chains/qa_generation/base.py b/libs/langchain/langchain/chains/qa_generation/base.pyindex e906702f43..3d5cd613c2 100644--- a/libs/langchain/langchain/chains/qa_generation/base.py+++ b/libs/langchain/langchain/chains/qa_generation/base.py@@ -85,8 +85,7 @@ class QAGenerationChain(Chain):prompt: Optional[BasePromptTemplate] = None,**kwargs: Any,) -> QAGenerationChain:- """- Create a QAGenerationChain from a language model.+ """Create a QAGenerationChain from a language model.Args:llm: a language modeldiff --git a/libs/langchain/langchain/chains/qa_with_sources/loading.py b/libs/langchain/langchain/chains/qa_with_sources/loading.pyindex 11a2462bdb..57a9329f34 100644--- a/libs/langchain/langchain/chains/qa_with_sources/loading.py+++ b/libs/langchain/langchain/chains/qa_with_sources/loading.py@@ -189,6 +189,7 @@ def load_qa_with_sources_chain("map_reduce", "refine" and "map_rerank".verbose: Whether chains should be run in verbose mode or not. Note that thisapplies to all chains that make up the final chain.+ **kwargs: Additional keyword arguments.Returns:A chain to use for question answering with sources.diff --git a/libs/langchain/langchain/chains/query_constructor/base.py b/libs/langchain/langchain/chains/query_constructor/base.pyindex b684953d83..bb6b059580 100644--- a/libs/langchain/langchain/chains/query_constructor/base.py+++ b/libs/langchain/langchain/chains/query_constructor/base.py@@ -76,12 +76,13 @@ class StructuredQueryOutputParser(BaseOutputParser[StructuredQuery]):allowed_attributes: Optional[Sequence[str]] = None,fix_invalid: bool = False, # noqa: FBT001,FBT002) -> StructuredQueryOutputParser:- """- Create a structured query output parser from components.+ """Create a structured query output parser from components.Args:allowed_comparators: allowed comparatorsallowed_operators: allowed operators+ allowed_attributes: allowed attributes+ fix_invalid: whether to fix invalid filter directivesReturns:a structured query output parserdiff --git a/libs/langchain/langchain/chains/query_constructor/parser.py b/libs/langchain/langchain/chains/query_constructor/parser.pyindex 495cd428e6..5a13b2f030 100644--- a/libs/langchain/langchain/chains/query_constructor/parser.py+++ b/libs/langchain/langchain/chains/query_constructor/parser.py@@ -89,6 +89,7 @@ class QueryTransformer(Transformer):"""Initialize the QueryTransformer.Args:+ *args: Positional arguments.allowed_comparators: Optional sequence of allowed comparators.allowed_operators: Optional sequence of allowed operators.allowed_attributes: Optional sequence of allowed attributes for comparators.@@ -109,8 +110,10 @@ class QueryTransformer(Transformer):Args:func_name: The name of the function.args: The arguments passed to the function.+Returns:FilterDirective: The filter directive.+Raises:ValueError: If the function is a comparator and the first arg is not in theallowed attributes.@@ -204,6 +207,7 @@ class QueryTransformer(Transformer):Args:item: The item to transform.+Raises:ValueError: If the item is not in ISO 8601 date format."""@@ -223,6 +227,7 @@ class QueryTransformer(Transformer):Args:item: The item to transform.+Raises:ValueError: If the item is not in ISO 8601 datetime format."""@@ -257,8 +262,9 @@ def get_parser("""Return a parser for the query language.Args:- allowed_comparators: Optional[Sequence[Comparator]]- allowed_operators: Optional[Sequence[Operator]]+ allowed_comparators: The allowed comparators.+ allowed_operators: The allowed operators.+ allowed_attributes: The allowed attributes.Returns:Lark parser for the query language.diff --git a/libs/langchain/langchain/chains/question_answering/chain.py b/libs/langchain/langchain/chains/question_answering/chain.pyindex e8a29f674d..779b8ff687 100644--- a/libs/langchain/langchain/chains/question_answering/chain.py+++ b/libs/langchain/langchain/chains/question_answering/chain.py@@ -255,6 +255,7 @@ def load_qa_chain(verbose: Whether chains should be run in verbose mode or not. Note that thisapplies to all chains that make up the final chain.callback_manager: Callback manager to use for the chain.+ **kwargs: Additional keyword arguments.Returns:A chain to use for question answering.diff --git a/libs/langchain/langchain/chains/router/multi_retrieval_qa.py b/libs/langchain/langchain/chains/router/multi_retrieval_qa.pyindex aa3bd23f9c..5c74463a63 100644--- a/libs/langchain/langchain/chains/router/multi_retrieval_qa.py+++ b/libs/langchain/langchain/chains/router/multi_retrieval_qa.py@@ -22,8 +22,11 @@ from langchain.chains.router.multi_retrieval_prompt import (class MultiRetrievalQAChain(MultiRouteChain):- """A multi-route chain that uses an LLM router chain to choose amongst retrieval- qa chains."""+ """Multi Retrieval QA Chain.++ A multi-route chain that uses an LLM router chain to choose amongst retrieval+ qa chains.+ """router_chain: LLMRouterChain"""Chain for deciding a destination chain and the input to it."""@@ -62,6 +65,7 @@ class MultiRetrievalQAChain(MultiRouteChain):default_chain_llm: Optional language model to use if no default chain andno default retriever are provided.**kwargs: Additional keyword arguments to pass to the chain.+Returns:An instance of the multi retrieval qa chain."""diff --git a/libs/langchain/langchain/chains/sql_database/query.py b/libs/langchain/langchain/chains/sql_database/query.pyindex e2bcf5f74a..157553cde3 100644--- a/libs/langchain/langchain/chains/sql_database/query.py+++ b/libs/langchain/langchain/chains/sql_database/query.py@@ -38,7 +38,7 @@ def create_sql_query_chain(*,get_col_comments: Optional[bool] = None,) -> Runnable[Union[SQLInput, SQLInputWithTables, dict[str, Any]], str]:- """Create a chain that generates SQL queries.+ r"""Create a chain that generates SQL queries.*Security Note*: This chain generates SQL queries for the given database.diff --git a/libs/langchain/langchain/chains/structured_output/base.py b/libs/langchain/langchain/chains/structured_output/base.pyindex 58e3d041cc..ceacf6bbd8 100644--- a/libs/langchain/langchain/chains/structured_output/base.py+++ b/libs/langchain/langchain/chains/structured_output/base.py@@ -527,7 +527,6 @@ def _create_openai_json_runnable(*,output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None,) -> Runnable:- """"""if isinstance(output_schema, type) and is_basemodel_subclass(output_schema):output_parser = output_parser or PydanticOutputParser(pydantic_object=output_schema,diff --git a/libs/langchain/langchain/chains/summarize/chain.py b/libs/langchain/langchain/chains/summarize/chain.pyindex 6a118f7ca2..145eb2e0ec 100644--- a/libs/langchain/langchain/chains/summarize/chain.py+++ b/libs/langchain/langchain/chains/summarize/chain.py@@ -156,6 +156,7 @@ def load_summarize_chain("map_reduce", and "refine".verbose: Whether chains should be run in verbose mode or not. Note that thisapplies to all chains that make up the final chain.+ **kwargs: Additional keyword arguments.Returns:A chain to use for summarizing.diff --git a/libs/langchain/langchain/embeddings/__init__.py b/libs/langchain/langchain/embeddings/__init__.pyindex d377dc181c..e048925b39 100644--- a/libs/langchain/langchain/embeddings/__init__.py+++ b/libs/langchain/langchain/embeddings/__init__.py@@ -1,4 +1,6 @@-"""**Embedding models** are wrappers around embedding models+"""**Embedding models**.++**Embedding models** are wrappers around embedding modelsfrom different APIs and services.Embedding models can be LLMs or not.diff --git a/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py b/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.pyindex 80c591925a..b8616a2b42 100644--- a/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py+++ b/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py@@ -236,11 +236,12 @@ The following is the expected answer. Use this to measure correctness:"""Create a TrajectoryEvalChain object from a language model chain.Args:- llm (BaseChatModel): The language model chain.- agent_tools (Optional[Sequence[BaseTool]]): A list of tools- available to the agent.- output_parser (Optional[TrajectoryOutputParser]): The output parser- used to parse the chain output into a score.+ llm: The language model chain.+ agent_tools: A list of tools available to the agent.+ output_parser : The output parser used to parse the chain output into a+ score.+ **kwargs: Additional keyword arguments.+Returns:TrajectoryEvalChain: The TrajectoryEvalChain object."""@@ -346,15 +347,18 @@ The following is the expected answer. Use this to measure correctness:"""Evaluate a trajectory.Args:- prediction (str): The final predicted response.- input (str): The input to the agent.- agent_trajectory (List[Tuple[AgentAction, str]]):- The intermediate steps forming the agent trajectory.- reference (Optional[str]): The reference answer.- callbacks (Callbacks): Callbacks to use for this chain run.+ prediction: The final predicted response.+ input: The input to the agent.+ agent_trajectory: The intermediate steps forming the agent trajectory.+ reference: The reference answer.+ callbacks: Callbacks to use for this chain run.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation result, which includes the score and optionally+ The evaluation result, which includes the score and optionallythe reasoning for reaching that."""inputs = {@@ -389,15 +393,18 @@ The following is the expected answer. Use this to measure correctness:"""Asynchronously evaluate a trajectory.Args:- prediction (str): The final predicted response.- input (str): The input to the agent.- agent_trajectory (List[Tuple[AgentAction, str]]):- The intermediate steps forming the agent trajectory.- reference (Optional[str]): The reference answer.- callbacks (Callbacks): Callbacks to use for this chain run.+ prediction: The final predicted response.+ input: The input to the agent.+ agent_trajectory: The intermediate steps forming the agent trajectory.+ reference: The reference answer.+ callbacks: Callbacks to use for this chain run.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation result, which includes the score and optionally+ The evaluation result, which includes the score and optionallythe reasoning for reaching that."""inputs = {diff --git a/libs/langchain/langchain/evaluation/comparison/__init__.py b/libs/langchain/langchain/evaluation/comparison/__init__.pyindex 2b2d5c47e2..f0b5522aa1 100644--- a/libs/langchain/langchain/evaluation/comparison/__init__.py+++ b/libs/langchain/langchain/evaluation/comparison/__init__.py@@ -1,4 +1,4 @@-"""Comparison evaluators.+r"""Comparison evaluators.This module contains evaluators for comparing the output of two models,be they LLMs, Chains, or otherwise. This can be used for scoring@@ -24,7 +24,7 @@ Example:# "comment": "Both responses accurately state"# " that the chemical formula for water is H2O."# " However, Response B provides additional information"- # . " by explaining what the formula means.\\n[[B]]"+ # . " by explaining what the formula means.\n[[B]]"# }"""diff --git a/libs/langchain/langchain/evaluation/comparison/eval_chain.py b/libs/langchain/langchain/evaluation/comparison/eval_chain.pyindex e430e48166..c14c9d8ebc 100644--- a/libs/langchain/langchain/evaluation/comparison/eval_chain.py+++ b/libs/langchain/langchain/evaluation/comparison/eval_chain.py@@ -55,11 +55,10 @@ def resolve_pairwise_criteria("""Resolve the criteria for the pairwise evaluator.Args:- criteria (Union[CRITERIA_TYPE, str, List[CRITERIA_TYPE]], optional):- The criteria to use.+ criteria: The criteria to use.Returns:- dict: The resolved criteria.+ The resolved criteria."""if criteria is None:@@ -155,7 +154,9 @@ class PairwiseStringResultOutputParser(BaseOutputParser[dict]):class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):- """A chain for comparing two outputs, such as the outputs+ r"""Pairwise String Evaluation Chain.++ A chain for comparing two outputs, such as the outputsof two models, prompts, or outputs of a single model on similar inputs.Attributes:@@ -180,7 +181,7 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):# "comment": "Both responses accurately state"# " that the chemical formula for water is H2O."# " However, Response B provides additional information"- # . " by explaining what the formula means.\\n[[B]]"+ # . " by explaining what the formula means.\n[[B]]"# }""" # noqa: E501@@ -245,12 +246,13 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):"""Initialize the PairwiseStringEvalChain from an LLM.Args:- llm (BaseChatModel): The LLM to use (GPT-4 recommended).- prompt (PromptTemplate, optional): The prompt to use.- **kwargs (Any): Additional keyword arguments.+ llm: The LLM to use (GPT-4 recommended).+ prompt: The prompt to use.+ criteria: The criteria to use.+ **kwargs: Additional keyword arguments.Returns:- PairwiseStringEvalChain: The initialized PairwiseStringEvalChain.+ The initialized PairwiseStringEvalChain.Raises:ValueError: If the input variables are not as expected.@@ -328,15 +330,18 @@ Performance may be significantly worse with other models.","""Evaluate whether output A is preferred to output B.Args:- prediction (str): The output string from the first model.- prediction_b (str): The output string from the second model.- input (str, optional): The input or task string.- callbacks (Callbacks, optional): The callbacks to use.- reference (str, optional): The reference string, if any.- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ prediction_b: The output string from the second model.+ input: The input or task string.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ reference: The reference string, if any.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:+ A dictionary containing:- reasoning: The reasoning for the preference.- value: The preference value, which is either 'A', 'B', or Nonefor no preference.@@ -371,15 +376,18 @@ Performance may be significantly worse with other models.","""Asynchronously evaluate whether output A is preferred to output B.Args:- prediction (str): The output string from the first model.- prediction_b (str): The output string from the second model.- input (str, optional): The input or task string.- callbacks (Callbacks, optional): The callbacks to use.- reference (str, optional): The reference string, if any.- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ prediction_b: The output string from the second model.+ input: The input or task string.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ reference: The reference string, if any.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:+ A dictionary containing:- reasoning: The reasoning for the preference.- value: The preference value, which is either 'A', 'B', or Nonefor no preference.@@ -399,9 +407,11 @@ Performance may be significantly worse with other models.",class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain):- """A chain for comparing two outputs, such as the outputs- of two models, prompts, or outputs of a single model on similar inputs,- with labeled preferences.+ """Labeled Pairwise String Evaluation Chain.++ A chain for comparing two outputs, such as the outputs+ of two models, prompts, or outputs of a single model on similar inputs,+ with labeled preferences.Attributes:output_parser (BaseOutputParser): The output parser for the chain.diff --git a/libs/langchain/langchain/evaluation/criteria/__init__.py b/libs/langchain/langchain/evaluation/criteria/__init__.pyindex e8ab983bab..f7f6f6b1d7 100644--- a/libs/langchain/langchain/evaluation/criteria/__init__.py+++ b/libs/langchain/langchain/evaluation/criteria/__init__.py@@ -9,7 +9,7 @@ ClassesCriteriaEvalChain : Evaluates the output of a language model orchain against specified criteria.-Examples+Examples:--------Using a predefined criterion:>>> from langchain_community.llms import OpenAIdiff --git a/libs/langchain/langchain/evaluation/criteria/eval_chain.py b/libs/langchain/langchain/evaluation/criteria/eval_chain.pyindex 943a342e87..97413300e4 100644--- a/libs/langchain/langchain/evaluation/criteria/eval_chain.py+++ b/libs/langchain/langchain/evaluation/criteria/eval_chain.py@@ -134,12 +134,12 @@ def resolve_criteria(- a single criterion name present in one of the default criteria- a single `ConstitutionalPrinciple` instance- Returns+ Returns:-------Dict[str, str]A dictionary mapping criterion names to descriptions.- Examples+ Examples:-------->>> criterion = "relevance">>> CriteriaEvalChain.resolve_criteria(criteria)@@ -168,7 +168,7 @@ def resolve_criteria(class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):- """LLM Chain for evaluating runs against criteria.+ r"""LLM Chain for evaluating runs against criteria.Parameters----------@@ -189,12 +189,12 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):**kwargs : AnyAdditional keyword arguments to pass to the `LLMChain` constructor.- Returns+ Returns:-------CriteriaEvalChainAn instance of the `CriteriaEvalChain` class.- Examples+ Examples:-------->>> from langchain_anthropic import ChatAnthropic>>> from langchain.evaluation.criteria import CriteriaEvalChain@@ -203,7 +203,7 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):>>> evaluator = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)>>> evaluator.evaluate_strings(prediction="Imagine an ice cream flavor for the color aquamarine", input="Tell me an idea"){- 'reasoning': 'Here is my step-by-step reasoning for the given criteria:\\n\\nThe criterion is: "Is the submission the most amazing ever?" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered the most amazing idea ever conceived. There are many possible amazing ideas and this one ice cream flavor suggestion may or may not rise to that level for every person. \\n\\nN',+ 'reasoning': 'Here is my step-by-step reasoning for the given criteria:\n\nThe criterion is: "Is the submission the most amazing ever?" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered the most amazing idea ever conceived. There are many possible amazing ideas and this one ice cream flavor suggestion may or may not rise to that level for every person. \n\nN','value': 'N','score': 0,}@@ -223,7 +223,7 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):... ){'score': 0,- 'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accurate, or factual according to the given criterion.\\n\\nN',+ 'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accurate, or factual according to the given criterion.\n\nN','value': 'N',}@@ -258,7 +258,7 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):def evaluation_name(self) -> str:"""Get the name of the evaluation.- Returns+ Returns:-------strThe name of the evaluation.@@ -303,12 +303,12 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):- a single criterion name present in one of the default criteria- a single `ConstitutionalPrinciple` instance- Returns+ Returns:-------Dict[str, str]A dictionary mapping criterion names to descriptions.- Examples+ Examples:-------->>> criterion = "relevance">>> CriteriaEvalChain.resolve_criteria(criteria)@@ -343,12 +343,12 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):Additional keyword arguments to pass to the `LLMChain`constructor.- Returns+ Returns:-------CriteriaEvalChainAn instance of the `CriteriaEvalChain` class.- Examples+ Examples:-------->>> from langchain_openai import OpenAI>>> from langchain.evaluation.criteria import LabeledCriteriaEvalChain@@ -420,36 +420,32 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):) -> dict:"""Evaluate a prediction against the criteria.- Parameters- ----------- prediction : str- The predicted text to evaluate.- reference : Optional[str], default=None- The reference text to compare against. This is required if- `requires_reference` is `True`.- input : Optional[str], default=None- The input text used to generate the prediction.- **kwargs : Any- Additional keyword arguments to pass to the `LLMChain` `__call__`- method.+ Args:+ prediction: The predicted text to evaluate.+ reference: The reference text to compare against. This is required if+ `requires_reference` is `True`.+ input: The input text used to generate the prediction.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments to pass to the `LLMChain` `__call__`+ method.- Returns- -------- dict+ Returns:The evaluation results.- Examples- --------- >>> from langchain_openai import OpenAI- >>> from langchain.evaluation.criteria import CriteriaEvalChain- >>> llm = OpenAI()- >>> criteria = "conciseness"- >>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)- >>> chain.evaluate_strings(- prediction="The answer is 42.",- reference="42",- input="What is the answer to life, the universe, and everything?",- )+ Examples:+ >>> from langchain_openai import OpenAI+ >>> from langchain.evaluation.criteria import CriteriaEvalChain+ >>> llm = OpenAI()+ >>> criteria = "conciseness"+ >>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)+ >>> chain.evaluate_strings(+ prediction="The answer is 42.",+ reference="42",+ input="What is the answer to life, the universe, and everything?",+ )"""input_ = self._get_eval_input(prediction, reference, input)result = self(@@ -476,36 +472,32 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):) -> dict:"""Asynchronously evaluate a prediction against the criteria.- Parameters- ----------- prediction : str- The predicted text to evaluate.- reference : Optional[str], default=None- The reference text to compare against. This is required if- `requires_reference` is `True`.- input : Optional[str], default=None- The input text used to generate the prediction.- **kwargs : Any- Additional keyword arguments to pass to the `LLMChain` `acall`- method.+ Args:+ prediction: The predicted text to evaluate.+ reference: The reference text to compare against. This is required if+ `requires_reference` is `True`.+ input: The input text used to generate the prediction.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments to pass to the `LLMChain` `__call__`+ method.- Returns- -------- dict+ Returns:The evaluation results.- Examples- --------- >>> from langchain_openai import OpenAI- >>> from langchain.evaluation.criteria import CriteriaEvalChain- >>> llm = OpenAI()- >>> criteria = "conciseness"- >>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)- >>> await chain.aevaluate_strings(- prediction="The answer is 42.",- reference="42",- input="What is the answer to life, the universe, and everything?",- )+ Examples:+ >>> from langchain_openai import OpenAI+ >>> from langchain.evaluation.criteria import CriteriaEvalChain+ >>> llm = OpenAI()+ >>> criteria = "conciseness"+ >>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)+ >>> await chain.aevaluate_strings(+ prediction="The answer is 42.",+ reference="42",+ input="What is the answer to life, the universe, and everything?",+ )"""input_ = self._get_eval_input(prediction, reference, input)result = await self.acall(@@ -573,12 +565,12 @@ class LabeledCriteriaEvalChain(CriteriaEvalChain):Additional keyword arguments to pass to the `LLMChain`constructor.- Returns+ Returns:-------LabeledCriteriaEvalChainAn instance of the `LabeledCriteriaEvalChain` class.- Examples+ Examples:-------->>> from langchain_openai import OpenAI>>> from langchain.evaluation.criteria import LabeledCriteriaEvalChaindiff --git a/libs/langchain/langchain/evaluation/embedding_distance/base.py b/libs/langchain/langchain/evaluation/embedding_distance/base.pyindex bf9e0a798a..49e19d3c7a 100644--- a/libs/langchain/langchain/evaluation/embedding_distance/base.py+++ b/libs/langchain/langchain/evaluation/embedding_distance/base.py@@ -49,6 +49,7 @@ def _check_numpy() -> bool:def _embedding_factory() -> Embeddings:"""Create an Embeddings object.+Returns:Embeddings: The created Embeddings object."""@@ -344,7 +345,9 @@ class _EmbeddingDistanceChainMixin(Chain):class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):- """Use embedding distances to score semantic difference between+ """Embedding distance evaluation chain.++ Use embedding distances to score semantic difference betweena prediction and reference.Examples:@@ -442,19 +445,20 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):include_run_info: bool = False,**kwargs: Any,) -> dict:- """Evaluate the embedding distance between a prediction and- reference.+ """Evaluate the embedding distance between a prediction and reference.Args:- prediction (str): The output string from the first model.- reference (str): The reference string (required)- callbacks (Callbacks, optional): The callbacks to use.- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ reference: The output string from the second model.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run information in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:- - score: The embedding distance between the two- predictions.+ A dictionary containing:+ - score: The embedding distance between the two predictions."""result = self(inputs={"prediction": prediction, "reference": reference},@@ -477,19 +481,20 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):include_run_info: bool = False,**kwargs: Any,) -> dict:- """Asynchronously evaluate the embedding distance between- a prediction and reference.+ """Evaluate the embedding distance between a prediction and reference.Args:- prediction (str): The output string from the first model.- reference (str): The output string from the second model.- callbacks (Callbacks, optional): The callbacks to use.- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ reference: The output string from the second model.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run information in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:- - score: The embedding distance between the two- predictions.+ A dictionary containing:+ - score: The embedding distance between the two predictions."""result = await self.acall(inputs={"prediction": prediction, "reference": reference},@@ -599,17 +604,17 @@ class PairwiseEmbeddingDistanceEvalChain("""Evaluate the embedding distance between two predictions.Args:- prediction (str): The output string from the first model.- prediction_b (str): The output string from the second model.- callbacks (Callbacks, optional): The callbacks to use.- tags (List[str], optional): Tags to apply to traces- metadata (Dict[str, Any], optional): metadata to apply to- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ prediction_b: The output string from the second model.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run information in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:- - score: The embedding distance between the two- predictions.+ A dictionary containing:+ - score: The embedding distance between the two predictions."""result = self(inputs={"prediction": prediction, "prediction_b": prediction_b},@@ -632,22 +637,20 @@ class PairwiseEmbeddingDistanceEvalChain(include_run_info: bool = False,**kwargs: Any,) -> dict:- """Asynchronously evaluate the embedding distance-- between two predictions.+ """Asynchronously evaluate the embedding distance between two predictions.Args:- prediction (str): The output string from the first model.- prediction_b (str): The output string from the second model.- callbacks (Callbacks, optional): The callbacks to use.- tags (List[str], optional): Tags to apply to traces- metadata (Dict[str, Any], optional): metadata to apply to traces- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ prediction_b: The output string from the second model.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run information in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:- - score: The embedding distance between the two- predictions.+ A dictionary containing:+ - score: The embedding distance between the two predictions."""result = await self.acall(inputs={"prediction": prediction, "prediction_b": prediction_b},diff --git a/libs/langchain/langchain/evaluation/exact_match/base.py b/libs/langchain/langchain/evaluation/exact_match/base.pyindex c7ae0dc120..9b0964690f 100644--- a/libs/langchain/langchain/evaluation/exact_match/base.py+++ b/libs/langchain/langchain/evaluation/exact_match/base.py@@ -9,7 +9,7 @@ from langchain.evaluation.schema import StringEvaluatorclass ExactMatchStringEvaluator(StringEvaluator):"""Compute an exact match between the prediction and the reference.- Examples+ Examples:---------->>> evaluator = ExactMatchChain()>>> evaluator.evaluate_strings(@@ -48,22 +48,17 @@ class ExactMatchStringEvaluator(StringEvaluator):@propertydef requires_input(self) -> bool:- """- This evaluator does not require input.- """+ """This evaluator does not require input."""return False@propertydef requires_reference(self) -> bool:- """- This evaluator requires a reference.- """+ """This evaluator requires a reference."""return True@propertydef input_keys(self) -> list[str]:- """- Get the input keys.+ """Get the input keys.Returns:List[str]: The input keys.@@ -72,8 +67,7 @@ class ExactMatchStringEvaluator(StringEvaluator):@propertydef evaluation_name(self) -> str:- """- Get the evaluation name.+ """Get the evaluation name.Returns:str: The evaluation name.@@ -88,15 +82,15 @@ class ExactMatchStringEvaluator(StringEvaluator):reference: str,**kwargs: Any,) -> dict:- """- Evaluate the exact match between the prediction and the reference.+ """Evaluate the exact match between the prediction and the reference.Args:- prediction (str): The prediction string.- reference (Optional[str], optional): The reference string.+ prediction: The prediction string.+ reference: The reference string.+ **kwargs: Additional keyword arguments (not used).Returns:- dict: The evaluation results containing the score.+ The evaluation results containing the score."""if self.ignore_case:prediction = prediction.lower()diff --git a/libs/langchain/langchain/evaluation/loading.py b/libs/langchain/langchain/evaluation/loading.pyindex 06f6304816..879fc564ab 100644--- a/libs/langchain/langchain/evaluation/loading.py+++ b/libs/langchain/langchain/evaluation/loading.py@@ -52,7 +52,7 @@ def load_dataset(uri: str) -> list[dict]:pip install datasets- Examples+ Examples:--------.. code-block:: python@@ -117,12 +117,12 @@ def load_evaluator(**kwargs : AnyAdditional keyword arguments to pass to the evaluator.- Returns+ Returns:-------ChainThe loaded evaluation chain.- Examples+ Examples:-------->>> from langchain.evaluation import load_evaluator, EvaluatorType>>> evaluator = load_evaluator(EvaluatorType.QA)@@ -189,12 +189,12 @@ def load_evaluators(**kwargs : AnyAdditional keyword arguments to pass to all evaluators.- Returns+ Returns:-------List[Chain]The loaded evaluators.- Examples+ Examples:-------->>> from langchain.evaluation import load_evaluators, EvaluatorType>>> evaluators = [EvaluatorType.QA, EvaluatorType.CRITERIA]diff --git a/libs/langchain/langchain/evaluation/parsing/base.py b/libs/langchain/langchain/evaluation/parsing/base.pyindex bcd73477b4..b39d1ea6f1 100644--- a/libs/langchain/langchain/evaluation/parsing/base.py+++ b/libs/langchain/langchain/evaluation/parsing/base.py@@ -58,16 +58,13 @@ class JsonValidityEvaluator(StringEvaluator):def _evaluate_strings(self,prediction: str,- input: Optional[str] = None,- reference: Optional[str] = None,**kwargs: Any,) -> dict:"""Evaluate the prediction string.Args:- prediction (str): The prediction string to evaluate.- input (str, optional): Not used in this evaluator. Defaults to None.- reference (str, optional): Not used in this evaluator. Defaults to None.+ prediction: The prediction string to evaluate.+ **kwargs: Additional keyword arguments (not used).Returns:dict: A dictionary containing the evaluation score. The score is 1 if@@ -84,8 +81,10 @@ class JsonValidityEvaluator(StringEvaluator):class JsonEqualityEvaluator(StringEvaluator):- """Evaluate whether the prediction is equal to the reference after- parsing both as JSON.+ """Json Equality Evaluator.++ Evaluate whether the prediction is equal to the reference after+ parsing both as JSON.This evaluator checks if the prediction, after parsing as JSON, is equalto the reference,@@ -151,19 +150,18 @@ class JsonEqualityEvaluator(StringEvaluator):def _evaluate_strings(self,prediction: str,- input: Optional[str] = None,reference: Optional[str] = None,**kwargs: Any,) -> dict:"""Evaluate the prediction string.Args:- prediction (str): The prediction string to evaluate.- input (str, optional): Not used in this evaluator.- reference (str): The reference string to compare against.+ prediction: The prediction string to evaluate.+ reference: The reference string to compare against.+ **kwargs: Additional keyword arguments (not used).Returns:- dict: A dictionary containing the evaluation score.+ A dictionary containing the evaluation score."""parsed = self._parse_json(prediction)label = self._parse_json(cast("str", reference))diff --git a/libs/langchain/langchain/evaluation/parsing/json_distance.py b/libs/langchain/langchain/evaluation/parsing/json_distance.pyindex 954f545a66..63648841e4 100644--- a/libs/langchain/langchain/evaluation/parsing/json_distance.py+++ b/libs/langchain/langchain/evaluation/parsing/json_distance.py@@ -8,8 +8,7 @@ from langchain.evaluation.schema import StringEvaluatorclass JsonEditDistanceEvaluator(StringEvaluator):- """- An evaluator that calculates the edit distance between JSON strings.+ """An evaluator that calculates the edit distance between JSON strings.This evaluator computes a normalized Damerau-Levenshtein distance between two JSON stringsafter parsing them and converting them to a canonical format (i.e., whitespace and key order are normalized).@@ -98,7 +97,6 @@ class JsonEditDistanceEvaluator(StringEvaluator):def _evaluate_strings(self,prediction: str,- input: Optional[str] = None,reference: Optional[str] = None,**kwargs: Any,) -> dict:diff --git a/libs/langchain/langchain/evaluation/qa/eval_chain.py b/libs/langchain/langchain/evaluation/qa/eval_chain.pyindex 0ad0eddc40..67ec69950a 100644--- a/libs/langchain/langchain/evaluation/qa/eval_chain.py+++ b/libs/langchain/langchain/evaluation/qa/eval_chain.py@@ -181,6 +181,7 @@ class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):include_run_info (bool, optional): whether to include run info in thereturned results.**kwargs: additional keyword arguments, including callbacks, tags, etc.+Returns:dict: The evaluation results containing the score or value."""@@ -215,7 +216,7 @@ class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):- """LLM Chain for evaluating QA w/o GT based on context"""+ """LLM Chain for evaluating QA w/o GT based on context."""@classmethod@overridediff --git a/libs/langchain/langchain/evaluation/regex_match/base.py b/libs/langchain/langchain/evaluation/regex_match/base.pyindex 6ad35f192b..08baabadd9 100644--- a/libs/langchain/langchain/evaluation/regex_match/base.py+++ b/libs/langchain/langchain/evaluation/regex_match/base.py@@ -9,7 +9,7 @@ from langchain.evaluation.schema import StringEvaluatorclass RegexMatchStringEvaluator(StringEvaluator):"""Compute a regex match between the prediction and the reference.- Examples+ Examples:---------->>> evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE)>>> evaluator.evaluate_strings(@@ -40,22 +40,17 @@ class RegexMatchStringEvaluator(StringEvaluator):@propertydef requires_input(self) -> bool:- """- This evaluator does not require input.- """+ """This evaluator does not require input."""return False@propertydef requires_reference(self) -> bool:- """- This evaluator requires a reference.- """+ """This evaluator requires a reference."""return True@propertydef input_keys(self) -> list[str]:- """- Get the input keys.+ """Get the input keys.Returns:List[str]: The input keys.@@ -64,8 +59,7 @@ class RegexMatchStringEvaluator(StringEvaluator):@propertydef evaluation_name(self) -> str:- """- Get the evaluation name.+ """Get the evaluation name.Returns:str: The evaluation name.@@ -80,15 +74,15 @@ class RegexMatchStringEvaluator(StringEvaluator):reference: str,**kwargs: Any,) -> dict:- """- Evaluate the regex match between the prediction and the reference.+ """Evaluate the regex match between the prediction and the reference.Args:- prediction (str): The prediction string.- reference (Optional[str], optional): The reference regex pattern.+ prediction: The prediction string.+ reference: The reference regex pattern.+ **kwargs: Additional keyword arguments (not used).Returns:- dict: The evaluation results containing the score.+ The evaluation results containing the score."""match = re.match(reference, prediction, flags=self.flags)return {"score": int(bool(match))}diff --git a/libs/langchain/langchain/evaluation/schema.py b/libs/langchain/langchain/evaluation/schema.pyindex 588d6c4634..299710cc22 100644--- a/libs/langchain/langchain/evaluation/schema.py+++ b/libs/langchain/langchain/evaluation/schema.py@@ -116,6 +116,7 @@ class _EvalArgsMixin:Args:reference (Optional[str], optional): The reference label.input_ (Optional[str], optional): The input string.+Raises:ValueError: If the evaluator requires an input string but none is provided,or if the evaluator requires a reference label but none is provided.@@ -133,8 +134,11 @@ class _EvalArgsMixin:class StringEvaluator(_EvalArgsMixin, ABC):- """Grade, tag, or otherwise evaluate predictions relative to their inputs- and/or reference labels."""+ """String evaluator interface.++ Grade, tag, or otherwise evaluate predictions relative to their inputs+ and/or reference labels.+ """@propertydef evaluation_name(self) -> str:@@ -162,6 +166,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The reference label to evaluate against.input (Optional[str], optional): The input to consider during evaluation.kwargs: Additional keyword arguments, including callbacks, tags, etc.+Returns:dict: The evaluation results containing the score or value.It is recommended that the dictionary contain the following keys:@@ -185,6 +190,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The reference label to evaluate against.input (Optional[str], optional): The input to consider during evaluation.kwargs: Additional keyword arguments, including callbacks, tags, etc.+Returns:dict: The evaluation results containing the score or value.It is recommended that the dictionary contain the following keys:@@ -216,6 +222,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The reference label to evaluate against.input (Optional[str], optional): The input to consider during evaluation.kwargs: Additional keyword arguments, including callbacks, tags, etc.+Returns:dict: The evaluation results containing the score or value.""" # noqa: E501@@ -242,6 +249,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The reference label to evaluate against.input (Optional[str], optional): The input to consider during evaluation.kwargs: Additional keyword arguments, including callbacks, tags, etc.+Returns:dict: The evaluation results containing the score or value.""" # noqa: E501@@ -275,6 +283,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The expected output / reference string.input (Optional[str], optional): The input string.kwargs: Additional keyword arguments, such as callbacks and optional reference strings.+Returns:dict: A dictionary containing the preference, scores, and/or other information.""" # noqa: E501@@ -296,6 +305,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The expected output / reference string.input (Optional[str], optional): The input string.kwargs: Additional keyword arguments, such as callbacks and optional reference strings.+Returns:dict: A dictionary containing the preference, scores, and/or other information.""" # noqa: E501@@ -326,6 +336,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The expected output / reference string.input (Optional[str], optional): The input string.kwargs: Additional keyword arguments, such as callbacks and optional reference strings.+Returns:dict: A dictionary containing the preference, scores, and/or other information.""" # noqa: E501@@ -355,6 +366,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):reference (Optional[str], optional): The expected output / reference string.input (Optional[str], optional): The input string.kwargs: Additional keyword arguments, such as callbacks and optional reference strings.+Returns:dict: A dictionary containing the preference, scores, and/or other information.""" # noqa: E501@@ -389,14 +401,15 @@ class AgentTrajectoryEvaluator(_EvalArgsMixin, ABC):"""Evaluate a trajectory.Args:- prediction (str): The final predicted response.- agent_trajectory (List[Tuple[AgentAction, str]]):+ prediction: The final predicted response.+ agent_trajectory:The intermediate steps forming the agent trajectory.- input (str): The input to the agent.- reference (Optional[str]): The reference answer.+ input: The input to the agent.+ reference: The reference answer.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation result.+ The evaluation result."""async def _aevaluate_agent_trajectory(@@ -411,14 +424,15 @@ class AgentTrajectoryEvaluator(_EvalArgsMixin, ABC):"""Asynchronously evaluate a trajectory.Args:- prediction (str): The final predicted response.- agent_trajectory (List[Tuple[AgentAction, str]]):+ prediction: The final predicted response.+ agent_trajectory:The intermediate steps forming the agent trajectory.- input (str): The input to the agent.- reference (Optional[str]): The reference answer.+ input: The input to the agent.+ reference: The reference answer.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation result.+ The evaluation result."""return await run_in_executor(None,@@ -442,14 +456,15 @@ class AgentTrajectoryEvaluator(_EvalArgsMixin, ABC):"""Evaluate a trajectory.Args:- prediction (str): The final predicted response.- agent_trajectory (List[Tuple[AgentAction, str]]):+ prediction: The final predicted response.+ agent_trajectory:The intermediate steps forming the agent trajectory.- input (str): The input to the agent.- reference (Optional[str]): The reference answer.+ input: The input to the agent.+ reference: The reference answer.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation result.+ The evaluation result."""self._check_evaluation_args(reference=reference, input_=input)return self._evaluate_agent_trajectory(@@ -472,14 +487,15 @@ class AgentTrajectoryEvaluator(_EvalArgsMixin, ABC):"""Asynchronously evaluate a trajectory.Args:- prediction (str): The final predicted response.- agent_trajectory (List[Tuple[AgentAction, str]]):+ prediction: The final predicted response.+ agent_trajectory:The intermediate steps forming the agent trajectory.- input (str): The input to the agent.- reference (Optional[str]): The reference answer.+ input: The input to the agent.+ reference: The reference answer.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation result.+ The evaluation result."""self._check_evaluation_args(reference=reference, input_=input)return await self._aevaluate_agent_trajectory(diff --git a/libs/langchain/langchain/evaluation/scoring/eval_chain.py b/libs/langchain/langchain/evaluation/scoring/eval_chain.pyindex 1ab9b2102a..6dbf3ea3b0 100644--- a/libs/langchain/langchain/evaluation/scoring/eval_chain.py+++ b/libs/langchain/langchain/evaluation/scoring/eval_chain.py@@ -215,7 +215,7 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):def evaluation_name(self) -> str:"""Get the name of the evaluation.- Returns+ Returns:-------strThe name of the evaluation.@@ -249,12 +249,14 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):"""Initialize the ScoreStringEvalChain from an LLM.Args:- llm (BaseChatModel): The LLM to use (GPT-4 recommended).- prompt (PromptTemplate, optional): The prompt to use.- **kwargs (Any): Additional keyword arguments.+ llm: The LLM to use (GPT-4 recommended).+ prompt: The prompt to use.+ criteria: The criteria to use.+ normalize_by: The value to normalize the score by.+ **kwargs: Additional keyword arguments.Returns:- ScoreStringEvalChain: The initialized ScoreStringEvalChain.+ The initialized ScoreStringEvalChain.Raises:ValueError: If the input variables are not as expected.@@ -342,14 +344,17 @@ Performance may be significantly worse with other models.","""Score the output string.Args:- prediction (str): The output string from the first model.- input (str, optional): The input or task string.- callbacks (Callbacks, optional): The callbacks to use.- reference (str, optional): The reference string, if any.- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ input: The input or task string.+ callbacks: The callbacks to use.+ tags: Optional tags to use.+ metadata: Optional metadata to use.+ include_run_info: Whether to include run information in the output.+ reference: The reference string, if any.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:+ A dictionary containing:- reasoning: The reasoning for the preference.- score: A score between 1 and 10.@@ -380,14 +385,17 @@ Performance may be significantly worse with other models.","""Asynchronously score the output string.Args:- prediction (str): The output string from the first model.- input (str, optional): The input or task string.- callbacks (Callbacks, optional): The callbacks to use.- reference (str, optional): The reference string, if any.- **kwargs (Any): Additional keyword arguments.+ prediction: The output string from the first model.+ input: The input or task string.+ callbacks: The callbacks to use.+ tags: Optional tags to use.+ metadata: Optional metadata to use.+ include_run_info: Whether to include run information in the output.+ reference: The reference string, if any.+ **kwargs: Additional keyword arguments.Returns:- dict: A dictionary containing:+ A dictionary containing:- reasoning: The reasoning for the preference.- score: A score between 1 and 10.diff --git a/libs/langchain/langchain/evaluation/string_distance/base.py b/libs/langchain/langchain/evaluation/string_distance/base.pyindex 6a62452b9f..db397df7b0 100644--- a/libs/langchain/langchain/evaluation/string_distance/base.py+++ b/libs/langchain/langchain/evaluation/string_distance/base.py@@ -18,8 +18,7 @@ from langchain.schema import RUN_KEYdef _load_rapidfuzz() -> Any:- """- Load the RapidFuzz library.+ """Load the RapidFuzz library.Raises:ImportError: If the rapidfuzz library is not installed.@@ -68,8 +67,7 @@ class _RapidFuzzChainMixin(Chain):@pre_initdef validate_dependencies(cls, values: dict[str, Any]) -> dict[str, Any]:- """- Validate that the rapidfuzz library is installed.+ """Validate that the rapidfuzz library is installed.Args:values (Dict[str, Any]): The input values.@@ -82,8 +80,7 @@ class _RapidFuzzChainMixin(Chain):@propertydef output_keys(self) -> list[str]:- """- Get the output keys.+ """Get the output keys.Returns:List[str]: The output keys.@@ -91,8 +88,7 @@ class _RapidFuzzChainMixin(Chain):return ["score"]def _prepare_output(self, result: dict[str, Any]) -> dict[str, Any]:- """- Prepare the output dictionary.+ """Prepare the output dictionary.Args:result (Dict[str, Any]): The evaluation results.@@ -107,11 +103,11 @@ class _RapidFuzzChainMixin(Chain):@staticmethoddef _get_metric(distance: str, *, normalize_score: bool = False) -> Callable:- """- Get the distance metric function based on the distance type.+ """Get the distance metric function based on the distance type.Args:- distance (str): The distance type.+ distance: The distance type.+ normalize_score: Whether to normalize the score.Returns:Callable: The distance metric function.@@ -142,8 +138,7 @@ class _RapidFuzzChainMixin(Chain):@propertydef metric(self) -> Callable:- """- Get the distance metric function.+ """Get the distance metric function.Returns:Callable: The distance metric function.@@ -154,8 +149,7 @@ class _RapidFuzzChainMixin(Chain):)def compute_metric(self, a: str, b: str) -> float:- """- Compute the distance between two strings.+ """Compute the distance between two strings.Args:a (str): The first string.@@ -170,9 +164,8 @@ class _RapidFuzzChainMixin(Chain):class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):"""Compute string distances between the prediction and the reference.- Examples+ Examples:----------->>> from langchain.evaluation import StringDistanceEvalChain>>> evaluator = StringDistanceEvalChain()>>> evaluator.evaluate_strings(@@ -192,22 +185,17 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):@propertydef requires_input(self) -> bool:- """- This evaluator does not require input.- """+ """This evaluator does not require input."""return False@propertydef requires_reference(self) -> bool:- """- This evaluator does not require a reference.- """+ """This evaluator does not require a reference."""return True@propertydef input_keys(self) -> list[str]:- """- Get the input keys.+ """Get the input keys.Returns:List[str]: The input keys.@@ -216,8 +204,7 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):@propertydef evaluation_name(self) -> str:- """- Get the evaluation name.+ """Get the evaluation name.Returns:str: The evaluation name.@@ -230,8 +217,7 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):inputs: dict[str, Any],run_manager: Optional[CallbackManagerForChainRun] = None,) -> dict[str, Any]:- """- Compute the string distance between the prediction and the reference.+ """Compute the string distance between the prediction and the reference.Args:inputs (Dict[str, Any]): The input values.@@ -249,13 +235,11 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):inputs: dict[str, Any],run_manager: Optional[AsyncCallbackManagerForChainRun] = None,) -> dict[str, Any]:- """- Asynchronously compute the string distance between the prediction- and the reference.+ """Compute the string distance between the prediction and the reference.Args:inputs (Dict[str, Any]): The input values.- run_manager (Optional[AsyncCallbackManagerForChainRun]:+ run_manager (Optional[CallbackManagerForChainRun]):The callback manager.Returns:@@ -276,18 +260,20 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):include_run_info: bool = False,**kwargs: Any,) -> dict:- """- Evaluate the string distance between the prediction and the reference.+ """Evaluate the string distance between the prediction and the reference.Args:- prediction (str): The prediction string.- reference (Optional[str], optional): The reference string.- input (Optional[str], optional): The input string.- callbacks (Callbacks, optional): The callbacks to use.- kwargs: Additional keyword arguments.+ prediction: The prediction string.+ reference: The reference string.+ input: The input string.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation results containing the score.+ The evaluation results containing the score."""result = self(inputs={"prediction": prediction, "reference": reference},@@ -312,19 +298,20 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):include_run_info: bool = False,**kwargs: Any,) -> dict:- """- Asynchronously evaluate the string distance between the- prediction and the reference.+ """Evaluate the string distance between the prediction and the reference.Args:- prediction (str): The prediction string.- reference (Optional[str], optional): The reference string.- input (Optional[str], optional): The input string.- callbacks (Callbacks, optional): The callbacks to use.- kwargs: Additional keyword arguments.+ prediction: The prediction string.+ reference: The reference string.+ input: The input string.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to apply.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation results containing the score.+ The evaluation results containing the score."""result = await self.acall(inputs={"prediction": prediction, "reference": reference},@@ -341,8 +328,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi@propertydef input_keys(self) -> list[str]:- """- Get the input keys.+ """Get the input keys.Returns:List[str]: The input keys.@@ -351,8 +337,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi@propertydef evaluation_name(self) -> str:- """- Get the evaluation name.+ """Get the evaluation name.Returns:str: The evaluation name.@@ -365,8 +350,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMiinputs: dict[str, Any],run_manager: Optional[CallbackManagerForChainRun] = None,) -> dict[str, Any]:- """- Compute the string distance between two predictions.+ """Compute the string distance between two predictions.Args:inputs (Dict[str, Any]): The input values.@@ -386,8 +370,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMiinputs: dict[str, Any],run_manager: Optional[AsyncCallbackManagerForChainRun] = None,) -> dict[str, Any]:- """- Asynchronously compute the string distance between two predictions.+ """Asynchronously compute the string distance between two predictions.Args:inputs (Dict[str, Any]): The input values.@@ -413,19 +396,19 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMiinclude_run_info: bool = False,**kwargs: Any,) -> dict:- """- Evaluate the string distance between two predictions.+ """Evaluate the string distance between two predictions.Args:- prediction (str): The first prediction string.- prediction_b (str): The second prediction string.- callbacks (Callbacks, optional): The callbacks to use.- tags (List[str], optional): Tags to apply to traces.- metadata (Dict[str, Any], optional): Metadata to apply to traces.- kwargs: Additional keyword arguments.+ prediction: The first prediction string.+ prediction_b: The second prediction string.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation results containing the score.+ The evaluation results containing the score."""result = self(inputs={"prediction": prediction, "prediction_b": prediction_b},@@ -448,19 +431,19 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMiinclude_run_info: bool = False,**kwargs: Any,) -> dict:- """- Asynchronously evaluate the string distance between two predictions.+ """Asynchronously evaluate the string distance between two predictions.Args:- prediction (str): The first prediction string.- prediction_b (str): The second prediction string.- callbacks (Callbacks, optional): The callbacks to use.- tags (List[str], optional): Tags to apply to traces.- metadata (Dict[str, Any], optional): Metadata to apply to traces.- kwargs: Additional keyword arguments.+ prediction: The first prediction string.+ prediction_b: The second prediction string.+ callbacks: The callbacks to use.+ tags: The tags to apply.+ metadata: The metadata to use.+ include_run_info: Whether to include run info in the output.+ **kwargs: Additional keyword arguments.Returns:- dict: The evaluation results containing the score.+ The evaluation results containing the score."""result = await self.acall(inputs={"prediction": prediction, "prediction_b": prediction_b},diff --git a/libs/langchain/langchain/hub.py b/libs/langchain/langchain/hub.pyindex 20c40e78bb..eacc61c2dc 100644--- a/libs/langchain/langchain/hub.py+++ b/libs/langchain/langchain/hub.py@@ -49,8 +49,7 @@ def push(readme: Optional[str] = None,tags: Optional[Sequence[str]] = None,) -> str:- """- Push an object to the hub and returns the URL it can be viewed at in a browser.+ """Push an object to the hub and returns the URL it can be viewed at in a browser.:param repo_full_name: The full name of the prompt to push to in the format of`owner/prompt_name` or `prompt_name`.@@ -97,8 +96,7 @@ def pull(api_url: Optional[str] = None,api_key: Optional[str] = None,) -> Any:- """- Pull an object from the hub and returns it as a LangChain object.+ """Pull an object from the hub and returns it as a LangChain object.:param owner_repo_commit: The full name of the prompt to pull from in the format of`owner/prompt_name:commit_hash` or `owner/prompt_name`diff --git a/libs/langchain/langchain/indexes/__init__.py b/libs/langchain/langchain/indexes/__init__.pyindex c4e282cfdf..bae8b86ad2 100644--- a/libs/langchain/langchain/indexes/__init__.py+++ b/libs/langchain/langchain/indexes/__init__.py@@ -1,4 +1,6 @@-"""**Index** is used to avoid writing duplicated content+"""**Indexes**.++**Index** is used to avoid writing duplicated contentinto the vectostore and to avoid over-writing content if it's unchanged.Indexes also :diff --git a/libs/langchain/langchain/indexes/_sql_record_manager.py b/libs/langchain/langchain/indexes/_sql_record_manager.pyindex 9c83318314..707bb7d54e 100644--- a/libs/langchain/langchain/indexes/_sql_record_manager.py+++ b/libs/langchain/langchain/indexes/_sql_record_manager.py@@ -159,7 +159,6 @@ class SQLRecordManager(RecordManager):async def acreate_schema(self) -> None:"""Create the database schema."""-if not isinstance(self.engine, AsyncEngine):msg = "This method is not supported for sync engines."raise AssertionError(msg) # noqa: TRY004@@ -170,7 +169,6 @@ class SQLRecordManager(RecordManager):@contextlib.contextmanagerdef _make_session(self) -> Generator[Session, None, None]:"""Create a session and close it after use."""-if isinstance(self.session_factory, async_sessionmaker):msg = "This method is not supported for async engines."raise AssertionError(msg) # noqa: TRY004@@ -184,7 +182,6 @@ class SQLRecordManager(RecordManager):@contextlib.asynccontextmanagerasync def _amake_session(self) -> AsyncGenerator[AsyncSession, None]:"""Create a session and close it after use."""-if not isinstance(self.session_factory, async_sessionmaker):msg = "This method is not supported for sync engines."raise AssertionError(msg) # noqa: TRY004diff --git a/libs/langchain/langchain/llms/__init__.py b/libs/langchain/langchain/llms/__init__.pyindex 6449590fed..9685b1ae5d 100644--- a/libs/langchain/langchain/llms/__init__.py+++ b/libs/langchain/langchain/llms/__init__.py@@ -1,6 +1,6 @@-"""-**LLM** classes provide-access to the large language model (**LLM**) APIs and services.+"""**LLMs**.++**LLM** classes provide access to the large language model (**LLM**) APIs and services.**Class hierarchy:**diff --git a/libs/langchain/langchain/llms/base.py b/libs/langchain/langchain/llms/base.pyindex 1b34e359f5..5246811f41 100644--- a/libs/langchain/langchain/llms/base.py+++ b/libs/langchain/langchain/llms/base.py@@ -1,5 +1,4 @@-"""-This module provides backward-compatible exports of core language model classes.+"""This module provides backward-compatible exports of core language model classes.These classes are re-exported for compatibility with older versions of LangChainand allow users to import language model interfaces from a stable path.diff --git a/libs/langchain/langchain/memory/buffer.py b/libs/langchain/langchain/memory/buffer.pyindex 57020000e8..70e00441a4 100644--- a/libs/langchain/langchain/memory/buffer.py+++ b/libs/langchain/langchain/memory/buffer.py@@ -131,6 +131,7 @@ class ConversationStringBufferMemory(BaseMemory):@propertydef memory_variables(self) -> list[str]:"""Will always return list of memory variables.+:meta private:"""return [self.memory_key]diff --git a/libs/langchain/langchain/memory/entity.py b/libs/langchain/langchain/memory/entity.pyindex 726abed4f8..9e9a6bf3d6 100644--- a/libs/langchain/langchain/memory/entity.py+++ b/libs/langchain/langchain/memory/entity.py@@ -128,6 +128,8 @@ class UpstashRedisEntityStore(BaseEntityStore):key_prefix: Prefix for keys in the Redis store.ttl: Time-to-live for keys in seconds (default 1 day).recall_ttl: Time-to-live extension for keys when recalled (default 3 days).+ *args: Additional positional arguments.+ **kwargs: Additional keyword arguments."""try:from upstash_redis import Redis@@ -245,8 +247,9 @@ class RedisEntityStore(BaseEntityStore):key_prefix: Prefix for keys in the Redis store.ttl: Time-to-live for keys in seconds (default 1 day).recall_ttl: Time-to-live extension for keys when recalled (default 3 days).+ *args: Additional positional arguments.+ **kwargs: Additional keyword arguments."""-try:import redisexcept ImportError as e:@@ -362,6 +365,8 @@ class SQLiteEntityStore(BaseEntityStore):session_id: Unique identifier for the session.db_file: Path to the SQLite database file.table_name: Name of the table to store entities.+ *args: Additional positional arguments.+ **kwargs: Additional keyword arguments."""super().__init__(*args, **kwargs)try:@@ -498,7 +503,8 @@ class ConversationEntityMemory(BaseChatMemory):return ["entities", self.chat_history_key]def load_memory_variables(self, inputs: dict[str, Any]) -> dict[str, Any]:- """+ """Load memory variables.+Returns chat history and all generated entities with summaries if available,and updates or clears the recent entity cache.@@ -506,7 +512,6 @@ class ConversationEntityMemory(BaseChatMemory):summaries are generated, so the entity cache values may be empty if no entitydescriptions are generated yet."""-# Create an LLMChain for predicting entity names from the recent chat history:chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)@@ -563,13 +568,11 @@ class ConversationEntityMemory(BaseChatMemory):}def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None:- """- Save context from this conversation history to the entity store.+ """Save context from this conversation history to the entity store.Generates a summary for each entity in the entity cache by promptingthe model, and saves these summaries to the entity store."""-super().save_context(inputs, outputs)if self.input_key is None:diff --git a/libs/langchain/langchain/memory/readonly.py b/libs/langchain/langchain/memory/readonly.pyindex 48e23d08fa..4220612316 100644--- a/libs/langchain/langchain/memory/readonly.py+++ b/libs/langchain/langchain/memory/readonly.py@@ -18,7 +18,7 @@ class ReadOnlySharedMemory(BaseMemory):return self.memory.load_memory_variables(inputs)def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None:- """Nothing should be saved or changed"""+ """Nothing should be saved or changed."""def clear(self) -> None:"""Nothing to clear, got a memory like a vault."""diff --git a/libs/langchain/langchain/memory/simple.py b/libs/langchain/langchain/memory/simple.pyindex 466a3bf1cd..61fb2b2730 100644--- a/libs/langchain/langchain/memory/simple.py+++ b/libs/langchain/langchain/memory/simple.py@@ -5,7 +5,9 @@ from typing_extensions import overrideclass SimpleMemory(BaseMemory):- """Simple memory for storing context or other information that shouldn't+ """Simple Memory.++ Simple memory for storing context or other information that shouldn'tever change between prompts."""diff --git a/libs/langchain/langchain/memory/summary.py b/libs/langchain/langchain/memory/summary.pyindex d5518a6e9e..f6e6fd27b7 100644--- a/libs/langchain/langchain/memory/summary.py+++ b/libs/langchain/langchain/memory/summary.py@@ -115,6 +115,7 @@ class ConversationSummaryMemory(BaseChatMemory, SummarizerMixin):chat_memory: The chat history to summarize.summarize_step: Number of messages to summarize at a time.**kwargs: Additional keyword arguments to pass to the class.+Returns:An instance of ConversationSummaryMemory with the summarized history."""diff --git a/libs/langchain/langchain/memory/summary_buffer.py b/libs/langchain/langchain/memory/summary_buffer.pyindex 7b82702240..4eca567f4f 100644--- a/libs/langchain/langchain/memory/summary_buffer.py+++ b/libs/langchain/langchain/memory/summary_buffer.py@@ -113,7 +113,7 @@ class ConversationSummaryBufferMemory(BaseChatMemory, SummarizerMixin):await self.aprune()def prune(self) -> None:- """Prune buffer if it exceeds max token limit"""+ """Prune buffer if it exceeds max token limit."""buffer = self.chat_memory.messagescurr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)if curr_buffer_length > self.max_token_limit:@@ -127,7 +127,7 @@ class ConversationSummaryBufferMemory(BaseChatMemory, SummarizerMixin):)async def aprune(self) -> None:- """Asynchronously prune buffer if it exceeds max token limit"""+ """Asynchronously prune buffer if it exceeds max token limit."""buffer = self.chat_memory.messagescurr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)if curr_buffer_length > self.max_token_limit:diff --git a/libs/langchain/langchain/memory/utils.py b/libs/langchain/langchain/memory/utils.pyindex 6415d3b597..f2950422cd 100644--- a/libs/langchain/langchain/memory/utils.py+++ b/libs/langchain/langchain/memory/utils.py@@ -2,8 +2,7 @@ from typing import Anydef get_prompt_input_key(inputs: dict[str, Any], memory_variables: list[str]) -> str:- """- Get the prompt input key.+ """Get the prompt input key.Args:inputs: Dict[str, Any]diff --git a/libs/langchain/langchain/memory/vectorstore.py b/libs/langchain/langchain/memory/vectorstore.pyindex 6d54fd0ed7..3345b5b704 100644--- a/libs/langchain/langchain/memory/vectorstore.py+++ b/libs/langchain/langchain/memory/vectorstore.py@@ -21,7 +21,9 @@ from langchain.memory.utils import get_prompt_input_key),)class VectorStoreRetrieverMemory(BaseMemory):- """Store the conversation history in a vector store and retrieves the relevant+ """Vector Store Retriever Memory.++ Store the conversation history in a vector store and retrieves the relevantparts of past conversation based on the input."""diff --git a/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py b/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.pyindex de0403a4e6..3aff21aaaa 100644--- a/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py+++ b/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py@@ -1,5 +1,4 @@-"""-Class for a conversation memory buffer with older messages stored in a vectorstore .+"""Class for a conversation memory buffer with older messages stored in a vectorstore .This implements a conversation memory in which the messages are stored in a memorybuffer up to a specified token limit. When the limit is exceeded, older messages are@@ -155,8 +154,7 @@ class ConversationVectorStoreTokenBufferMemory(ConversationTokenBufferMemory):curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)def save_remainder(self) -> None:- """- Save the remainder of the conversation buffer to the vector store.+ """Save the remainder of the conversation buffer to the vector store.This is useful if you have made the vectorstore persistent, in whichcase this can be called before the end of the session to store thediff --git a/libs/langchain/langchain/model_laboratory.py b/libs/langchain/langchain/model_laboratory.pyindex 3e87f212f3..e2ff5e7ee0 100644--- a/libs/langchain/langchain/model_laboratory.py+++ b/libs/langchain/langchain/model_laboratory.py@@ -20,10 +20,10 @@ class ModelLaboratory:"""Initialize the ModelLaboratory with chains to experiment with.Args:- chains (Sequence[Chain]): A sequence of chains to experiment with.- Each chain must have exactly one input and one output variable.- names (Optional[List[str]]): Optional list of names corresponding to each chain.- If provided, its length must match the number of chains.+ chains: A sequence of chains to experiment with.+ Each chain must have exactly one input and one output variable.+ names (Optional[List[str]]): Optional list of names corresponding to each+ chain. If provided, its length must match the number of chains.Raises:diff --git a/libs/langchain/langchain/output_parsers/combining.py b/libs/langchain/langchain/output_parsers/combining.pyindex 555bf00e67..e5fde8817c 100644--- a/libs/langchain/langchain/output_parsers/combining.py+++ b/libs/langchain/langchain/output_parsers/combining.py@@ -42,7 +42,6 @@ class CombiningOutputParser(BaseOutputParser[dict[str, Any]]):def get_format_instructions(self) -> str:"""Instructions on how the LLM output should be formatted."""-initial = f"For your first output: {self.parsers[0].get_format_instructions()}"subsequent = "\n".join(f"Complete that output fully. Then produce another output, separated by two newline characters: {p.get_format_instructions()}" # noqa: E501diff --git a/libs/langchain/langchain/output_parsers/structured.py b/libs/langchain/langchain/output_parsers/structured.pyindex 07952c091b..8ced0658e4 100644--- a/libs/langchain/langchain/output_parsers/structured.py+++ b/libs/langchain/langchain/output_parsers/structured.py@@ -61,7 +61,7 @@ class StructuredOutputParser(BaseOutputParser[dict[str, Any]]):) -> str:"""Get format instructions for the output parser.- example:+ Example:```pythonfrom langchain.output_parsers.structured import (StructuredOutputParser, ResponseSchemadiff --git a/libs/langchain/langchain/retrievers/contextual_compression.py b/libs/langchain/langchain/retrievers/contextual_compression.pyindex 0891bb913d..8f82c6f5b6 100644--- a/libs/langchain/langchain/retrievers/contextual_compression.py+++ b/libs/langchain/langchain/retrievers/contextual_compression.py@@ -7,6 +7,7 @@ from langchain_core.callbacks import (from langchain_core.documents import BaseDocumentCompressor, Documentfrom langchain_core.retrievers import BaseRetriever, RetrieverLikefrom pydantic import ConfigDict+from typing_extensions import overrideclass ContextualCompressionRetriever(BaseRetriever):@@ -22,6 +23,7 @@ class ContextualCompressionRetriever(BaseRetriever):arbitrary_types_allowed=True,)+ @overridedef _get_relevant_documents(self,query: str,@@ -29,14 +31,6 @@ class ContextualCompressionRetriever(BaseRetriever):run_manager: CallbackManagerForRetrieverRun,**kwargs: Any,) -> list[Document]:- """Get documents relevant for a query.-- Args:- query: string to find relevant documents for-- Returns:- Sequence of relevant documents- """docs = self.base_retriever.invoke(query,config={"callbacks": run_manager.get_child()},@@ -51,6 +45,7 @@ class ContextualCompressionRetriever(BaseRetriever):return list(compressed_docs)return []+ @overrideasync def _aget_relevant_documents(self,query: str,@@ -58,14 +53,6 @@ class ContextualCompressionRetriever(BaseRetriever):run_manager: AsyncCallbackManagerForRetrieverRun,**kwargs: Any,) -> list[Document]:- """Get documents relevant for a query.-- Args:- query: string to find relevant documents for-- Returns:- List of relevant documents- """docs = await self.base_retriever.ainvoke(query,config={"callbacks": run_manager.get_child()},diff --git a/libs/langchain/langchain/retrievers/document_compressors/chain_extract.py b/libs/langchain/langchain/retrievers/document_compressors/chain_extract.pyindex c5f5f51807..5f139483ce 100644--- a/libs/langchain/langchain/retrievers/document_compressors/chain_extract.py+++ b/libs/langchain/langchain/retrievers/document_compressors/chain_extract.py@@ -49,8 +49,11 @@ def _get_default_chain_prompt() -> PromptTemplate:class LLMChainExtractor(BaseDocumentCompressor):- """Document compressor that uses an LLM chain to extract- the relevant parts of documents."""+ """LLM Chain Extractor.++ Document compressor that uses an LLM chain to extract+ the relevant parts of documents.+ """llm_chain: Runnable"""LLM wrapper to use for compressing documents."""diff --git a/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py b/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.pyindex 4d779c8e3c..6f0d55ec57 100644--- a/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py+++ b/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py@@ -106,8 +106,7 @@ class CohereRerank(BaseDocumentCompressor):query: str,callbacks: Optional[Callbacks] = None,) -> Sequence[Document]:- """- Compress documents using Cohere's rerank API.+ """Compress documents using Cohere's rerank API.Args:documents: A sequence of documents to compress.diff --git a/libs/langchain/langchain/retrievers/document_compressors/cross_encoder_rerank.py b/libs/langchain/langchain/retrievers/document_compressors/cross_encoder_rerank.pyindex 553811eb94..4949d33882 100644--- a/libs/langchain/langchain/retrievers/document_compressors/cross_encoder_rerank.py+++ b/libs/langchain/langchain/retrievers/document_compressors/cross_encoder_rerank.py@@ -33,8 +33,7 @@ class CrossEncoderReranker(BaseDocumentCompressor):query: str,callbacks: Optional[Callbacks] = None,) -> Sequence[Document]:- """- Rerank documents using CrossEncoder.+ """Rerank documents using CrossEncoder.Args:documents: A sequence of documents to compress.diff --git a/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py b/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.pyindex cc4c3098ef..9dd2998f22 100644--- a/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py+++ b/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py@@ -22,8 +22,10 @@ def _get_similarity_function() -> Callable:class EmbeddingsFilter(BaseDocumentCompressor):- """Document compressor that uses embeddings to drop documents- unrelated to the query."""+ """Embeddings Filter.++ Document compressor that uses embeddings to drop documents unrelated to the query.+ """embeddings: Embeddings"""Embeddings to use for embedding document contents and queries."""diff --git a/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py b/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.pyindex 5f0dadd6f6..b2b95e2005 100644--- a/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py+++ b/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py@@ -117,7 +117,6 @@ class LLMListwiseRerank(BaseDocumentCompressor):Returns:A LLMListwiseRerank document compressor that uses the given language model."""-if llm.with_structured_output == BaseLanguageModel.with_structured_output:msg = (f"llm of type {type(llm)} does not implement `with_structured_output`."@@ -126,7 +125,9 @@ class LLMListwiseRerank(BaseDocumentCompressor):class RankDocuments(BaseModel):"""Rank the documents by their relevance to the user question.- Rank from most to least relevant."""++ Rank from most to least relevant.+ """ranked_document_ids: list[int] = Field(...,diff --git a/libs/langchain/langchain/retrievers/ensemble.py b/libs/langchain/langchain/retrievers/ensemble.pyindex 7c385339bb..797c6ddcb3 100644--- a/libs/langchain/langchain/retrievers/ensemble.py+++ b/libs/langchain/langchain/retrievers/ensemble.py@@ -1,6 +1,7 @@-"""+"""Ensemble Retriever.+Ensemble retriever that ensemble the results of-multiple retrievers by using weighted Reciprocal Rank Fusion+multiple retrievers by using weighted Reciprocal Rank Fusion."""import asyncio@@ -171,16 +172,15 @@ class EnsembleRetriever(BaseRetriever):*,run_manager: CallbackManagerForRetrieverRun,) -> list[Document]:- """- Get the relevant documents for a given query.+ """Get the relevant documents for a given query.Args:query: The query to search for.+ run_manager: The callback handler to use.Returns:A list of reranked documents."""-# Get fused result of the retrievers.return self.rank_fusion(query, run_manager)@@ -190,16 +190,15 @@ class EnsembleRetriever(BaseRetriever):*,run_manager: AsyncCallbackManagerForRetrieverRun,) -> list[Document]:- """- Asynchronously get the relevant documents for a given query.+ """Asynchronously get the relevant documents for a given query.Args:query: The query to search for.+ run_manager: The callback handler to use.Returns:A list of reranked documents."""-# Get fused result of the retrievers.return await self.arank_fusion(query, run_manager)@@ -210,17 +209,19 @@ class EnsembleRetriever(BaseRetriever):*,config: Optional[RunnableConfig] = None,) -> list[Document]:- """+ """Rank fusion.+Retrieve the results of the retrievers and use rank_fusion_func to getthe final result.Args:query: The query to search for.+ run_manager: The callback handler to use.+ config: Optional configuration for the retrievers.Returns:A list of reranked documents."""-# Get the results of all retrievers.retriever_docs = [retriever.invoke(@@ -250,17 +251,19 @@ class EnsembleRetriever(BaseRetriever):*,config: Optional[RunnableConfig] = None,) -> list[Document]:- """+ """Rank fusion.+Asynchronously retrieve the results of the retrieversand use rank_fusion_func to get the final result.Args:query: The query to search for.+ run_manager: The callback handler to use.+ config: Optional configuration for the retrievers.Returns:A list of reranked documents."""-# Get the results of all retrievers.retriever_docs = await asyncio.gather(*[@@ -289,10 +292,10 @@ class EnsembleRetriever(BaseRetriever):self,doc_lists: list[list[Document]],) -> list[Document]:- """- Perform weighted Reciprocal Rank Fusion on multiple rank lists.+ """Perform weighted Reciprocal Rank Fusion on multiple rank lists.+You can find more details about RRF here:- https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf+ https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf.Args:doc_lists: A list of rank lists, where each rank list contains unique items.diff --git a/libs/langchain/langchain/retrievers/merger_retriever.py b/libs/langchain/langchain/retrievers/merger_retriever.pyindex 4d02fda877..ba6e64abf4 100644--- a/libs/langchain/langchain/retrievers/merger_retriever.py+++ b/libs/langchain/langchain/retrievers/merger_retriever.py@@ -20,16 +20,15 @@ class MergerRetriever(BaseRetriever):*,run_manager: CallbackManagerForRetrieverRun,) -> list[Document]:- """- Get the relevant documents for a given query.+ """Get the relevant documents for a given query.Args:query: The query to search for.+ run_manager: The callback handler to use.Returns:A list of relevant documents."""-# Merge the results of the retrievers.return self.merge_documents(query, run_manager)@@ -39,16 +38,15 @@ class MergerRetriever(BaseRetriever):*,run_manager: AsyncCallbackManagerForRetrieverRun,) -> list[Document]:- """- Asynchronously get the relevant documents for a given query.+ """Asynchronously get the relevant documents for a given query.Args:query: The query to search for.+ run_manager: The callback handler to use.Returns:A list of relevant documents."""-# Merge the results of the retrievers.return await self.amerge_documents(query, run_manager)@@ -57,16 +55,15 @@ class MergerRetriever(BaseRetriever):query: str,run_manager: CallbackManagerForRetrieverRun,) -> list[Document]:- """- Merge the results of the retrievers.+ """Merge the results of the retrievers.Args:query: The query to search for.+ run_manager: The callback handler to use.Returns:A list of merged documents."""-# Get the results of all retrievers.retriever_docs = [retriever.invoke(@@ -91,16 +88,15 @@ class MergerRetriever(BaseRetriever):query: str,run_manager: AsyncCallbackManagerForRetrieverRun,) -> list[Document]:- """- Asynchronously merge the results of the retrievers.+ """Asynchronously merge the results of the retrievers.Args:query: The query to search for.+ run_manager: The callback handler to use.Returns:A list of merged documents."""-# Get the results of all retrievers.retriever_docs = await asyncio.gather(*(diff --git a/libs/langchain/langchain/retrievers/multi_query.py b/libs/langchain/langchain/retrievers/multi_query.pyindex 4006684aa5..1cb41cd82c 100644--- a/libs/langchain/langchain/retrievers/multi_query.py+++ b/libs/langchain/langchain/retrievers/multi_query.py@@ -77,6 +77,8 @@ class MultiQueryRetriever(BaseRetriever):llm: llm for query generation using DEFAULT_QUERY_PROMPTprompt: The prompt which aims to generate several different versionsof the given user query+ parser_key: DEPRECATED. `parser_key` is no longer used and should not be+ specified.include_original: Whether to include the original query in the list ofgenerated queries.@@ -101,6 +103,7 @@ class MultiQueryRetriever(BaseRetriever):Args:query: user query+ run_manager: the callback handler to use.Returns:Unique union of relevant documents from all generated queries@@ -120,6 +123,7 @@ class MultiQueryRetriever(BaseRetriever):Args:question: user query+ run_manager: the callback handler to use.Returns:List of LLM generated queries that are similar to the user input@@ -142,6 +146,7 @@ class MultiQueryRetriever(BaseRetriever):Args:queries: query list+ run_manager: the callback handler to useReturns:List of retrieved Documents@@ -167,6 +172,7 @@ class MultiQueryRetriever(BaseRetriever):Args:query: user query+ run_manager: the callback handler to use.Returns:Unique union of relevant documents from all generated queries@@ -186,6 +192,7 @@ class MultiQueryRetriever(BaseRetriever):Args:question: user query+ run_manager: run manager for callbacksReturns:List of LLM generated queries that are similar to the user input@@ -208,6 +215,7 @@ class MultiQueryRetriever(BaseRetriever):Args:queries: query list+ run_manager: run manager for callbacksReturns:List of retrieved Documentsdiff --git a/libs/langchain/langchain/retrievers/multi_vector.py b/libs/langchain/langchain/retrievers/multi_vector.pyindex 9e973e8190..1eef0cf181 100644--- a/libs/langchain/langchain/retrievers/multi_vector.py+++ b/libs/langchain/langchain/retrievers/multi_vector.py@@ -63,11 +63,12 @@ class MultiVectorRetriever(BaseRetriever):run_manager: CallbackManagerForRetrieverRun,) -> list[Document]:"""Get documents relevant to a query.+Args:query: String to find relevant documents forrun_manager: The callbacks handler to useReturns:- List of relevant documents+ List of relevant documents."""if self.search_type == SearchType.mmr:sub_docs = self.vectorstore.max_marginal_relevance_search(@@ -101,11 +102,12 @@ class MultiVectorRetriever(BaseRetriever):run_manager: AsyncCallbackManagerForRetrieverRun,) -> list[Document]:"""Asynchronously get documents relevant to a query.+Args:query: String to find relevant documents forrun_manager: The callbacks handler to useReturns:- List of relevant documents+ List of relevant documents."""if self.search_type == SearchType.mmr:sub_docs = await self.vectorstore.amax_marginal_relevance_search(diff --git a/libs/langchain/langchain/retrievers/parent_document_retriever.py b/libs/langchain/langchain/retrievers/parent_document_retriever.pyindex 0974f9327f..4b539e013e 100644--- a/libs/langchain/langchain/retrievers/parent_document_retriever.py+++ b/libs/langchain/langchain/retrievers/parent_document_retriever.py@@ -131,6 +131,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):This can be false if and only if `ids` are provided. You may wantto set this to False if the documents are already in the docstoreand you don't want to re-add them.+ **kwargs: additional keyword arguments passed to the vectorstore."""docs, full_docs = self._split_docs_for_adding(documents,@@ -161,6 +162,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):This can be false if and only if `ids` are provided. You may wantto set this to False if the documents are already in the docstoreand you don't want to re-add them.+ **kwargs: additional keyword arguments passed to the vectorstore."""docs, full_docs = self._split_docs_for_adding(documents,diff --git a/libs/langchain/langchain/retrievers/re_phraser.py b/libs/langchain/langchain/retrievers/re_phraser.pyindex 2b2139c656..8d83a55c91 100644--- a/libs/langchain/langchain/retrievers/re_phraser.py+++ b/libs/langchain/langchain/retrievers/re_phraser.py@@ -26,7 +26,9 @@ DEFAULT_QUERY_PROMPT = PromptTemplate.from_template(DEFAULT_TEMPLATE)class RePhraseQueryRetriever(BaseRetriever):"""Given a query, use an LLM to re-phrase it.- Then, retrieve docs for the re-phrased query."""++ Then, retrieve docs for the re-phrased query.+ """retriever: BaseRetrieverllm_chain: Runnable@@ -66,6 +68,7 @@ class RePhraseQueryRetriever(BaseRetriever):Args:query: user question+ run_manager: callback handler to useReturns:Relevant documents for re-phrased questiondiff --git a/libs/langchain/langchain/retrievers/self_query/base.py b/libs/langchain/langchain/retrievers/self_query/base.pyindex 7ffa2a43ea..c3a268d02b 100644--- a/libs/langchain/langchain/retrievers/self_query/base.py+++ b/libs/langchain/langchain/retrievers/self_query/base.py@@ -15,6 +15,7 @@ from langchain_core.runnables import Runnablefrom langchain_core.structured_query import StructuredQuery, Visitorfrom langchain_core.vectorstores import VectorStorefrom pydantic import ConfigDict, Field, model_validator+from typing_extensions import overridefrom langchain.chains.query_constructor.base import load_query_constructor_runnablefrom langchain.chains.query_constructor.schema import AttributeInfo@@ -232,8 +233,10 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:class SelfQueryRetriever(BaseRetriever):- """Retriever that uses a vector store and an LLM to generate- the vector store queries."""+ """Self Query Retriever.++ Retriever that uses a vector store and an LLM to generate the vector store queries.+ """vectorstore: VectorStore"""The underlying vector store from which documents will be retrieved."""@@ -301,20 +304,13 @@ class SelfQueryRetriever(BaseRetriever):) -> list[Document]:return await self.vectorstore.asearch(query, self.search_type, **search_kwargs)+ @overridedef _get_relevant_documents(self,query: str,*,run_manager: CallbackManagerForRetrieverRun,) -> list[Document]:- """Get documents relevant for a query.-- Args:- query: string to find relevant documents for-- Returns:- List of relevant documents- """structured_query = self.query_constructor.invoke({"query": query},config={"callbacks": run_manager.get_child()},@@ -324,20 +320,13 @@ class SelfQueryRetriever(BaseRetriever):new_query, search_kwargs = self._prepare_query(query, structured_query)return self._get_docs_with_query(new_query, search_kwargs)+ @overrideasync def _aget_relevant_documents(self,query: str,*,run_manager: AsyncCallbackManagerForRetrieverRun,) -> list[Document]:- """Get documents relevant for a query.-- Args:- query: string to find relevant documents for-- Returns:- List of relevant documents- """structured_query = await self.query_constructor.ainvoke({"query": query},config={"callbacks": run_manager.get_child()},diff --git a/libs/langchain/langchain/retrievers/time_weighted_retriever.py b/libs/langchain/langchain/retrievers/time_weighted_retriever.pyindex 4087cce12f..6416008578 100644--- a/libs/langchain/langchain/retrievers/time_weighted_retriever.py+++ b/libs/langchain/langchain/retrievers/time_weighted_retriever.py@@ -19,8 +19,10 @@ def _get_hours_passed(time: datetime.datetime, ref_time: datetime.datetime) -> fclass TimeWeightedVectorStoreRetriever(BaseRetriever):- """Retriever that combines embedding similarity with- recency in retrieving values."""+ """Time Weighted Vector Store Retriever.++ Retriever that combines embedding similarity with recency in retrieving values.+ """vectorstore: VectorStore"""The vectorstore to store documents and determine salience."""diff --git a/libs/langchain/langchain/runnables/hub.py b/libs/langchain/langchain/runnables/hub.pyindex 6036360e71..93492c9ade 100644--- a/libs/langchain/langchain/runnables/hub.py+++ b/libs/langchain/langchain/runnables/hub.py@@ -5,9 +5,7 @@ from langchain_core.runnables.utils import Input, Outputclass HubRunnable(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]- """- An instance of a runnable stored in the LangChain Hub.- """+ """An instance of a runnable stored in the LangChain Hub."""owner_repo_commit: strdiff --git a/libs/langchain/langchain/runnables/openai_functions.py b/libs/langchain/langchain/runnables/openai_functions.pyindex 5ac5119898..a62737f0a4 100644--- a/libs/langchain/langchain/runnables/openai_functions.py+++ b/libs/langchain/langchain/runnables/openai_functions.py@@ -10,7 +10,7 @@ from typing_extensions import TypedDictclass OpenAIFunction(TypedDict):- """A function description for ChatOpenAI"""+ """A function description for ChatOpenAI."""name: str"""The name of the function."""diff --git a/libs/langchain/langchain/smith/evaluation/config.py b/libs/langchain/langchain/smith/evaluation/config.pyindex a6fef4259e..3afe723f3f 100644--- a/libs/langchain/langchain/smith/evaluation/config.py+++ b/libs/langchain/langchain/smith/evaluation/config.py@@ -39,7 +39,7 @@ class EvalConfig(BaseModel):evaluator_type : EvaluatorTypeThe type of evaluator to use.- Methods+ Methods:-------get_kwargs()Get the keyword arguments for the evaluator configuration.@@ -51,7 +51,7 @@ class EvalConfig(BaseModel):def get_kwargs(self) -> dict[str, Any]:"""Get the keyword arguments for the load_evaluator call.- Returns+ Returns:-------Dict[str, Any]The keyword arguments for the load_evaluator call.@@ -360,6 +360,6 @@ class RunEvalConfig(BaseModel):prompt: Optional[BasePromptTemplate] = Noneclass LabeledScoreString(ScoreString):- """ "Configuration for a labeled score string evaluator."""+ """Configuration for a labeled score string evaluator."""evaluator_type: EvaluatorType = EvaluatorType.LABELED_SCORE_STRINGdiff --git a/libs/langchain/langchain/smith/evaluation/progress.py b/libs/langchain/langchain/smith/evaluation/progress.pyindex 4282f9c76a..79672b0e90 100644--- a/libs/langchain/langchain/smith/evaluation/progress.py+++ b/libs/langchain/langchain/smith/evaluation/progress.py@@ -26,6 +26,7 @@ class ProgressBarCallback(base_callbacks.BaseCallbackHandler):total: int, the total number of items to be processed.ncols: int, the character width of the progress bar.end_with: str, last string to print after progress bar reaches end.+ **kwargs: additional keyword arguments."""self.total = totalself.ncols = ncolsdiff --git a/libs/langchain/langchain/smith/evaluation/runner_utils.py b/libs/langchain/langchain/smith/evaluation/runner_utils.pyindex b50ae0cbf2..d584a52116 100644--- a/libs/langchain/langchain/smith/evaluation/runner_utils.py+++ b/libs/langchain/langchain/smith/evaluation/runner_utils.py@@ -168,8 +168,10 @@ class EvalError(dict):Args:name: The name of the attribute to get.+Returns:The value of the attribute.+Raises:AttributeError: If the attribute does not exist."""@@ -184,8 +186,11 @@ def _wrap_in_chain_factory(llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,dataset_name: str = "<my_dataset>",) -> MCF:- """Forgive the user if they pass in a chain without memory instead of a chain- factory. It's a common mistake. Raise a more helpful error message as well."""+ """Wrap in a chain factory.++ Forgive the user if they pass in a chain without memory instead of a chain+ factory. It's a common mistake. Raise a more helpful error message as well.+ """if isinstance(llm_or_chain_factory, Chain):chain = llm_or_chain_factorychain_class = chain.__class__.__name__@@ -249,6 +254,7 @@ def _get_prompt(inputs: dict[str, Any]) -> str:Returns:A string prompt.+Raises:InputFormatError: If the input format is invalid."""@@ -308,6 +314,7 @@ def _get_messages(inputs: dict[str, Any]) -> dict:Returns:A list of chat messages.+Raises:InputFormatError: If the input format is invalid."""@@ -628,11 +635,15 @@ def _load_run_evaluators(run_inputs: Optional[list[str]],run_outputs: Optional[list[str]],) -> list[RunEvaluator]:- """- Load run evaluators from a configuration.+ """Load run evaluators from a configuration.Args:config: Configuration for the run evaluators.+ run_type: The type of run.+ data_type: The type of dataset used in the run.+ example_outputs: The example outputs.+ run_inputs: The input keys for the run.+ run_outputs: The output keys for the run.Returns:A list of run evaluators.@@ -708,9 +719,11 @@ async def _arun_llm(tags: Optional tags to add to the run.callbacks: Optional callbacks to use during the run.input_mapper: Optional function to map inputs to the expected format.+ metadata: Optional metadata to add to the run.Returns:The LLMResult or ChatResult.+Raises:ValueError: If the LLM type is unsupported.InputFormatError: If the input format is invalid.@@ -806,9 +819,8 @@ async def _arun_llm_or_chain(Args:example: The example to run.+ config: The configuration for the run.llm_or_chain_factory: The Chain or language model constructor to run.- tags: Optional tags to add to the run.- callbacks: Optional callbacks to use during the run.input_mapper: Optional function to map the input to the expected format.Returns:@@ -863,8 +875,7 @@ def _run_llm(input_mapper: Optional[Callable[[dict], Any]] = None,metadata: Optional[dict[str, Any]] = None,) -> Union[str, BaseMessage]:- """- Run the language model on the example.+ """Run the language model on the example.Args:llm: The language model to run.@@ -872,8 +883,11 @@ def _run_llm(callbacks: The callbacks to use during the run.tags: Optional tags to add to the run.input_mapper: function to map to the inputs dictionary from an Example+ metadata: Optional metadata to add to the run.+Returns:The LLMResult or ChatResult.+Raises:ValueError: If the LLM type is unsupported.InputFormatError: If the input format is invalid.@@ -963,14 +977,13 @@ def _run_llm_or_chain(llm_or_chain_factory: MCF,input_mapper: Optional[Callable[[dict], Any]] = None,) -> Union[dict, str, LLMResult, ChatResult]:- """- Run the Chain or language model synchronously.+ """Run the Chain or language model synchronously.Args:example: The example to run.+ config: The configuration for the run.llm_or_chain_factory: The Chain or language model constructor to run.- tags: Optional tags to add to the run.- callbacks: Optional callbacks to use during the run.+ input_mapper: Optional function to map the input to the expected format.Returns:Union[List[dict], List[str], List[LLMResult], List[ChatResult]]:@@ -1359,7 +1372,8 @@ async def arun_on_dataset(over the dataset. The Chain constructor is used to permitindependent calls on each example without carrying over state.evaluation: Configuration for evaluators to run on the- results of the chain+ results of the chain.+ dataset_version: Optional version of the dataset.concurrency_level: The number of async tasks to run concurrently.project_name: Name of the project to store the traces in.Defaults to {dataset_name}-{chain class name}-{datetime}.@@ -1369,9 +1383,10 @@ async def arun_on_dataset(client: LangSmith client to use to access the dataset and tolog feedback and run traces.verbose: Whether to print progress.- tags: Tags to add to each run in the project.revision_id: Optional revision identifier to assign this test run totrack the performance of different versions of your system.+ **kwargs: Should not be used, but is provided for backwards compatibility.+Returns:A dictionary containing the run's project name and the resulting model outputs.@@ -1532,7 +1547,8 @@ def run_on_dataset(over the dataset. The Chain constructor is used to permitindependent calls on each example without carrying over state.evaluation: Configuration for evaluators to run on the- results of the chain+ results of the chain.+ dataset_version: Optional version of the dataset.concurrency_level: The number of async tasks to run concurrently.project_name: Name of the project to store the traces in.Defaults to {dataset_name}-{chain class name}-{datetime}.@@ -1542,9 +1558,10 @@ def run_on_dataset(client: LangSmith client to use to access the dataset and tolog feedback and run traces.verbose: Whether to print progress.- tags: Tags to add to each run in the project.revision_id: Optional revision identifier to assign this test run totrack the performance of different versions of your system.+ **kwargs: Should not be used, but is provided for backwards compatibility.+Returns:A dictionary containing the run's project name and the resulting model outputs.diff --git a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.pyindex 307e1109bf..202755e280 100644--- a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py+++ b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py@@ -79,8 +79,10 @@ class LLMStringRunMapper(StringRunMapper):Args:inputs: The inputs from the run, expected to contain prompts or messages.+Returns:The serialized input text from the prompts or messages.+Raises:ValueError: If neither prompts nor messages are found in the inputs."""@@ -408,8 +410,7 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):reference_key: Optional[str] = None,tags: Optional[list[str]] = None,) -> StringRunEvaluatorChain:- """- Create a StringRunEvaluatorChain from an evaluator and the run and dataset types.+ """Create a StringRunEvaluatorChain from an evaluator and the run and dataset types.This method provides an easy way to instantiate a StringRunEvaluatorChain, bytaking an evaluator and information about the type of run and the data.@@ -433,7 +434,6 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):reference from the dataset but the reference key is not provided.""" # noqa: E501-# Configure how run inputs/predictions are passed to the evaluatorif run_type == "llm":run_mapper: StringRunMapper = LLMStringRunMapper()diff --git a/libs/langchain/langchain/storage/file_system.py b/libs/langchain/langchain/storage/file_system.pyindex c0c8e1ab42..f2476d63e1 100644--- a/libs/langchain/langchain/storage/file_system.py+++ b/libs/langchain/langchain/storage/file_system.py@@ -90,7 +90,7 @@ class LocalFileStore(ByteStore):return full_pathdef _mkdir_for_store(self, dir_path: Path) -> None:- """Makes a store directory path (including parents) with specified permissions+ """Makes a store directory path (including parents) with specified permissions.This is needed because `Path.mkdir()` is restricted by the current `umask`,whereas the explicit `os.chmod()` used here is not.diff --git a/libs/langchain/langchain/tools/github/__init__.py b/libs/langchain/langchain/tools/github/__init__.pyindex 11c741aa55..b3a380e65e 100644--- a/libs/langchain/langchain/tools/github/__init__.py+++ b/libs/langchain/langchain/tools/github/__init__.py@@ -1 +1 @@-"""GitHub Tool"""+"""GitHub Tool."""diff --git a/libs/langchain/langchain/tools/gitlab/__init__.py b/libs/langchain/langchain/tools/gitlab/__init__.pyindex 75ad8d0196..9c194f644c 100644--- a/libs/langchain/langchain/tools/gitlab/__init__.py+++ b/libs/langchain/langchain/tools/gitlab/__init__.py@@ -1 +1 @@-"""GitLab Tool"""+"""GitLab Tool."""diff --git a/libs/langchain/langchain/tools/graphql/__init__.py b/libs/langchain/langchain/tools/graphql/__init__.pyindex 7e9a84c377..4833068325 100644--- a/libs/langchain/langchain/tools/graphql/__init__.py+++ b/libs/langchain/langchain/tools/graphql/__init__.py@@ -1 +1 @@-"""Tools for interacting with a GraphQL API"""+"""Tools for interacting with a GraphQL API."""diff --git a/libs/langchain/langchain/tools/jira/tool.py b/libs/langchain/langchain/tools/jira/tool.pyindex b9f2db6c11..c0eb5c4b4e 100644--- a/libs/langchain/langchain/tools/jira/tool.py+++ b/libs/langchain/langchain/tools/jira/tool.py@@ -1,5 +1,4 @@-"""-This module provides dynamic access to deprecated Jira tools.+"""This module provides dynamic access to deprecated Jira tools.When attributes like `JiraAction` are accessed, they are redirected to their newlocations in `langchain_community.tools`. This ensures backward compatibility@@ -25,8 +24,7 @@ _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_Ldef __getattr__(name: str) -> Any:- """- Dynamically retrieve attributes from the updated module path.+ """Dynamically retrieve attributes from the updated module path.Args:name (str): The name of the attribute to import.diff --git a/libs/langchain/langchain/tools/json/tool.py b/libs/langchain/langchain/tools/json/tool.pyindex d6b2a6a429..65384b22b6 100644--- a/libs/langchain/langchain/tools/json/tool.py+++ b/libs/langchain/langchain/tools/json/tool.py@@ -1,5 +1,4 @@-"""-This module provides dynamic access to deprecated JSON tools in LangChain.+"""This module provides dynamic access to deprecated JSON tools in LangChain.It ensures backward compatibility by forwarding references such as`JsonGetValueTool`, `JsonListKeysTool`, and `JsonSpec` to their updated@@ -30,8 +29,7 @@ _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_Ldef __getattr__(name: str) -> Any:- """- Dynamically retrieve attributes from the updated module path.+ """Dynamically retrieve attributes from the updated module path.This method is used to resolve deprecated attribute importsat runtime and forward them to their new locations.diff --git a/libs/langchain/langchain/tools/steam/__init__.py b/libs/langchain/langchain/tools/steam/__init__.pyindex 9367fd95b3..195a6eef37 100644--- a/libs/langchain/langchain/tools/steam/__init__.py+++ b/libs/langchain/langchain/tools/steam/__init__.py@@ -1 +1 @@-"""Steam API toolkit"""+"""Steam API toolkit."""diff --git a/libs/langchain/langchain/tools/zapier/tool.py b/libs/langchain/langchain/tools/zapier/tool.pyindex c0100e3d0c..dd069c503c 100644--- a/libs/langchain/langchain/tools/zapier/tool.py+++ b/libs/langchain/langchain/tools/zapier/tool.py@@ -1,5 +1,4 @@-"""-This module provides dynamic access to deprecated Zapier tools in LangChain.+"""This module provides dynamic access to deprecated Zapier tools in LangChain.It supports backward compatibility by forwarding references such as`ZapierNLAListActions` and `ZapierNLARunAction` to their updated locations@@ -28,8 +27,7 @@ _import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_Ldef __getattr__(name: str) -> Any:- """- Dynamically retrieve attributes from the updated module path.+ """Dynamically retrieve attributes from the updated module path.This method is used to resolve deprecated attribute importsat runtime and forward them to their new locations.diff --git a/libs/langchain/langchain/utilities/asyncio.py b/libs/langchain/langchain/utilities/asyncio.pyindex d7db052e93..f00e87f452 100644--- a/libs/langchain/langchain/utilities/asyncio.py+++ b/libs/langchain/langchain/utilities/asyncio.py@@ -1,4 +1,4 @@-"""Shims for asyncio features that may be missing from older python versions"""+"""Shims for asyncio features that may be missing from older python versions."""import sysdiff --git a/libs/langchain/langchain/utils/__init__.py b/libs/langchain/langchain/utils/__init__.pyindex a21d037097..06f6848444 100644--- a/libs/langchain/langchain/utils/__init__.py+++ b/libs/langchain/langchain/utils/__init__.py@@ -1,5 +1,4 @@-"""-**Utility functions** for LangChain.+"""**Utility functions** for LangChain.These functions do not depend on any other LangChain module."""diff --git a/libs/langchain/pyproject.toml b/libs/langchain/pyproject.tomlindex d7b0f14959..0db0925bd6 100644--- a/libs/langchain/pyproject.toml+++ b/libs/langchain/pyproject.toml@@ -164,9 +164,6 @@ ignore = ["BLE","D100", # pydocstyle: missing docstring in public module"D104", # pydocstyle: missing docstring in public package- "D2",- "D3",- "D4","ERA","PLC0415", # pylint: import-outside-top-level"TRY301", # tryceratops: raise-within-trydiff --git a/libs/langchain/scripts/check_imports.py b/libs/langchain/scripts/check_imports.pyindex c7f667eacf..3d5e2beeb2 100644--- a/libs/langchain/scripts/check_imports.py+++ b/libs/langchain/scripts/check_imports.py@@ -1,4 +1,5 @@-"""+"""Check Imports Script.+Quickly verify that a list of Python files can be loaded by the Python interpreterwithout raising any errors. Ran before running more expensive tests. Useful inMakefiles.diff --git a/libs/langchain/tests/integration_tests/cache/fake_embeddings.py b/libs/langchain/tests/integration_tests/cache/fake_embeddings.pyindex f427e3c478..2226bee87d 100644--- a/libs/langchain/tests/integration_tests/cache/fake_embeddings.py+++ b/libs/langchain/tests/integration_tests/cache/fake_embeddings.py@@ -11,9 +11,18 @@ fake_texts = ["foo", "bar", "baz"]class FakeEmbeddings(Embeddings):"""Fake embeddings functionality for testing."""+ @overridedef embed_documents(self, texts: list[str]) -> list[list[float]]:"""Return simple embeddings.- Embeddings encode each text as its index."""++ Embeddings encode each text as its index.++ Args:+ texts: List of text to embed.++ Returns:+ List of embeddings.+ """return [[1.0] * 9 + [float(i)] for i in range(len(texts))]async def aembed_documents(self, texts: list[str]) -> list[list[float]]:@@ -22,9 +31,17 @@ class FakeEmbeddings(Embeddings):@overridedef embed_query(self, text: str) -> list[float]:"""Return constant query embeddings.+Embeddings are identical to embed_documents(texts)[0].Distance to each text will be that text's index,- as it was passed to embed_documents."""+ as it was passed to embed_documents.++ Args:+ text: Text to embed.++ Returns:+ Embedding.+ """return [1.0] * 9 + [0.0]async def aembed_query(self, text: str) -> list[float]:@@ -32,8 +49,11 @@ class FakeEmbeddings(Embeddings):class ConsistentFakeEmbeddings(FakeEmbeddings):- """Fake embeddings which remember all the texts seen so far to return consistent- vectors for the same texts."""+ """Consistent fake embeddings.++ Fake embeddings which remember all the texts seen so far to return consistent+ vectors for the same texts.+ """def __init__(self, dimensionality: int = 10) -> None:self.known_texts: list[str] = []@@ -51,29 +71,43 @@ class ConsistentFakeEmbeddings(FakeEmbeddings):out_vectors.append(vector)return out_vectors+ @overridedef embed_query(self, text: str) -> list[float]:- """Return consistent embeddings for the text, if seen before, or a constant- one if the text is unknown."""+ """Embed query text.++ Return consistent embeddings for the text, if seen before, or a constant+ one if the text is unknown.++ Args:+ text: Text to embed.++ Returns:+ Embedding.+ """return self.embed_documents([text])[0]class AngularTwoDimensionalEmbeddings(Embeddings):- """- From angles (as strings in units of pi) to unit embedding vectors on a circle.- """+ """From angles (as strings in units of pi) to unit embedding vectors on a circle."""def embed_documents(self, texts: list[str]) -> list[list[float]]:- """- Make a list of texts into a list of embedding vectors.- """+ """Make a list of texts into a list of embedding vectors."""return [self.embed_query(text) for text in texts]+ @overridedef embed_query(self, text: str) -> list[float]:- """+ """Embed query text.+Convert input text to a 'vector' (list of floats).If the text is a number, use it as the angle for theunit vector in units of pi.Any other input text becomes the singular result [0, 0] !++ Args:+ text: Text to embed.++ Returns:+ Embedding."""try:angle = float(text)diff --git a/libs/langchain/tests/mock_servers/robot/server.py b/libs/langchain/tests/mock_servers/robot/server.pyindex e80d87c305..4d92a8c1b9 100644--- a/libs/langchain/tests/mock_servers/robot/server.py+++ b/libs/langchain/tests/mock_servers/robot/server.py@@ -181,7 +181,7 @@ async def ask_for_help(query: str) -> dict[str, Any]:def custom_openapi() -> dict[str, Any]:- """Add servers configuration to the OpenAPI schema"""+ """Add servers configuration to the OpenAPI schema."""if app.openapi_schema:return app.openapi_schemadiff --git a/libs/langchain/tests/unit_tests/agents/test_agent.py b/libs/langchain/tests/unit_tests/agents/test_agent.pyindex 36045d82a0..f1e8a7388b 100644--- a/libs/langchain/tests/unit_tests/agents/test_agent.py+++ b/libs/langchain/tests/unit_tests/agents/test_agent.py@@ -451,7 +451,6 @@ def test_agent_invalid_tool() -> None:async def test_runnable_agent() -> None:"""Simple test to verify that an agent built with LCEL works."""-# Will alternate between responding with hello and goodbyeinfinite_cycle = cycle([AIMessage(content="hello world!")])# When streaming GenericFakeChatModel breaks AIMessage into chunks based on spacesdiff --git a/libs/langchain/tests/unit_tests/agents/test_agent_iterator.py b/libs/langchain/tests/unit_tests/agents/test_agent_iterator.pyindex faef1a4f21..ed0395565f 100644--- a/libs/langchain/tests/unit_tests/agents/test_agent_iterator.py+++ b/libs/langchain/tests/unit_tests/agents/test_agent_iterator.py@@ -28,7 +28,8 @@ def test_agent_iterator_bad_action() -> None:def test_agent_iterator_stopped_early() -> None:- """+ """Test react chain iterator when stopped early.+Test react chain iterator when max iterations ormax execution time is exceeded."""@@ -58,7 +59,8 @@ def test_agent_iterator_stopped_early() -> None:async def test_agent_async_iterator_stopped_early() -> None:- """+ """Test when async react chain iterator is stopped early.+Test react chain async iterator when max iterations ormax execution time is exceeded."""@@ -352,7 +354,6 @@ def test_agent_iterator_custom_stopping_condition() -> None:def test_agent_iterator_failing_tool() -> None:"""Test AgentExecutorIterator with a tool that raises an exception."""-# Get agent for testing.bad_action_name = "FailingTool"responses = [diff --git a/libs/langchain/tests/unit_tests/agents/test_mrkl.py b/libs/langchain/tests/unit_tests/agents/test_mrkl.pyindex b156592564..cc2449eaa8 100644--- a/libs/langchain/tests/unit_tests/agents/test_mrkl.py+++ b/libs/langchain/tests/unit_tests/agents/test_mrkl.py@@ -47,9 +47,11 @@ def test_get_action_and_input_newline() -> None:def test_get_action_and_input_newline_after_keyword() -> None:- """Test getting an action and action input from the text+ """Test when there is a new line before the action.++ Test getting an action and action input from the textwhen there is a new line before the action- (after the keywords "Action:" and "Action Input:")+ (after the keywords "Action:" and "Action Input:")."""llm_output = """I can use the `ls` command to list the contents of the directory \@@ -68,8 +70,10 @@ def test_get_action_and_input_newline_after_keyword() -> None:def test_get_action_and_input_sql_query() -> None:- """Test getting the action and action input from the text- when the LLM output is a well formed SQL query+ """Test when the LLM output is a well-formed SQL query.++ Test getting the action and action input from the text+ when the LLM output is a well formed SQL query."""llm_output = """I should query for the largest single shift payment for every unique user.diff --git a/libs/langchain/tests/unit_tests/callbacks/test_file.py b/libs/langchain/tests/unit_tests/callbacks/test_file.pyindex 7e91bd1526..1e7fdda860 100644--- a/libs/langchain/tests/unit_tests/callbacks/test_file.py+++ b/libs/langchain/tests/unit_tests/callbacks/test_file.py@@ -36,8 +36,7 @@ class FakeChain(Chain):def strip_ansi(text: str) -> str:- """- Removes ANSI escape sequences from a string.+ """Removes ANSI escape sequences from a string.Args:text: The string potentially containing ANSI codes.diff --git a/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py b/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.pyindex 5628429226..ea4b776616 100644--- a/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py+++ b/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py@@ -1,4 +1,4 @@-"""Test map_rerank parser"""+"""Test map_rerank parser."""import pytestdiff --git a/libs/langchain/tests/unit_tests/chains/test_base.py b/libs/langchain/tests/unit_tests/chains/test_base.pyindex a40f0c9f6f..37c5abc9c4 100644--- a/libs/langchain/tests/unit_tests/chains/test_base.py+++ b/libs/langchain/tests/unit_tests/chains/test_base.py@@ -80,7 +80,7 @@ def test_bad_outputs() -> None:def test_run_info() -> None:- """Test that run_info is returned properly when specified"""+ """Test that run_info is returned properly when specified."""chain = FakeChain()output = chain({"foo": "bar"}, include_run_info=True)assert "foo" in outputdiff --git a/libs/langchain/tests/unit_tests/indexes/test_indexing.py b/libs/langchain/tests/unit_tests/indexes/test_indexing.pyindex c820df836d..84c37a5207 100644--- a/libs/langchain/tests/unit_tests/indexes/test_indexing.py+++ b/libs/langchain/tests/unit_tests/indexes/test_indexing.py@@ -803,7 +803,7 @@ def test_incremental_indexing_with_batch_size(record_manager: SQLRecordManager,vector_store: InMemoryVectorStore,) -> None:- """Test indexing with incremental indexing"""+ """Test indexing with incremental indexing."""loader = ToyLoader(documents=[Document(diff --git a/libs/langchain/tests/unit_tests/llms/fake_chat_model.py b/libs/langchain/tests/unit_tests/llms/fake_chat_model.pyindex c4f2670fb8..5d67a0a05d 100644--- a/libs/langchain/tests/unit_tests/llms/fake_chat_model.py+++ b/libs/langchain/tests/unit_tests/llms/fake_chat_model.py@@ -87,7 +87,7 @@ class GenericFakeChatModel(BaseChatModel):run_manager: Optional[CallbackManagerForLLMRun] = None,**kwargs: Any,) -> ChatResult:- """Top Level call"""+ """Top Level call."""message = next(self.messages)generation = ChatGeneration(message=message)return ChatResult(generations=[generation])diff --git a/libs/langchain/tests/unit_tests/load/test_dump.py b/libs/langchain/tests/unit_tests/load/test_dump.pyindex ed4dc7982a..1861b6f790 100644--- a/libs/langchain/tests/unit_tests/load/test_dump.py+++ b/libs/langchain/tests/unit_tests/load/test_dump.py@@ -1,4 +1,4 @@-"""Test for Serializable base class"""+"""Test for Serializable base class."""import jsonimport osdiff --git a/libs/langchain/tests/unit_tests/load/test_load.py b/libs/langchain/tests/unit_tests/load/test_load.pyindex 1a14f01b53..786648ca94 100644--- a/libs/langchain/tests/unit_tests/load/test_load.py+++ b/libs/langchain/tests/unit_tests/load/test_load.py@@ -1,4 +1,4 @@-"""Test for Serializable base class"""+"""Test for Serializable base class."""import pytestfrom langchain_core.load.dump import dumpd, dumpsdiff --git a/libs/langchain/tests/unit_tests/memory/__init__.py b/libs/langchain/tests/unit_tests/memory/__init__.pyindex 2494d10284..972603e37c 100644--- a/libs/langchain/tests/unit_tests/memory/__init__.py+++ b/libs/langchain/tests/unit_tests/memory/__init__.py@@ -1 +1 @@-"""Unit tests for memory module"""+"""Unit tests for memory module."""diff --git a/libs/langchain/tests/unit_tests/memory/test_combined_memory.py b/libs/langchain/tests/unit_tests/memory/test_combined_memory.pyindex a8853bd919..085a8eabdc 100644--- a/libs/langchain/tests/unit_tests/memory/test_combined_memory.py+++ b/libs/langchain/tests/unit_tests/memory/test_combined_memory.py@@ -1,4 +1,4 @@-"""Test for CombinedMemory class"""+"""Test for CombinedMemory class."""# from langchain_core.prompts import PromptTemplate@@ -16,7 +16,7 @@ def example_memory() -> list[ConversationBufferMemory]:def test_basic_functionality(example_memory: list[ConversationBufferMemory]) -> None:- """Test basic functionality of methods exposed by class"""+ """Test basic functionality of methods exposed by class."""combined_memory = CombinedMemory(memories=[example_memory[0], example_memory[1]])assert combined_memory.memory_variables == ["foo", "bar"]assert combined_memory.load_memory_variables({}) == {"foo": "", "bar": ""}@@ -33,7 +33,7 @@ def test_basic_functionality(example_memory: list[ConversationBufferMemory]) ->def test_repeated_memory_var(example_memory: list[ConversationBufferMemory]) -> None:- """Test raising error when repeated memory variables found"""+ """Test raising error when repeated memory variables found."""with pytest.raises(ValueError,match="Value error, The same variables {'bar'} are found in "diff --git a/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py b/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.pyindex 5e73d885fd..a727d4a7e0 100644--- a/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py+++ b/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py@@ -1,4 +1,4 @@-"""Test PandasDataframeParser"""+"""Test PandasDataframeParser."""from typing import Anydiff --git a/libs/langchain/tests/unit_tests/output_parsers/test_yaml_parser.py b/libs/langchain/tests/unit_tests/output_parsers/test_yaml_parser.pyindex b5f0c3d3f9..bbaa6dfdc2 100644--- a/libs/langchain/tests/unit_tests/output_parsers/test_yaml_parser.py+++ b/libs/langchain/tests/unit_tests/output_parsers/test_yaml_parser.py@@ -1,4 +1,4 @@-"""Test yamlOutputParser"""+"""Test yamlOutputParser."""from enum import Enumfrom typing import Optional@@ -70,7 +70,6 @@ DEF_EXPECTED_RESULT = TestModel(@pytest.mark.parametrize("result", [DEF_RESULT, DEF_RESULT_NO_BACKTICKS])def test_yaml_output_parser(result: str) -> None:"""Test yamlOutputParser."""-yaml_parser: YamlOutputParser[TestModel] = YamlOutputParser(pydantic_object=TestModel,)@@ -82,7 +81,6 @@ def test_yaml_output_parser(result: str) -> None:def test_yaml_output_parser_fail() -> None:"""Test YamlOutputParser where completion result fails schema validation."""-yaml_parser: YamlOutputParser[TestModel] = YamlOutputParser(pydantic_object=TestModel,)diff --git a/libs/langchain/tests/unit_tests/retrievers/sequential_retriever.py b/libs/langchain/tests/unit_tests/retrievers/sequential_retriever.pyindex e47e144ede..1853a76d09 100644--- a/libs/langchain/tests/unit_tests/retrievers/sequential_retriever.py+++ b/libs/langchain/tests/unit_tests/retrievers/sequential_retriever.py@@ -6,7 +6,7 @@ from typing_extensions import overrideclass SequentialRetriever(BaseRetriever):- """Test util that returns a sequence of documents"""+ """Test util that returns a sequence of documents."""sequential_responses: list[list[Document]]response_index: int = 0diff --git a/libs/langchain/tests/unit_tests/retrievers/test_ensemble.py b/libs/langchain/tests/unit_tests/retrievers/test_ensemble.pyindex 02a67e33a7..42163d39a4 100644--- a/libs/langchain/tests/unit_tests/retrievers/test_ensemble.py+++ b/libs/langchain/tests/unit_tests/retrievers/test_ensemble.py@@ -18,7 +18,7 @@ class MockRetriever(BaseRetriever):*,run_manager: Optional[CallbackManagerForRetrieverRun] = None,) -> list[Document]:- """Return the documents"""+ """Return the documents."""return self.docsdiff --git a/libs/langchain/tests/unit_tests/storage/test_filesystem.py b/libs/langchain/tests/unit_tests/storage/test_filesystem.pyindex 49c0e7a153..a352c8d3a9 100644--- a/libs/langchain/tests/unit_tests/storage/test_filesystem.py+++ b/libs/langchain/tests/unit_tests/storage/test_filesystem.py@@ -133,7 +133,10 @@ def test_yield_keys(file_store: LocalFileStore) -> None:def test_catches_forbidden_keys(file_store: LocalFileStore) -> None:- """Make sure we raise exception on keys that are not allowed; e.g., absolute path"""+ """Test that forbidden keys raise exceptions.++ Make sure we raise exception on keys that are not allowed; e.g., absolute path.+ """with pytest.raises(InvalidKeyException):file_store.mset([("/etc", b"value1")])with pytest.raises(InvalidKeyException):diff --git a/libs/langchain/tests/unit_tests/test_dependencies.py b/libs/langchain/tests/unit_tests/test_dependencies.pyindex 5b0160a7f5..7b9e12f0e4 100644--- a/libs/langchain/tests/unit_tests/test_dependencies.py+++ b/libs/langchain/tests/unit_tests/test_dependencies.py@@ -52,7 +52,6 @@ def test_test_group_dependencies(uv_conf: Mapping[str, Any]) -> None:Examples of dependencies that should NOT be included: boto3, azure, postgres, etc."""-dependencies = uv_conf["dependency-groups"]["test"]test_group_deps = {Requirement(dep).name for dep in dependencies}diff --git a/libs/langchain/tests/unit_tests/test_imports.py b/libs/langchain/tests/unit_tests/test_imports.pyindex 5e83b8a52c..5eb03e7dc9 100644--- a/libs/langchain/tests/unit_tests/test_imports.py+++ b/libs/langchain/tests/unit_tests/test_imports.py@@ -108,7 +108,7 @@ def test_no_more_changes_to_proxy_community() -> None:def extract_deprecated_lookup(file_path: str) -> Optional[dict[str, Any]]:- """Detect and extracts the value of a dictionary named DEPRECATED_LOOKUP+ """Detect and extracts the value of a dictionary named DEPRECATED_LOOKUP.This variable is located in the global namespace of a Python file.