Skip to content

The agent engineering platform.

chore(langchain): remove arg types from docstrings (#33413)

Christophe Bornetdd994b9d7f8b
diff --git a/AGENTS.md b/AGENTS.md
index ee61a460a4..7fb2a21350 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -152,11 +152,11 @@ def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:
priority: Email priority level (`'low'`, `'normal'`, `'high'`).
Returns:
- True if email was sent successfully, False otherwise.
+ `True` if email was sent successfully, `False` otherwise.
Raises:
- InvalidEmailError: If the email address format is invalid.
- SMTPConnectionError: If unable to connect to email server.
+ `InvalidEmailError`: If the email address format is invalid.
+ `SMTPConnectionError`: If unable to connect to email server.
"""
```
diff --git a/CLAUDE.md b/CLAUDE.md
index ee61a460a4..7fb2a21350 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -152,11 +152,11 @@ def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:
priority: Email priority level (`'low'`, `'normal'`, `'high'`).
Returns:
- True if email was sent successfully, False otherwise.
+ `True` if email was sent successfully, `False` otherwise.
Raises:
- InvalidEmailError: If the email address format is invalid.
- SMTPConnectionError: If unable to connect to email server.
+ `InvalidEmailError`: If the email address format is invalid.
+ `SMTPConnectionError`: If unable to connect to email server.
"""
```
diff --git a/libs/cli/langchain_cli/namespaces/migrate/generate/utils.py b/libs/cli/langchain_cli/namespaces/migrate/generate/utils.py
index e62f4b07db..688276617c 100644
--- a/libs/cli/langchain_cli/namespaces/migrate/generate/utils.py
+++ b/libs/cli/langchain_cli/namespaces/migrate/generate/utils.py
@@ -65,7 +65,7 @@ def is_subclass(class_obj: type, classes_: list[type]) -> bool:
classes_: A list of classes to check against.
Returns:
- True if `class_obj` is a subclass of any class in `classes_`, False otherwise.
+ True if `class_obj` is a subclass of any class in `classes_`, `False` otherwise.
"""
return any(
issubclass(class_obj, kls)
diff --git a/libs/core/langchain_core/language_models/_utils.py b/libs/core/langchain_core/language_models/_utils.py
index 48141b5481..453031f677 100644
--- a/libs/core/langchain_core/language_models/_utils.py
+++ b/libs/core/langchain_core/language_models/_utils.py
@@ -35,7 +35,7 @@ def is_openai_data_block(
different type, this function will return False.
Returns:
- True if the block is a valid OpenAI data block and matches the filter_
+ `True` if the block is a valid OpenAI data block and matches the filter_
(if provided).
"""
diff --git a/libs/core/langchain_core/messages/content.py b/libs/core/langchain_core/messages/content.py
index 9f14baea9b..889f58cfe2 100644
--- a/libs/core/langchain_core/messages/content.py
+++ b/libs/core/langchain_core/messages/content.py
@@ -877,7 +877,7 @@ def is_data_content_block(block: dict) -> bool:
block: The content block to check.
Returns:
- True if the content block is a data content block, False otherwise.
+ `True` if the content block is a data content block, `False` otherwise.
"""
if block.get("type") not in _get_data_content_block_types():
diff --git a/libs/core/langchain_core/outputs/llm_result.py b/libs/core/langchain_core/outputs/llm_result.py
index ddb12a77f6..4eb3160f39 100644
--- a/libs/core/langchain_core/outputs/llm_result.py
+++ b/libs/core/langchain_core/outputs/llm_result.py
@@ -97,7 +97,7 @@ class LLMResult(BaseModel):
other: Another `LLMResult` object to compare against.
Returns:
- True if the generations and `llm_output` are equal, False otherwise.
+ `True` if the generations and `llm_output` are equal, `False` otherwise.
"""
if not isinstance(other, LLMResult):
return NotImplemented
diff --git a/libs/core/langchain_core/rate_limiters.py b/libs/core/langchain_core/rate_limiters.py
index dd0753fbc4..d15335679e 100644
--- a/libs/core/langchain_core/rate_limiters.py
+++ b/libs/core/langchain_core/rate_limiters.py
@@ -44,7 +44,7 @@ class BaseRateLimiter(abc.ABC):
the attempt. Defaults to `True`.
Returns:
- True if the tokens were successfully acquired, False otherwise.
+ `True` if the tokens were successfully acquired, `False` otherwise.
"""
@abc.abstractmethod
@@ -63,7 +63,7 @@ class BaseRateLimiter(abc.ABC):
the attempt. Defaults to `True`.
Returns:
- True if the tokens were successfully acquired, False otherwise.
+ `True` if the tokens were successfully acquired, `False` otherwise.
"""
@@ -210,7 +210,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
the attempt. Defaults to `True`.
Returns:
- True if the tokens were successfully acquired, False otherwise.
+ `True` if the tokens were successfully acquired, `False` otherwise.
"""
if not blocking:
return self._consume()
@@ -234,7 +234,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
the attempt. Defaults to `True`.
Returns:
- True if the tokens were successfully acquired, False otherwise.
+ `True` if the tokens were successfully acquired, `False` otherwise.
"""
if not blocking:
return self._consume()
diff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.py
index 6386e223b6..6e3b334120 100644
--- a/libs/core/langchain_core/runnables/graph.py
+++ b/libs/core/langchain_core/runnables/graph.py
@@ -52,7 +52,7 @@ def is_uuid(value: str) -> bool:
value: The string to check.
Returns:
- True if the string is a valid UUID, False otherwise.
+ `True` if the string is a valid UUID, `False` otherwise.
"""
try:
UUID(value)
diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.py
index 448a917ea6..58ca3a7512 100644
--- a/libs/core/langchain_core/runnables/utils.py
+++ b/libs/core/langchain_core/runnables/utils.py
@@ -80,7 +80,7 @@ def accepts_run_manager(callable: Callable[..., Any]) -> bool: # noqa: A002
callable: The callable to check.
Returns:
- True if the callable accepts a run_manager argument, False otherwise.
+ `True` if the callable accepts a run_manager argument, `False` otherwise.
"""
try:
return signature(callable).parameters.get("run_manager") is not None
@@ -95,7 +95,7 @@ def accepts_config(callable: Callable[..., Any]) -> bool: # noqa: A002
callable: The callable to check.
Returns:
- True if the callable accepts a config argument, False otherwise.
+ `True` if the callable accepts a config argument, `False` otherwise.
"""
try:
return signature(callable).parameters.get("config") is not None
@@ -110,7 +110,7 @@ def accepts_context(callable: Callable[..., Any]) -> bool: # noqa: A002
callable: The callable to check.
Returns:
- True if the callable accepts a context argument, False otherwise.
+ `True` if the callable accepts a context argument, `False` otherwise.
"""
try:
return signature(callable).parameters.get("context") is not None
@@ -123,7 +123,7 @@ def asyncio_accepts_context() -> bool:
"""Cache the result of checking if asyncio.create_task accepts a `context` arg.
Returns:
- True if `asyncio.create_task` accepts a context argument, False otherwise.
+ True if `asyncio.create_task` accepts a context argument, `False` otherwise.
"""
return accepts_context(asyncio.create_task)
@@ -727,7 +727,7 @@ def is_async_generator(
func: The function to check.
Returns:
- True if the function is an async generator, False otherwise.
+ `True` if the function is an async generator, `False` otherwise.
"""
return inspect.isasyncgenfunction(func) or (
hasattr(func, "__call__") # noqa: B004
@@ -744,7 +744,7 @@ def is_async_callable(
func: The function to check.
Returns:
- True if the function is async, False otherwise.
+ `True` if the function is async, `False` otherwise.
"""
return asyncio.iscoroutinefunction(func) or (
hasattr(func, "__call__") # noqa: B004
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index ea6e10f81f..5c491b19ba 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -92,7 +92,7 @@ def _is_annotated_type(typ: type[Any]) -> bool:
typ: The type to check.
Returns:
- True if the type is an Annotated type, False otherwise.
+ `True` if the type is an Annotated type, `False` otherwise.
"""
return get_origin(typ) is typing.Annotated
@@ -226,7 +226,7 @@ def _is_pydantic_annotation(annotation: Any, pydantic_version: str = "v2") -> bo
pydantic_version: The Pydantic version to check against ("v1" or "v2").
Returns:
- True if the annotation is a Pydantic model, False otherwise.
+ `True` if the annotation is a Pydantic model, `False` otherwise.
"""
base_model_class = BaseModelV1 if pydantic_version == "v1" else BaseModel
try:
@@ -245,7 +245,7 @@ def _function_annotations_are_pydantic_v1(
func: The function being checked.
Returns:
- True if all Pydantic annotations are from V1, False otherwise.
+ True if all Pydantic annotations are from V1, `False` otherwise.
Raises:
NotImplementedError: If the function contains mixed V1 and V2 annotations.
@@ -517,7 +517,7 @@ class ChildTool(BaseTool):
"""Check if the tool accepts only a single input argument.
Returns:
- True if the tool has only one input argument, False otherwise.
+ `True` if the tool has only one input argument, `False` otherwise.
"""
keys = {k for k in self.args if k != "kwargs"}
return len(keys) == 1
@@ -981,7 +981,7 @@ def _is_tool_call(x: Any) -> bool:
x: The input to check.
Returns:
- True if the input is a tool call, False otherwise.
+ `True` if the input is a tool call, `False` otherwise.
"""
return isinstance(x, dict) and x.get("type") == "tool_call"
@@ -1128,7 +1128,7 @@ def _is_message_content_type(obj: Any) -> bool:
obj: The object to check.
Returns:
- True if the object is valid message content, False otherwise.
+ `True` if the object is valid message content, `False` otherwise.
"""
return isinstance(obj, str) or (
isinstance(obj, list) and all(_is_message_content_block(e) for e in obj)
@@ -1144,7 +1144,7 @@ def _is_message_content_block(obj: Any) -> bool:
obj: The object to check.
Returns:
- True if the object is a valid content block, False otherwise.
+ `True` if the object is a valid content block, `False` otherwise.
"""
if isinstance(obj, str):
return True
@@ -1248,7 +1248,7 @@ def _is_injected_arg_type(
injected_type: The specific injected type to check for.
Returns:
- True if the type is an injected argument, False otherwise.
+ `True` if the type is an injected argument, `False` otherwise.
"""
injected_type = injected_type or InjectedToolArg
return any(
diff --git a/libs/core/langchain_core/tracers/log_stream.py b/libs/core/langchain_core/tracers/log_stream.py
index 65a6a1baf7..da77371dde 100644
--- a/libs/core/langchain_core/tracers/log_stream.py
+++ b/libs/core/langchain_core/tracers/log_stream.py
@@ -190,7 +190,7 @@ class RunLog(RunLogPatch):
other: The other `RunLog` to compare to.
Returns:
- True if the `RunLog`s are equal, False otherwise.
+ `True` if the `RunLog`s are equal, `False` otherwise.
"""
# First compare that the state is the same
if not isinstance(other, RunLog):
@@ -288,7 +288,7 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
*ops: The operations to send to the stream.
Returns:
- True if the patch was sent successfully, False if the stream is closed.
+ `True` if the patch was sent successfully, False if the stream is closed.
"""
# We will likely want to wrap this in try / except at some point
# to handle exceptions that might arise at run time.
@@ -368,7 +368,7 @@ class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
run: The Run to check.
Returns:
- True if the run should be included, False otherwise.
+ `True` if the run should be included, `False` otherwise.
"""
if run.id == self.root_id:
return False
diff --git a/libs/core/langchain_core/utils/env.py b/libs/core/langchain_core/utils/env.py
index 9af2179dfe..f19928e876 100644
--- a/libs/core/langchain_core/utils/env.py
+++ b/libs/core/langchain_core/utils/env.py
@@ -13,7 +13,7 @@ def env_var_is_set(env_var: str) -> bool:
env_var: The name of the environment variable.
Returns:
- True if the environment variable is set, False otherwise.
+ `True` if the environment variable is set, `False` otherwise.
"""
return env_var in os.environ and os.environ[env_var] not in {
"",
diff --git a/libs/core/langchain_core/utils/interactive_env.py b/libs/core/langchain_core/utils/interactive_env.py
index 305b8edc14..f86fe0763b 100644
--- a/libs/core/langchain_core/utils/interactive_env.py
+++ b/libs/core/langchain_core/utils/interactive_env.py
@@ -7,6 +7,6 @@ def is_interactive_env() -> bool:
"""Determine if running within IPython or Jupyter.
Returns:
- True if running in an interactive environment, False otherwise.
+ True if running in an interactive environment, `False` otherwise.
"""
return hasattr(sys, "ps2")
diff --git a/libs/core/langchain_core/utils/pydantic.py b/libs/core/langchain_core/utils/pydantic.py
index b0c58048a8..9d3b228a59 100644
--- a/libs/core/langchain_core/utils/pydantic.py
+++ b/libs/core/langchain_core/utils/pydantic.py
@@ -78,7 +78,7 @@ def is_pydantic_v1_subclass(cls: type) -> bool:
"""Check if the given class is Pydantic v1-like.
Returns:
- True if the given class is a subclass of Pydantic `BaseModel` 1.x.
+ `True` if the given class is a subclass of Pydantic `BaseModel` 1.x.
"""
return issubclass(cls, BaseModelV1)
@@ -87,7 +87,7 @@ def is_pydantic_v2_subclass(cls: type) -> bool:
"""Check if the given class is Pydantic v2-like.
Returns:
- True if the given class is a subclass of Pydantic BaseModel 2.x.
+ `True` if the given class is a subclass of Pydantic BaseModel 2.x.
"""
return issubclass(cls, BaseModel)
@@ -101,7 +101,7 @@ def is_basemodel_subclass(cls: type) -> bool:
* pydantic.v1.BaseModel in Pydantic 2.x
Returns:
- True if the given class is a subclass of Pydantic `BaseModel`.
+ `True` if the given class is a subclass of Pydantic `BaseModel`.
"""
# Before we can use issubclass on the cls we need to check if it is a class
if not inspect.isclass(cls) or isinstance(cls, GenericAlias):
@@ -119,7 +119,7 @@ def is_basemodel_instance(obj: Any) -> bool:
* pydantic.v1.BaseModel in Pydantic 2.x
Returns:
- True if the given class is an instance of Pydantic `BaseModel`.
+ `True` if the given class is an instance of Pydantic `BaseModel`.
"""
return isinstance(obj, (BaseModel, BaseModelV1))
diff --git a/libs/core/tests/unit_tests/language_models/chat_models/test_base.py b/libs/core/tests/unit_tests/language_models/chat_models/test_base.py
index 3d8e03b5e7..7ab177ce48 100644
--- a/libs/core/tests/unit_tests/language_models/chat_models/test_base.py
+++ b/libs/core/tests/unit_tests/language_models/chat_models/test_base.py
@@ -57,7 +57,7 @@ def _content_blocks_equal_ignore_id(
expected: Expected content to compare against (string or list of blocks).
Returns:
- True if content matches (excluding `id` fields), False otherwise.
+ True if content matches (excluding `id` fields), `False` otherwise.
"""
if isinstance(actual, str) or isinstance(expected, str):
diff --git a/libs/langchain/langchain_classic/agents/agent.py b/libs/langchain/langchain_classic/agents/agent.py
index 4984573fa0..452f6df4a7 100644
--- a/libs/langchain/langchain_classic/agents/agent.py
+++ b/libs/langchain/langchain_classic/agents/agent.py
@@ -124,7 +124,7 @@ class BaseSingleActionAgent(BaseModel):
along with observations.
Returns:
- AgentFinish: Agent finish object.
+ Agent finish object.
Raises:
ValueError: If `early_stopping_method` is not supported.
@@ -155,7 +155,7 @@ class BaseSingleActionAgent(BaseModel):
kwargs: Additional arguments.
Returns:
- BaseSingleActionAgent: Agent object.
+ Agent object.
"""
raise NotImplementedError
@@ -169,7 +169,7 @@ class BaseSingleActionAgent(BaseModel):
"""Return dictionary representation of agent.
Returns:
- Dict: Dictionary representation of agent.
+ Dictionary representation of agent.
"""
_dict = super().model_dump()
try:
@@ -233,7 +233,7 @@ class BaseMultiActionAgent(BaseModel):
"""Get allowed tools.
Returns:
- list[str] | None: Allowed tools.
+ Allowed tools.
"""
return None
@@ -297,7 +297,7 @@ class BaseMultiActionAgent(BaseModel):
along with observations.
Returns:
- AgentFinish: Agent finish object.
+ Agent finish object.
Raises:
ValueError: If `early_stopping_method` is not supported.
@@ -388,8 +388,7 @@ class MultiActionAgentOutputParser(
text: Text to parse.
Returns:
- Union[List[AgentAction], AgentFinish]:
- List of agent actions or agent finish.
+ List of agent actions or agent finish.
"""
@@ -812,7 +811,7 @@ class Agent(BaseSingleActionAgent):
**kwargs: User inputs.
Returns:
- Dict[str, Any]: Full inputs for the LLMChain.
+ Full inputs for the LLMChain.
"""
thoughts = self._construct_scratchpad(intermediate_steps)
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
@@ -834,7 +833,7 @@ class Agent(BaseSingleActionAgent):
values: Values to validate.
Returns:
- Dict: Validated values.
+ Validated values.
Raises:
ValueError: If `agent_scratchpad` is not in prompt.input_variables
@@ -875,7 +874,7 @@ class Agent(BaseSingleActionAgent):
tools: Tools to use.
Returns:
- BasePromptTemplate: Prompt template.
+ Prompt template.
"""
@classmethod
@@ -910,7 +909,7 @@ class Agent(BaseSingleActionAgent):
kwargs: Additional arguments.
Returns:
- Agent: Agent object.
+ Agent object.
"""
cls._validate_tools(tools)
llm_chain = LLMChain(
@@ -942,7 +941,7 @@ class Agent(BaseSingleActionAgent):
**kwargs: User inputs.
Returns:
- AgentFinish: Agent finish object.
+ Agent finish object.
Raises:
ValueError: If `early_stopping_method` is not in ['force', 'generate'].
@@ -1082,7 +1081,7 @@ class AgentExecutor(Chain):
kwargs: Additional arguments.
Returns:
- AgentExecutor: Agent executor object.
+ Agent executor object.
"""
return cls(
agent=agent,
@@ -1099,7 +1098,7 @@ class AgentExecutor(Chain):
values: Values to validate.
Returns:
- Dict: Validated values.
+ Validated values.
Raises:
ValueError: If allowed tools are different than provided tools.
@@ -1126,7 +1125,7 @@ class AgentExecutor(Chain):
values: Values to validate.
Returns:
- Dict: Validated values.
+ Validated values.
"""
agent = values.get("agent")
if agent and isinstance(agent, Runnable):
@@ -1209,7 +1208,7 @@ class AgentExecutor(Chain):
async_: Whether to run async. (Ignored)
Returns:
- AgentExecutorIterator: Agent executor iterator object.
+ Agent executor iterator object.
"""
return AgentExecutorIterator(
self,
@@ -1244,7 +1243,7 @@ class AgentExecutor(Chain):
name: Name of tool.
Returns:
- BaseTool: Tool object.
+ Tool object.
"""
return {tool.name: tool for tool in self.tools}[name]
@@ -1759,7 +1758,7 @@ class AgentExecutor(Chain):
kwargs: Additional arguments.
Yields:
- AddableDict: Addable dictionary.
+ Addable dictionary.
"""
config = ensure_config(config)
iterator = AgentExecutorIterator(
@@ -1790,7 +1789,7 @@ class AgentExecutor(Chain):
kwargs: Additional arguments.
Yields:
- AddableDict: Addable dictionary.
+ Addable dictionary.
"""
config = ensure_config(config)
iterator = AgentExecutorIterator(
diff --git a/libs/langchain/langchain_classic/agents/format_scratchpad/log.py b/libs/langchain/langchain_classic/agents/format_scratchpad/log.py
index bf24a96a67..a3672f817b 100644
--- a/libs/langchain/langchain_classic/agents/format_scratchpad/log.py
+++ b/libs/langchain/langchain_classic/agents/format_scratchpad/log.py
@@ -16,7 +16,7 @@ def format_log_to_str(
Defaults to "Thought: ".
Returns:
- str: The scratchpad.
+ The scratchpad.
"""
thoughts = ""
for action, observation in intermediate_steps:
diff --git a/libs/langchain/langchain_classic/agents/format_scratchpad/log_to_messages.py b/libs/langchain/langchain_classic/agents/format_scratchpad/log_to_messages.py
index a193e37ae3..650e58572a 100644
--- a/libs/langchain/langchain_classic/agents/format_scratchpad/log_to_messages.py
+++ b/libs/langchain/langchain_classic/agents/format_scratchpad/log_to_messages.py
@@ -14,7 +14,7 @@ def format_log_to_messages(
Defaults to "{observation}".
Returns:
- List[BaseMessage]: The scratchpad.
+ The scratchpad.
"""
thoughts: list[BaseMessage] = []
for action, observation in intermediate_steps:
diff --git a/libs/langchain/langchain_classic/chains/api/base.py b/libs/langchain/langchain_classic/chains/api/base.py
index 955e52fd5e..ee2e13b231 100644
--- a/libs/langchain/langchain_classic/chains/api/base.py
+++ b/libs/langchain/langchain_classic/chains/api/base.py
@@ -42,7 +42,7 @@ def _check_in_allowed_domain(url: str, limit_to_domains: Sequence[str]) -> bool:
limit_to_domains: The allowed domains.
Returns:
- True if the URL is in the allowed domains, False otherwise.
+ `True` if the URL is in the allowed domains, `False` otherwise.
"""
scheme, domain = _extract_scheme_and_domain(url)
diff --git a/libs/langchain/langchain_classic/chains/prompt_selector.py b/libs/langchain/langchain_classic/chains/prompt_selector.py
index bb8665b9fc..431b8df33f 100644
--- a/libs/langchain/langchain_classic/chains/prompt_selector.py
+++ b/libs/langchain/langchain_classic/chains/prompt_selector.py
@@ -48,7 +48,7 @@ def is_llm(llm: BaseLanguageModel) -> bool:
llm: Language model to check.
Returns:
- True if the language model is a BaseLLM model, False otherwise.
+ `True` if the language model is a BaseLLM model, `False` otherwise.
"""
return isinstance(llm, BaseLLM)
@@ -60,6 +60,6 @@ def is_chat_model(llm: BaseLanguageModel) -> bool:
llm: Language model to check.
Returns:
- True if the language model is a BaseChatModel model, False otherwise.
+ `True` if the language model is a BaseChatModel model, `False` otherwise.
"""
return isinstance(llm, BaseChatModel)
diff --git a/libs/langchain/langchain_classic/chains/query_constructor/parser.py b/libs/langchain/langchain_classic/chains/query_constructor/parser.py
index d7e4de680e..2bc4d3a05c 100644
--- a/libs/langchain/langchain_classic/chains/query_constructor/parser.py
+++ b/libs/langchain/langchain_classic/chains/query_constructor/parser.py
@@ -112,7 +112,7 @@ class QueryTransformer(Transformer):
args: The arguments passed to the function.
Returns:
- FilterDirective: The filter directive.
+ The filter directive.
Raises:
ValueError: If the function is a comparator and the first arg is not in the
diff --git a/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py b/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py
index e4cd9410d1..a8b364028c 100644
--- a/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py
+++ b/libs/langchain/langchain_classic/evaluation/agents/trajectory_eval_chain.py
@@ -165,7 +165,7 @@ class TrajectoryEvalChain(AgentTrajectoryEvaluator, LLMEvalChain):
"""Get the description of the agent tools.
Returns:
- str: The description of the agent tools.
+ The description of the agent tools.
"""
if self.agent_tools is None:
return ""
@@ -184,10 +184,10 @@ Description: {tool.description}"""
"""Get the agent trajectory as a formatted string.
Args:
- steps (Union[str, List[Tuple[AgentAction, str]]]): The agent trajectory.
+ steps: The agent trajectory.
Returns:
- str: The formatted agent trajectory.
+ The formatted agent trajectory.
"""
if isinstance(steps, str):
return steps
@@ -240,7 +240,7 @@ The following is the expected answer. Use this to measure correctness:
**kwargs: Additional keyword arguments.
Returns:
- TrajectoryEvalChain: The TrajectoryEvalChain object.
+ The `TrajectoryEvalChain` object.
"""
if not isinstance(llm, BaseChatModel):
msg = "Only chat models supported by the current trajectory eval"
@@ -259,7 +259,7 @@ The following is the expected answer. Use this to measure correctness:
"""Get the input keys for the chain.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["question", "agent_trajectory", "answer", "reference"]
@@ -268,7 +268,7 @@ The following is the expected answer. Use this to measure correctness:
"""Get the output keys for the chain.
Returns:
- List[str]: The output keys.
+ The output keys.
"""
return ["score", "reasoning"]
@@ -289,7 +289,7 @@ The following is the expected answer. Use this to measure correctness:
run_manager: The callback manager for the chain run.
Returns:
- Dict[str, Any]: The output values of the chain.
+ The output values of the chain.
"""
chain_input = {**inputs}
if self.agent_tools:
@@ -313,7 +313,7 @@ The following is the expected answer. Use this to measure correctness:
run_manager: The callback manager for the chain run.
Returns:
- Dict[str, Any]: The output values of the chain.
+ The output values of the chain.
"""
chain_input = {**inputs}
if self.agent_tools:
diff --git a/libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py b/libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py
index 51ef0838cb..ab83aa46c4 100644
--- a/libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py
+++ b/libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py
@@ -207,7 +207,7 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
"""Return whether the chain requires a reference.
Returns:
- True if the chain requires a reference, False otherwise.
+ `True` if the chain requires a reference, `False` otherwise.
"""
return False
@@ -217,7 +217,7 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
"""Return whether the chain requires an input.
Returns:
- bool: True if the chain requires an input, False otherwise.
+ `True` if the chain requires an input, `False` otherwise.
"""
return True
@@ -227,7 +227,7 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
"""Return the warning to show when reference is ignored.
Returns:
- str: The warning to show when reference is ignored.
+ The warning to show when reference is ignored.
"""
return (
@@ -425,7 +425,7 @@ class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain):
"""Return whether the chain requires a reference.
Returns:
- bool: True if the chain requires a reference, False otherwise.
+ `True` if the chain requires a reference, `False` otherwise.
"""
return True
@@ -442,18 +442,18 @@ class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain):
"""Initialize the LabeledPairwiseStringEvalChain from an LLM.
Args:
- llm (BaseLanguageModel): The LLM to use.
- prompt (PromptTemplate, optional): The prompt to use.
- criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.
- **kwargs (Any): Additional keyword arguments.
+ llm: The LLM to use.
+ prompt: The prompt to use.
+ criteria: The criteria to use.
+ **kwargs: Additional keyword arguments.
Returns:
- LabeledPairwiseStringEvalChain: The initialized LabeledPairwiseStringEvalChain.
+ The initialized `LabeledPairwiseStringEvalChain`.
Raises:
ValueError: If the input variables are not as expected.
- """ # noqa: E501
+ """
expected_input_vars = {
"prediction",
"prediction_b",
diff --git a/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py b/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py
index 58b7f032ff..46b13eb7ed 100644
--- a/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py
+++ b/libs/langchain/langchain_classic/evaluation/embedding_distance/base.py
@@ -51,7 +51,7 @@ def _embedding_factory() -> Embeddings:
"""Create an Embeddings object.
Returns:
- Embeddings: The created Embeddings object.
+ The created `Embeddings` object.
"""
# Here for backwards compatibility.
# Generally, we do not want to be seeing imports from langchain community
@@ -94,9 +94,8 @@ class _EmbeddingDistanceChainMixin(Chain):
"""Shared functionality for embedding distance evaluators.
Attributes:
- embeddings (Embeddings): The embedding objects to vectorize the outputs.
- distance_metric (EmbeddingDistance): The distance metric to use
- for comparing the embeddings.
+ embeddings: The embedding objects to vectorize the outputs.
+ distance_metric: The distance metric to use for comparing the embeddings.
"""
embeddings: Embeddings = Field(default_factory=_embedding_factory)
@@ -107,10 +106,10 @@ class _EmbeddingDistanceChainMixin(Chain):
"""Validate that the TikTok library is installed.
Args:
- values (Dict[str, Any]): The values to validate.
+ values: The values to validate.
Returns:
- Dict[str, Any]: The validated values.
+ The validated values.
"""
embeddings = values.get("embeddings")
types_ = []
@@ -159,7 +158,7 @@ class _EmbeddingDistanceChainMixin(Chain):
"""Return the output keys of the chain.
Returns:
- List[str]: The output keys.
+ The output keys.
"""
return ["score"]
@@ -173,10 +172,10 @@ class _EmbeddingDistanceChainMixin(Chain):
"""Get the metric function for the given metric name.
Args:
- metric (EmbeddingDistance): The metric name.
+ metric: The metric name.
Returns:
- Any: The metric function.
+ The metric function.
"""
metrics = {
EmbeddingDistance.COSINE: self._cosine_distance,
@@ -334,7 +333,7 @@ class _EmbeddingDistanceChainMixin(Chain):
vectors (np.ndarray): The input vectors.
Returns:
- float: The computed score.
+ The computed score.
"""
metric = self._get_metric(self.distance_metric)
if _check_numpy() and isinstance(vectors, _import_numpy().ndarray):
@@ -362,7 +361,7 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):
"""Return whether the chain requires a reference.
Returns:
- bool: True if a reference is required, False otherwise.
+ True if a reference is required, `False` otherwise.
"""
return True
@@ -376,7 +375,7 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):
"""Return the input keys of the chain.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["prediction", "reference"]
@@ -393,7 +392,7 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):
run_manager: The callback manager.
Returns:
- Dict[str, Any]: The computed score.
+ The computed score.
"""
vectors = self.embeddings.embed_documents(
[inputs["prediction"], inputs["reference"]],
@@ -413,12 +412,11 @@ class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):
"""Asynchronously compute the score for a prediction and reference.
Args:
- inputs (Dict[str, Any]): The input data.
- run_manager (AsyncCallbackManagerForChainRun, optional):
- The callback manager.
+ inputs: The input data.
+ run_manager: The callback manager.
Returns:
- Dict[str, Any]: The computed score.
+ The computed score.
"""
vectors = await self.embeddings.aembed_documents(
[
@@ -523,7 +521,7 @@ class PairwiseEmbeddingDistanceEvalChain(
"""Return the input keys of the chain.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["prediction", "prediction_b"]
@@ -541,12 +539,11 @@ class PairwiseEmbeddingDistanceEvalChain(
"""Compute the score for two predictions.
Args:
- inputs (Dict[str, Any]): The input data.
- run_manager (CallbackManagerForChainRun, optional):
- The callback manager.
+ inputs: The input data.
+ run_manager: The callback manager.
Returns:
- Dict[str, Any]: The computed score.
+ The computed score.
"""
vectors = self.embeddings.embed_documents(
[
@@ -569,12 +566,11 @@ class PairwiseEmbeddingDistanceEvalChain(
"""Asynchronously compute the score for two predictions.
Args:
- inputs (Dict[str, Any]): The input data.
- run_manager (AsyncCallbackManagerForChainRun, optional):
- The callback manager.
+ inputs: The input data.
+ run_manager: The callback manager.
Returns:
- Dict[str, Any]: The computed score.
+ The computed score.
"""
vectors = await self.embeddings.aembed_documents(
[
diff --git a/libs/langchain/langchain_classic/evaluation/exact_match/base.py b/libs/langchain/langchain_classic/evaluation/exact_match/base.py
index b555d932b7..93ebad7daa 100644
--- a/libs/langchain/langchain_classic/evaluation/exact_match/base.py
+++ b/libs/langchain/langchain_classic/evaluation/exact_match/base.py
@@ -61,7 +61,7 @@ class ExactMatchStringEvaluator(StringEvaluator):
"""Get the input keys.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["reference", "prediction"]
@@ -70,7 +70,7 @@ class ExactMatchStringEvaluator(StringEvaluator):
"""Get the evaluation name.
Returns:
- str: The evaluation name.
+ The evaluation name.
"""
return "exact_match"
diff --git a/libs/langchain/langchain_classic/evaluation/parsing/base.py b/libs/langchain/langchain_classic/evaluation/parsing/base.py
index 9814179009..ab23325383 100644
--- a/libs/langchain/langchain_classic/evaluation/parsing/base.py
+++ b/libs/langchain/langchain_classic/evaluation/parsing/base.py
@@ -71,10 +71,11 @@ class JsonValidityEvaluator(StringEvaluator):
**kwargs: Additional keyword arguments (not used).
Returns:
- dict: A dictionary containing the evaluation score. The score is 1 if
- the prediction is valid JSON, and 0 otherwise.
- If the prediction is not valid JSON, the dictionary also contains
- a "reasoning" field with the error message.
+ A dictionary containing the evaluation score. The score is `1` if
+ the prediction is valid JSON, and `0` otherwise.
+
+ If the prediction is not valid JSON, the dictionary also contains
+ a `reasoning` field with the error message.
"""
try:
diff --git a/libs/langchain/langchain_classic/evaluation/parsing/json_distance.py b/libs/langchain/langchain_classic/evaluation/parsing/json_distance.py
index b1167cd40c..057b8d4e1f 100644
--- a/libs/langchain/langchain_classic/evaluation/parsing/json_distance.py
+++ b/libs/langchain/langchain_classic/evaluation/parsing/json_distance.py
@@ -50,7 +50,7 @@ class JsonEditDistanceEvaluator(StringEvaluator):
Raises:
ImportError: If the `rapidfuzz` package is not installed and no
- `string_distance` function is provided.
+ `string_distance` function is provided.
"""
super().__init__()
if string_distance is not None:
diff --git a/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py b/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py
index 189a2f5321..b1388fc380 100644
--- a/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py
+++ b/libs/langchain/langchain_classic/evaluation/qa/eval_chain.py
@@ -113,17 +113,16 @@ class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
"""Load QA Eval Chain from LLM.
Args:
- llm (BaseLanguageModel): the base language model to use.
+ llm: The base language model to use.
+ prompt: A prompt template containing the input_variables:
+ `'input'`, `'answer'` and `'result'` that will be used as the prompt
+ for evaluation.
- prompt (PromptTemplate): A prompt template containing the input_variables:
- 'input', 'answer' and 'result' that will be used as the prompt
- for evaluation.
- Defaults to PROMPT.
-
- **kwargs: additional keyword arguments.
+ Defaults to `PROMPT`.
+ **kwargs: Additional keyword arguments.
Returns:
- QAEvalChain: the loaded QA eval chain.
+ The loaded QA eval chain.
"""
prompt = prompt or PROMPT
expected_input_vars = {"query", "answer", "result"}
@@ -264,17 +263,16 @@ class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
"""Load QA Eval Chain from LLM.
Args:
- llm (BaseLanguageModel): the base language model to use.
-
- prompt (PromptTemplate): A prompt template containing the input_variables:
- 'query', 'context' and 'result' that will be used as the prompt
- for evaluation.
- Defaults to PROMPT.
+ llm: The base language model to use.
+ prompt: A prompt template containing the `input_variables`:
+ `'query'`, `'context'` and `'result'` that will be used as the prompt
+ for evaluation.
- **kwargs: additional keyword arguments.
+ Defaults to `PROMPT`.
+ **kwargs: Additional keyword arguments.
Returns:
- ContextQAEvalChain: the loaded QA eval chain.
+ The loaded QA eval chain.
"""
prompt = prompt or CONTEXT_PROMPT
cls._validate_input_vars(prompt)
diff --git a/libs/langchain/langchain_classic/evaluation/regex_match/base.py b/libs/langchain/langchain_classic/evaluation/regex_match/base.py
index 23afa56ae4..40b16085ef 100644
--- a/libs/langchain/langchain_classic/evaluation/regex_match/base.py
+++ b/libs/langchain/langchain_classic/evaluation/regex_match/base.py
@@ -53,7 +53,7 @@ class RegexMatchStringEvaluator(StringEvaluator):
"""Get the input keys.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["reference", "prediction"]
@@ -62,7 +62,7 @@ class RegexMatchStringEvaluator(StringEvaluator):
"""Get the evaluation name.
Returns:
- str: The evaluation name.
+ The evaluation name.
"""
return "regex_match"
diff --git a/libs/langchain/langchain_classic/evaluation/schema.py b/libs/langchain/langchain_classic/evaluation/schema.py
index 25d2b0b028..3bb4d2e12d 100644
--- a/libs/langchain/langchain_classic/evaluation/schema.py
+++ b/libs/langchain/langchain_classic/evaluation/schema.py
@@ -114,8 +114,8 @@ class _EvalArgsMixin:
"""Check if the evaluation arguments are valid.
Args:
- reference (str | None, optional): The reference label.
- input_ (str | None, optional): The input string.
+ reference: The reference label.
+ input_: The input string.
Raises:
ValueError: If the evaluator requires an input string but none is provided,
@@ -162,17 +162,17 @@ class StringEvaluator(_EvalArgsMixin, ABC):
"""Evaluate Chain or LLM output, based on optional input and label.
Args:
- prediction (str): The LLM or chain prediction to evaluate.
- reference (str | None, optional): The reference label to evaluate against.
- input (str | None, optional): The input to consider during evaluation.
- kwargs: Additional keyword arguments, including callbacks, tags, etc.
+ prediction: The LLM or chain prediction to evaluate.
+ reference: The reference label to evaluate against.
+ input: 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:
- - score: the score of the evaluation, if applicable.
- - value: the string value of the evaluation, if applicable.
- - reasoning: the reasoning for the evaluation, if applicable.
+ The evaluation results containing the score or value.
+ It is recommended that the dictionary contain the following keys:
+ - score: the score of the evaluation, if applicable.
+ - value: the string value of the evaluation, if applicable.
+ - reasoning: the reasoning for the evaluation, if applicable.
"""
async def _aevaluate_strings(
@@ -186,17 +186,17 @@ class StringEvaluator(_EvalArgsMixin, ABC):
"""Asynchronously evaluate Chain or LLM output, based on optional input and label.
Args:
- prediction (str): The LLM or chain prediction to evaluate.
- reference (str | None, optional): The reference label to evaluate against.
- input (str | None, optional): The input to consider during evaluation.
- kwargs: Additional keyword arguments, including callbacks, tags, etc.
+ prediction: The LLM or chain prediction to evaluate.
+ reference: The reference label to evaluate against.
+ input: 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:
- - score: the score of the evaluation, if applicable.
- - value: the string value of the evaluation, if applicable.
- - reasoning: the reasoning for the evaluation, if applicable.
+ The evaluation results containing the score or value.
+ It is recommended that the dictionary contain the following keys:
+ - score: the score of the evaluation, if applicable.
+ - value: the string value of the evaluation, if applicable.
+ - reasoning: the reasoning for the evaluation, if applicable.
""" # noqa: E501
return await run_in_executor(
None,
@@ -218,13 +218,13 @@ class StringEvaluator(_EvalArgsMixin, ABC):
"""Evaluate Chain or LLM output, based on optional input and label.
Args:
- prediction (str): The LLM or chain prediction to evaluate.
- reference (str | None, optional): The reference label to evaluate against.
- input (str | None, optional): The input to consider during evaluation.
- kwargs: Additional keyword arguments, including callbacks, tags, etc.
+ prediction: The LLM or chain prediction to evaluate.
+ reference: The reference label to evaluate against.
+ input: The input to consider during evaluation.
+ **kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
- dict: The evaluation results containing the score or value.
+ The evaluation results containing the score or value.
"""
self._check_evaluation_args(reference=reference, input_=input)
return self._evaluate_strings(
@@ -245,13 +245,13 @@ class StringEvaluator(_EvalArgsMixin, ABC):
"""Asynchronously evaluate Chain or LLM output, based on optional input and label.
Args:
- prediction (str): The LLM or chain prediction to evaluate.
- reference (str | None, optional): The reference label to evaluate against.
- input (str | None, optional): The input to consider during evaluation.
- kwargs: Additional keyword arguments, including callbacks, tags, etc.
+ prediction: The LLM or chain prediction to evaluate.
+ reference: The reference label to evaluate against.
+ input: The input to consider during evaluation.
+ **kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
- dict: The evaluation results containing the score or value.
+ The evaluation results containing the score or value.
""" # noqa: E501
self._check_evaluation_args(reference=reference, input_=input)
return await self._aevaluate_strings(
@@ -278,14 +278,14 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
"""Evaluate the output string pairs.
Args:
- prediction (str): The output string from the first model.
- prediction_b (str): The output string from the second model.
- reference (str | None, optional): The expected output / reference string.
- input (str | None, optional): The input string.
- kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
+ prediction: The output string from the first model.
+ prediction_b: The output string from the second model.
+ reference: The expected output / reference string.
+ input: 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.
+ A dictionary containing the preference, scores, and/or other information.
""" # noqa: E501
async def _aevaluate_string_pairs(
@@ -300,14 +300,14 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
"""Asynchronously evaluate the output string pairs.
Args:
- prediction (str): The output string from the first model.
- prediction_b (str): The output string from the second model.
- reference (str | None, optional): The expected output / reference string.
- input (str | None, optional): The input string.
- kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
+ prediction: The output string from the first model.
+ prediction_b: The output string from the second model.
+ reference: The expected output / reference string.
+ input: 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.
+ A dictionary containing the preference, scores, and/or other information.
""" # noqa: E501
return await run_in_executor(
None,
@@ -331,14 +331,14 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
"""Evaluate the output string pairs.
Args:
- prediction (str): The output string from the first model.
- prediction_b (str): The output string from the second model.
- reference (str | None, optional): The expected output / reference string.
- input (str | None, optional): The input string.
- kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
+ prediction: The output string from the first model.
+ prediction_b: The output string from the second model.
+ reference: The expected output / reference string.
+ input: 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.
+ A dictionary containing the preference, scores, and/or other information.
""" # noqa: E501
self._check_evaluation_args(reference=reference, input_=input)
return self._evaluate_string_pairs(
@@ -361,14 +361,14 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
"""Asynchronously evaluate the output string pairs.
Args:
- prediction (str): The output string from the first model.
- prediction_b (str): The output string from the second model.
- reference (str | None, optional): The expected output / reference string.
- input (str | None, optional): The input string.
- kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
+ prediction: The output string from the first model.
+ prediction_b: The output string from the second model.
+ reference: The expected output / reference string.
+ input: 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.
+ A dictionary containing the preference, scores, and/or other information.
""" # noqa: E501
self._check_evaluation_args(reference=reference, input_=input)
return await self._aevaluate_string_pairs(
diff --git a/libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py b/libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py
index cbc01d75bd..93c412af61 100644
--- a/libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py
+++ b/libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py
@@ -56,10 +56,10 @@ def resolve_criteria(
"""Resolve the criteria for the pairwise evaluator.
Args:
- criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.
+ criteria: The criteria to use.
Returns:
- dict: The resolved criteria.
+ The resolved criteria.
"""
if criteria is None:
@@ -196,7 +196,7 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
"""Return whether the chain requires a reference.
Returns:
- bool: True if the chain requires a reference, False otherwise.
+ `True` if the chain requires a reference, `False` otherwise.
"""
return False
@@ -206,7 +206,7 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
"""Return whether the chain requires an input.
Returns:
- bool: True if the chain requires an input, False otherwise.
+ `True` if the chain requires an input, `False` otherwise.
"""
return True
@@ -227,7 +227,7 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
"""Return the warning to show when reference is ignored.
Returns:
- str: The warning to show when reference is ignored.
+ The warning to show when reference is ignored.
"""
return (
@@ -424,7 +424,7 @@ class LabeledScoreStringEvalChain(ScoreStringEvalChain):
"""Return whether the chain requires a reference.
Returns:
- bool: True if the chain requires a reference, False otherwise.
+ `True` if the chain requires a reference, `False` otherwise.
"""
return True
@@ -442,14 +442,14 @@ class LabeledScoreStringEvalChain(ScoreStringEvalChain):
"""Initialize the LabeledScoreStringEvalChain from an LLM.
Args:
- llm (BaseLanguageModel): The LLM to use.
- prompt (PromptTemplate, optional): The prompt to use.
- criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.
- normalize_by (float, optional): The value to normalize the score by.
- **kwargs (Any): Additional keyword arguments.
+ llm: The LLM to use.
+ prompt: The prompt to use.
+ criteria: The criteria to use.
+ normalize_by: The value to normalize the score by.
+ **kwargs: Additional keyword arguments.
Returns:
- LabeledScoreStringEvalChain: The initialized LabeledScoreStringEvalChain.
+ The initialized LabeledScoreStringEvalChain.
Raises:
ValueError: If the input variables are not as expected.
diff --git a/libs/langchain/langchain_classic/evaluation/string_distance/base.py b/libs/langchain/langchain_classic/evaluation/string_distance/base.py
index e8d5c06fa9..ee72d93328 100644
--- a/libs/langchain/langchain_classic/evaluation/string_distance/base.py
+++ b/libs/langchain/langchain_classic/evaluation/string_distance/base.py
@@ -22,10 +22,10 @@ def _load_rapidfuzz() -> Any:
"""Load the RapidFuzz library.
Raises:
- ImportError: If the rapidfuzz library is not installed.
+ `ImportError`: If the rapidfuzz library is not installed.
Returns:
- Any: The rapidfuzz.distance module.
+ The `rapidfuzz.distance` module.
"""
try:
import rapidfuzz
@@ -42,12 +42,12 @@ class StringDistance(str, Enum):
"""Distance metric to use.
Attributes:
- DAMERAU_LEVENSHTEIN: The Damerau-Levenshtein distance.
- LEVENSHTEIN: The Levenshtein distance.
- JARO: The Jaro distance.
- JARO_WINKLER: The Jaro-Winkler distance.
- HAMMING: The Hamming distance.
- INDEL: The Indel distance.
+ `DAMERAU_LEVENSHTEIN`: The Damerau-Levenshtein distance.
+ `LEVENSHTEIN`: The Levenshtein distance.
+ `JARO`: The Jaro distance.
+ `JARO_WINKLER`: The Jaro-Winkler distance.
+ `HAMMING`: The Hamming distance.
+ `INDEL`: The Indel distance.
"""
DAMERAU_LEVENSHTEIN = "damerau_levenshtein"
@@ -63,7 +63,7 @@ class _RapidFuzzChainMixin(Chain):
distance: StringDistance = Field(default=StringDistance.JARO_WINKLER)
normalize_score: bool = Field(default=True)
- """Whether to normalize the score to a value between 0 and 1.
+ """Whether to normalize the score to a value between `0` and `1`.
Applies only to the Levenshtein and Damerau-Levenshtein distances."""
@pre_init
@@ -71,10 +71,10 @@ class _RapidFuzzChainMixin(Chain):
"""Validate that the rapidfuzz library is installed.
Args:
- values (Dict[str, Any]): The input values.
+ values: The input values.
Returns:
- Dict[str, Any]: The validated values.
+ The validated values.
"""
_load_rapidfuzz()
return values
@@ -84,7 +84,7 @@ class _RapidFuzzChainMixin(Chain):
"""Get the output keys.
Returns:
- List[str]: The output keys.
+ The output keys.
"""
return ["score"]
@@ -92,10 +92,10 @@ class _RapidFuzzChainMixin(Chain):
"""Prepare the output dictionary.
Args:
- result (Dict[str, Any]): The evaluation results.
+ result: The evaluation results.
Returns:
- Dict[str, Any]: The prepared output dictionary.
+ The prepared output dictionary.
"""
result = {"score": result["score"]}
if RUN_KEY in result:
@@ -111,7 +111,7 @@ class _RapidFuzzChainMixin(Chain):
normalize_score: Whether to normalize the score.
Returns:
- Callable: The distance metric function.
+ The distance metric function.
Raises:
ValueError: If the distance metric is invalid.
@@ -142,7 +142,7 @@ class _RapidFuzzChainMixin(Chain):
"""Get the distance metric function.
Returns:
- Callable: The distance metric function.
+ The distance metric function.
"""
return _RapidFuzzChainMixin._get_metric(
self.distance,
@@ -199,7 +199,7 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):
"""Get the input keys.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["reference", "prediction"]
@@ -208,7 +208,7 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):
"""Get the evaluation name.
Returns:
- str: The evaluation name.
+ The evaluation name.
"""
return f"{self.distance.value}_distance"
@@ -330,7 +330,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi
"""Get the input keys.
Returns:
- List[str]: The input keys.
+ The input keys.
"""
return ["prediction", "prediction_b"]
@@ -339,7 +339,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi
"""Get the evaluation name.
Returns:
- str: The evaluation name.
+ The evaluation name.
"""
return f"pairwise_{self.distance.value}_distance"
@@ -352,12 +352,11 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi
"""Compute the string distance between two predictions.
Args:
- inputs (Dict[str, Any]): The input values.
- run_manager (CallbackManagerForChainRun , optional):
- The callback manager.
+ inputs: The input values.
+ run_manager: The callback manager.
Returns:
- Dict[str, Any]: The evaluation results containing the score.
+ The evaluation results containing the score.
"""
return {
"score": self.compute_metric(inputs["prediction"], inputs["prediction_b"]),
@@ -372,12 +371,11 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi
"""Asynchronously compute the string distance between two predictions.
Args:
- inputs (Dict[str, Any]): The input values.
- run_manager (AsyncCallbackManagerForChainRun , optional):
- The callback manager.
+ inputs: The input values.
+ run_manager: The callback manager.
Returns:
- Dict[str, Any]: The evaluation results containing the score.
+ The evaluation results containing the score.
"""
return {
"score": self.compute_metric(inputs["prediction"], inputs["prediction_b"]),
diff --git a/libs/langchain/langchain_classic/model_laboratory.py b/libs/langchain/langchain_classic/model_laboratory.py
index 81f903a51b..fef007bb4a 100644
--- a/libs/langchain/langchain_classic/model_laboratory.py
+++ b/libs/langchain/langchain_classic/model_laboratory.py
@@ -21,15 +21,15 @@ class ModelLaboratory:
Args:
chains: A sequence of chains to experiment with.
Each chain must have exactly one input and one output variable.
- names (list[str] | None): Optional list of names corresponding to each
- chain. If provided, its length must match the number of chains.
+ names: Optional list of names corresponding to each chain.
+ If provided, its length must match the number of chains.
Raises:
- ValueError: If any chain is not an instance of `Chain`.
- ValueError: If a chain does not have exactly one input variable.
- ValueError: If a chain does not have exactly one output variable.
- ValueError: If the length of `names` does not match the number of chains.
+ `ValueError`: If any chain is not an instance of `Chain`.
+ `ValueError`: If a chain does not have exactly one input variable.
+ `ValueError`: If a chain does not have exactly one output variable.
+ `ValueError`: If the length of `names` does not match the number of chains.
"""
for chain in chains:
if not isinstance(chain, Chain):
@@ -72,7 +72,7 @@ class ModelLaboratory:
If provided, the prompt must contain exactly one input variable.
Returns:
- ModelLaboratory: An instance of `ModelLaboratory` initialized with LLMs.
+ An instance of `ModelLaboratory` initialized with LLMs.
"""
if prompt is None:
prompt = PromptTemplate(input_variables=["_input"], template="{_input}")
diff --git a/libs/langchain/langchain_classic/output_parsers/structured.py b/libs/langchain/langchain_classic/output_parsers/structured.py
index b5efae9060..306e2c8253 100644
--- a/libs/langchain/langchain_classic/output_parsers/structured.py
+++ b/libs/langchain/langchain_classic/output_parsers/structured.py
@@ -96,7 +96,7 @@ class StructuredOutputParser(BaseOutputParser[dict[str, Any]]):
# ```
Args:
- only_json (bool): If `True`, only the json in the Markdown code snippet
+ only_json: If `True`, only the json in the Markdown code snippet
will be returned, without the introducing text. Defaults to `False`.
"""
schema_str = "\n".join(
diff --git a/libs/langchain/langchain_classic/retrievers/ensemble.py b/libs/langchain/langchain_classic/retrievers/ensemble.py
index bdce26c6e2..4979a5d08c 100644
--- a/libs/langchain/langchain_classic/retrievers/ensemble.py
+++ b/libs/langchain/langchain_classic/retrievers/ensemble.py
@@ -299,8 +299,8 @@ class EnsembleRetriever(BaseRetriever):
doc_lists: A list of rank lists, where each rank list contains unique items.
Returns:
- list: The final aggregated list of items sorted by their weighted RRF
- scores in descending order.
+ The final aggregated list of items sorted by their weighted RRF
+ scores in descending order.
"""
if len(doc_lists) != len(self.weights):
msg = "Number of rank lists must be equal to the number of weights."
diff --git a/libs/langchain/langchain_classic/smith/evaluation/runner_utils.py b/libs/langchain/langchain_classic/smith/evaluation/runner_utils.py
index d52e037eb8..51fb2d776a 100644
--- a/libs/langchain/langchain_classic/smith/evaluation/runner_utils.py
+++ b/libs/langchain/langchain_classic/smith/evaluation/runner_utils.py
@@ -982,8 +982,7 @@ def _run_llm_or_chain(
input_mapper: Optional function to map the input to the expected format.
Returns:
- Union[List[dict], List[str], List[LLMResult], List[ChatResult]]:
- The outputs of the model or chain.
+ The outputs of the model or chain.
"""
chain_or_llm = (
"LLM" if isinstance(llm_or_chain_factory, BaseLanguageModel) else "Chain"
diff --git a/libs/langchain/langchain_classic/storage/file_system.py b/libs/langchain/langchain_classic/storage/file_system.py
index 226768451e..403312b8e3 100644
--- a/libs/langchain/langchain_classic/storage/file_system.py
+++ b/libs/langchain/langchain_classic/storage/file_system.py
@@ -47,14 +47,15 @@ class LocalFileStore(ByteStore):
"""Implement the BaseStore interface for the local file system.
Args:
- root_path (Union[str, Path]): The root path of the file store. All keys are
- interpreted as paths relative to this root.
- chmod_file: (optional, defaults to `None`) If specified, sets permissions
- for newly created files, overriding the current `umask` if needed.
- chmod_dir: (optional, defaults to `None`) If specified, sets permissions
- for newly created dirs, overriding the current `umask` if needed.
- update_atime: (optional, defaults to `False`) If `True`, updates the
- filesystem access time (but not the modified time) when a file is read.
+ root_path: The root path of the file store. All keys are interpreted as
+ paths relative to this root.
+ chmod_file: If specified, sets permissions for newly created files,
+ overriding the current `umask` if needed.
+ chmod_dir: If specified, sets permissions for newly created dirs,
+ overriding the current `umask` if needed.
+ update_atime: If `True`, updates the filesystem access time
+ (but not the modified time) when a file is read.
+
This allows MRU/LRU cache policies to be implemented for filesystems
where access time updates are disabled.
"""
@@ -67,10 +68,10 @@ class LocalFileStore(ByteStore):
"""Get the full path for a given key relative to the root path.
Args:
- key (str): The key relative to the root path.
+ key: The key relative to the root path.
Returns:
- Path: The full path for the given key.
+ The full path for the given key.
"""
if not re.match(r"^[a-zA-Z0-9_.\-/]+$", key):
msg = f"Invalid characters in key: {key}"
@@ -148,10 +149,8 @@ class LocalFileStore(ByteStore):
"""Delete the given keys and their associated values.
Args:
- keys (Sequence[str]): A sequence of keys to delete.
+ keys: A sequence of keys to delete.
- Returns:
- None
"""
for key in keys:
full_path = self._get_full_path(key)
@@ -162,10 +161,10 @@ class LocalFileStore(ByteStore):
"""Get an iterator over keys that match the given prefix.
Args:
- prefix (str | None): The prefix to match.
+ prefix: The prefix to match.
- Returns:
- Iterator[str]: An iterator over keys that match the given prefix.
+ Yields:
+ Keys that match the given prefix.
"""
prefix_path = self._get_full_path(prefix) if prefix else self.root_path
for file in prefix_path.rglob("*"):
diff --git a/libs/langchain/langchain_classic/tools/jira/tool.py b/libs/langchain/langchain_classic/tools/jira/tool.py
index f9216f08a4..e5f70b1418 100644
--- a/libs/langchain/langchain_classic/tools/jira/tool.py
+++ b/libs/langchain/langchain_classic/tools/jira/tool.py
@@ -27,10 +27,10 @@ def __getattr__(name: str) -> Any:
"""Dynamically retrieve attributes from the updated module path.
Args:
- name (str): The name of the attribute to import.
+ name: The name of the attribute to import.
Returns:
- Any: The resolved attribute from the updated path.
+ The resolved attribute from the updated path.
"""
return _import_attribute(name)
diff --git a/libs/langchain/langchain_classic/tools/json/tool.py b/libs/langchain/langchain_classic/tools/json/tool.py
index ca85daed0a..2ff1e4b844 100644
--- a/libs/langchain/langchain_classic/tools/json/tool.py
+++ b/libs/langchain/langchain_classic/tools/json/tool.py
@@ -35,10 +35,10 @@ def __getattr__(name: str) -> Any:
at runtime and forward them to their new locations.
Args:
- name (str): The name of the attribute to import.
+ name: The name of the attribute to import.
Returns:
- Any: The resolved attribute from the appropriate updated module.
+ The resolved attribute from the appropriate updated module.
"""
return _import_attribute(name)
diff --git a/libs/langchain/langchain_classic/tools/zapier/tool.py b/libs/langchain/langchain_classic/tools/zapier/tool.py
index 1249bb8bcf..d04673abe6 100644
--- a/libs/langchain/langchain_classic/tools/zapier/tool.py
+++ b/libs/langchain/langchain_classic/tools/zapier/tool.py
@@ -33,10 +33,10 @@ def __getattr__(name: str) -> Any:
at runtime and forward them to their new locations.
Args:
- name (str): The name of the attribute to import.
+ name: The name of the attribute to import.
Returns:
- Any: The resolved attribute from the appropriate updated module.
+ The resolved attribute from the appropriate updated module.
"""
return _import_attribute(name)
diff --git a/libs/langchain/tests/unit_tests/test_imports.py b/libs/langchain/tests/unit_tests/test_imports.py
index f13d1e18f3..6021f50974 100644
--- a/libs/langchain/tests/unit_tests/test_imports.py
+++ b/libs/langchain/tests/unit_tests/test_imports.py
@@ -108,15 +108,15 @@ def test_no_more_changes_to_proxy_community() -> None:
def extract_deprecated_lookup(file_path: str) -> dict[str, Any] | None:
- """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.
Args:
- file_path (str): The path to the Python file.
+ file_path: The path to the Python file.
Returns:
- dict or None: The value of DEPRECATED_LOOKUP if it exists, None otherwise.
+ The value of `DEPRECATED_LOOKUP` if it exists, `None` otherwise.
"""
tree = ast.parse(Path(file_path).read_text(encoding="utf-8"), filename=file_path)
@@ -136,10 +136,10 @@ def _dict_from_ast(node: ast.Dict) -> dict[str, str]:
"""Convert an AST dict node to a Python dictionary, assuming str to str format.
Args:
- node (ast.Dict): The AST node representing a dictionary.
+ node: The AST node representing a dictionary.
Returns:
- dict: The corresponding Python dictionary.
+ The corresponding Python dictionary.
"""
result: dict[str, str] = {}
for key, value in zip(node.keys, node.values, strict=False):
@@ -153,10 +153,10 @@ def _literal_eval_str(node: ast.AST) -> str:
"""Evaluate an AST literal node to its corresponding string value.
Args:
- node (ast.AST): The AST node representing a literal value.
+ node: The AST node representing a literal value.
Returns:
- str: The corresponding string value.
+ The corresponding string value.
"""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
diff --git a/libs/partners/qdrant/langchain_qdrant/qdrant.py b/libs/partners/qdrant/langchain_qdrant/qdrant.py
index 922c412265..496240a464 100644
--- a/libs/partners/qdrant/langchain_qdrant/qdrant.py
+++ b/libs/partners/qdrant/langchain_qdrant/qdrant.py
@@ -874,7 +874,7 @@ class QdrantVectorStore(VectorStore):
**kwargs: Other keyword arguments that subclasses might use.
Returns:
- True if deletion is successful, False otherwise.
+ True if deletion is successful, `False` otherwise.
"""
result = self.client.delete(
diff --git a/libs/partners/qdrant/langchain_qdrant/vectorstores.py b/libs/partners/qdrant/langchain_qdrant/vectorstores.py
index 1099dc546c..3e31309f05 100644
--- a/libs/partners/qdrant/langchain_qdrant/vectorstores.py
+++ b/libs/partners/qdrant/langchain_qdrant/vectorstores.py
@@ -1161,7 +1161,7 @@ class Qdrant(VectorStore):
**kwargs: Other keyword arguments that subclasses might use.
Returns:
- True if deletion is successful, False otherwise.
+ True if deletion is successful, `False` otherwise.
"""
result = self.client.delete(
@@ -1179,7 +1179,7 @@ class Qdrant(VectorStore):
**kwargs: Other keyword arguments that subclasses might use.
Returns:
- True if deletion is successful, False otherwise.
+ True if deletion is successful, `False` otherwise.
"""
if self.async_client is None or isinstance(