Skip to content

The agent engineering platform.

style: fix tables, capitalization (#33417)

Mason Daughertyed2ee4e8cc6a
diff --git a/libs/core/langchain_core/language_models/base.py b/libs/core/langchain_core/language_models/base.py
index 726c7aee6b..0d28d50ead 100644
--- a/libs/core/langchain_core/language_models/base.py
+++ b/libs/core/langchain_core/language_models/base.py
@@ -123,7 +123,6 @@ class BaseLanguageModel(
* If instance of `BaseCache`, will use the provided cache.
Caching is not currently supported for streaming methods of models.
-
"""
verbose: bool = Field(default_factory=_get_verbosity, exclude=True, repr=False)
"""Whether to print out response text."""
@@ -146,7 +145,7 @@ class BaseLanguageModel(
def set_verbose(cls, verbose: bool | None) -> bool: # noqa: FBT001
"""If verbose is `None`, set it.
- This allows users to pass in None as verbose to access the global setting.
+ This allows users to pass in `None` as verbose to access the global setting.
Args:
verbose: The verbosity setting to use.
@@ -186,12 +185,12 @@ class BaseLanguageModel(
1. Take advantage of batched calls,
2. Need more output from the model than just the top generated value,
3. Are building chains that are agnostic to the underlying language model
- type (e.g., pure text completion models vs chat models).
+ type (e.g., pure text completion models vs chat models).
Args:
- prompts: List of PromptValues. A PromptValue is an object that can be
- converted to match the format of any language model (string for pure
- text generation models and BaseMessages for chat models).
+ prompts: List of `PromptValue` objects. A `PromptValue` is an object that
+ can be converted to match the format of any language model (string for
+ pure text generation models and `BaseMessage` objects for chat models).
stop: Stop words to use when generating. Model output is cut off at the
first occurrence of any of these substrings.
callbacks: Callbacks to pass through. Used for executing additional
@@ -200,8 +199,8 @@ class BaseLanguageModel(
to the model provider API call.
Returns:
- An LLMResult, which contains a list of candidate Generations for each input
- prompt and additional model provider-specific output.
+ An `LLMResult`, which contains a list of candidate `Generation` objects for
+ each input prompt and additional model provider-specific output.
"""
@@ -223,12 +222,12 @@ class BaseLanguageModel(
1. Take advantage of batched calls,
2. Need more output from the model than just the top generated value,
3. Are building chains that are agnostic to the underlying language model
- type (e.g., pure text completion models vs chat models).
+ type (e.g., pure text completion models vs chat models).
Args:
- prompts: List of PromptValues. A PromptValue is an object that can be
- converted to match the format of any language model (string for pure
- text generation models and BaseMessages for chat models).
+ prompts: List of `PromptValue` objects. A `PromptValue` is an object that
+ can be converted to match the format of any language model (string for
+ pure text generation models and `BaseMessage` objects for chat models).
stop: Stop words to use when generating. Model output is cut off at the
first occurrence of any of these substrings.
callbacks: Callbacks to pass through. Used for executing additional
@@ -237,8 +236,8 @@ class BaseLanguageModel(
to the model provider API call.
Returns:
- An `LLMResult`, which contains a list of candidate Generations for each
- input prompt and additional model provider-specific output.
+ An `LLMResult`, which contains a list of candidate `Generation` objects for
+ each input prompt and additional model provider-specific output.
"""
diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py
index 6506111092..d13a081520 100644
--- a/libs/core/langchain_core/language_models/chat_models.py
+++ b/libs/core/langchain_core/language_models/chat_models.py
@@ -240,78 +240,54 @@ def _format_ls_structured_output(ls_structured_output_format: dict | None) -> di
class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
- """Base class for chat models.
+ r"""Base class for chat models.
Key imperative methods:
Methods that actually call the underlying model.
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | Method | Input | Output | Description |
- +===========================+================================================================+=====================================================================+==================================================================================================+
- | `invoke` | str | list[dict | tuple | BaseMessage] | PromptValue | BaseMessage | A single chat model call. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `ainvoke` | ''' | BaseMessage | Defaults to running invoke in an async executor. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `stream` | ''' | Iterator[BaseMessageChunk] | Defaults to yielding output of invoke. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `astream` | ''' | AsyncIterator[BaseMessageChunk] | Defaults to yielding output of ainvoke. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `astream_events` | ''' | AsyncIterator[StreamEvent] | Event types: 'on_chat_model_start', 'on_chat_model_stream', 'on_chat_model_end'. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `batch` | list['''] | list[BaseMessage] | Defaults to running invoke in concurrent threads. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `abatch` | list['''] | list[BaseMessage] | Defaults to running ainvoke in concurrent threads. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `batch_as_completed` | list['''] | Iterator[tuple[int, Union[BaseMessage, Exception]]] | Defaults to running invoke in concurrent threads. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
- | `abatch_as_completed` | list['''] | AsyncIterator[tuple[int, Union[BaseMessage, Exception]]] | Defaults to running ainvoke in concurrent threads. |
- +---------------------------+----------------------------------------------------------------+---------------------------------------------------------------------+--------------------------------------------------------------------------------------------------+
-
- This table provides a brief overview of the main imperative methods. Please see the base Runnable reference for full documentation.
+ This table provides a brief overview of the main imperative methods. Please see the base `Runnable` reference for full documentation.
+
+ | Method | Input | Output | Description |
+ | ---------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------- |
+ | `invoke` | `str` \| `list[dict | tuple | BaseMessage]` \| `PromptValue` | `BaseMessage` | A single chat model call. |
+ | `ainvoke` | `'''` | `BaseMessage` | Defaults to running `invoke` in an async executor. |
+ | `stream` | `'''` | `Iterator[BaseMessageChunk]` | Defaults to yielding output of `invoke`. |
+ | `astream` | `'''` | `AsyncIterator[BaseMessageChunk]` | Defaults to yielding output of `ainvoke`. |
+ | `astream_events` | `'''` | `AsyncIterator[StreamEvent]` | Event types: `on_chat_model_start`, `on_chat_model_stream`, `on_chat_model_end`. |
+ | `batch` | `list[''']` | `list[BaseMessage]` | Defaults to running `invoke` in concurrent threads. |
+ | `abatch` | `list[''']` | `list[BaseMessage]` | Defaults to running `ainvoke` in concurrent threads. |
+ | `batch_as_completed` | `list[''']` | `Iterator[tuple[int, Union[BaseMessage, Exception]]]` | Defaults to running `invoke` in concurrent threads. |
+ | `abatch_as_completed` | `list[''']` | `AsyncIterator[tuple[int, Union[BaseMessage, Exception]]]` | Defaults to running `ainvoke` in concurrent threads. |
Key declarative methods:
- Methods for creating another Runnable using the ChatModel.
-
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
- | Method | Description |
- +==================================+===========================================================================================================+
- | `bind_tools` | Create ChatModel that can call tools. |
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
- | `with_structured_output` | Create wrapper that structures model output using schema. |
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
- | `with_retry` | Create wrapper that retries model calls on failure. |
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
- | `with_fallbacks` | Create wrapper that falls back to other models on failure. |
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
- | `configurable_fields` | Specify init args of the model that can be configured at runtime via the RunnableConfig. |
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
- | `configurable_alternatives` | Specify alternative models which can be swapped in at runtime via the RunnableConfig. |
- +----------------------------------+-----------------------------------------------------------------------------------------------------------+
+ Methods for creating another `Runnable` using the chat model.
This table provides a brief overview of the main declarative methods. Please see the reference for each method for full documentation.
+ | Method | Description |
+ | ---------------------------- | -------------------------------------------------------------------------------------------- |
+ | `bind_tools` | Create chat model that can call tools. |
+ | `with_structured_output` | Create wrapper that structures model output using schema. |
+ | `with_retry` | Create wrapper that retries model calls on failure. |
+ | `with_fallbacks` | Create wrapper that falls back to other models on failure. |
+ | `configurable_fields` | Specify init args of the model that can be configured at runtime via the `RunnableConfig`. |
+ | `configurable_alternatives` | Specify alternative models which can be swapped in at runtime via the `RunnableConfig`. |
+
Creating custom chat model:
Custom chat model implementations should inherit from this class.
Please reference the table below for information about which
methods and properties are required or optional for implementations.
- +----------------------------------+--------------------------------------------------------------------+-------------------+
| Method/Property | Description | Required/Optional |
- +==================================+====================================================================+===================+
+ | -------------------------------- | ------------------------------------------------------------------ | ----------------- |
| `_generate` | Use to generate a chat result from a prompt | Required |
- +----------------------------------+--------------------------------------------------------------------+-------------------+
| `_llm_type` (property) | Used to uniquely identify the type of the model. Used for logging. | Required |
- +----------------------------------+--------------------------------------------------------------------+-------------------+
| `_identifying_params` (property) | Represent model parameterization for tracing purposes. | Optional |
- +----------------------------------+--------------------------------------------------------------------+-------------------+
| `_stream` | Use to implement streaming | Optional |
- +----------------------------------+--------------------------------------------------------------------+-------------------+
| `_agenerate` | Use to implement a native async method | Optional |
- +----------------------------------+--------------------------------------------------------------------+-------------------+
| `_astream` | Use to implement async version of `_stream` | Optional |
- +----------------------------------+--------------------------------------------------------------------+-------------------+
- Follow the guide for more information on how to implement a custom Chat Model:
+ Follow the guide for more information on how to implement a custom chat model:
[Guide](https://python.langchain.com/docs/how_to/custom_chat_model/).
""" # noqa: E501
@@ -327,9 +303,9 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
- If `True`, will always bypass streaming case.
- If `'tool_calling'`, will bypass streaming case only when the model is called
- with a `tools` keyword argument. In other words, LangChain will automatically
- switch to non-streaming behavior (`invoke`) only when the tools argument is
- provided. This offers the best of both worlds.
+ with a `tools` keyword argument. In other words, LangChain will automatically
+ switch to non-streaming behavior (`invoke`) only when the tools argument is
+ provided. This offers the best of both worlds.
- If `False` (Default), will always use streaming case if available.
The main reason for this flag is that code might be written using `stream` and
@@ -349,7 +325,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
Supported values:
- `'v0'`: provider-specific format in content (can lazily-parse with
- `.content_blocks`)
+ `.content_blocks`)
- `'v1'`: standardized format in content (consistent with `.content_blocks`)
Partner packages (e.g., `langchain-openai`) can also use this field to roll out
diff --git a/libs/core/langchain_core/load/serializable.py b/libs/core/langchain_core/load/serializable.py
index f4f8c0417b..ba729835d0 100644
--- a/libs/core/langchain_core/load/serializable.py
+++ b/libs/core/langchain_core/load/serializable.py
@@ -25,9 +25,9 @@ class BaseSerialized(TypedDict):
id: list[str]
"""The unique identifier of the object."""
name: NotRequired[str]
- """The name of the object. Optional."""
+ """The name of the object."""
graph: NotRequired[dict[str, Any]]
- """The graph of the object. Optional."""
+ """The graph of the object."""
class SerializedConstructor(BaseSerialized):
@@ -52,7 +52,7 @@ class SerializedNotImplemented(BaseSerialized):
type: Literal["not_implemented"]
"""The type of the object. Must be `'not_implemented'`."""
repr: str | None
- """The representation of the object. Optional."""
+ """The representation of the object."""
def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
@@ -61,7 +61,7 @@ def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
Args:
value: The value.
key: The key.
- model: The pydantic model.
+ model: The Pydantic model.
Returns:
Whether the value is different from the default.
@@ -93,18 +93,18 @@ class Serializable(BaseModel, ABC):
It relies on the following methods and properties:
- `is_lc_serializable`: Is this class serializable?
- By design, even if a class inherits from Serializable, it is not serializable by
- default. This is to prevent accidental serialization of objects that should not
- be serialized.
+ By design, even if a class inherits from `Serializable`, it is not serializable
+ by default. This is to prevent accidental serialization of objects that should
+ not be serialized.
- `get_lc_namespace`: Get the namespace of the langchain object.
During deserialization, this namespace is used to identify
the correct class to instantiate.
Please see the `Reviver` class in `langchain_core.load.load` for more details.
- During deserialization an additional mapping is handle
- classes that have moved or been renamed across package versions.
+ During deserialization an additional mapping is handle classes that have moved
+ or been renamed across package versions.
- `lc_secrets`: A map of constructor argument names to secret ids.
- `lc_attributes`: List of additional attribute names that should be included
- as part of the serialized representation.
+ as part of the serialized representation.
"""
# Remove default BaseModel init docstring.
@@ -116,12 +116,12 @@ class Serializable(BaseModel, ABC):
def is_lc_serializable(cls) -> bool:
"""Is this class serializable?
- By design, even if a class inherits from Serializable, it is not serializable by
- default. This is to prevent accidental serialization of objects that should not
- be serialized.
+ By design, even if a class inherits from `Serializable`, it is not serializable
+ by default. This is to prevent accidental serialization of objects that should
+ not be serialized.
Returns:
- Whether the class is serializable. Default is False.
+ Whether the class is serializable. Default is `False`.
"""
return False
@@ -133,7 +133,7 @@ class Serializable(BaseModel, ABC):
namespace is ["langchain", "llms", "openai"]
Returns:
- The namespace as a list of strings.
+ The namespace.
"""
return cls.__module__.split(".")
@@ -141,8 +141,7 @@ class Serializable(BaseModel, ABC):
def lc_secrets(self) -> dict[str, str]:
"""A map of constructor argument names to secret ids.
- For example,
- {"openai_api_key": "OPENAI_API_KEY"}
+ For example, `{"openai_api_key": "OPENAI_API_KEY"}`
"""
return {}
@@ -151,6 +150,7 @@ class Serializable(BaseModel, ABC):
"""List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
+
Default is an empty dictionary.
"""
return {}
@@ -194,7 +194,7 @@ class Serializable(BaseModel, ABC):
ValueError: If the class has deprecated attributes.
Returns:
- A json serializable object or a SerializedNotImplemented object.
+ A json serializable object or a `SerializedNotImplemented` object.
"""
if not self.is_lc_serializable():
return self.to_json_not_implemented()
@@ -269,7 +269,7 @@ class Serializable(BaseModel, ABC):
"""Serialize a "not implemented" object.
Returns:
- SerializedNotImplemented.
+ `SerializedNotImplemented`.
"""
return to_json_not_implemented(self)
@@ -284,8 +284,8 @@ def _is_field_useful(inst: Serializable, key: str, value: Any) -> bool:
Returns:
Whether the field is useful. If the field is required, it is useful.
- If the field is not required, it is useful if the value is not None.
- If the field is not required and the value is None, it is useful if the
+ If the field is not required, it is useful if the value is not `None`.
+ If the field is not required and the value is `None`, it is useful if the
default value is different from the value.
"""
field = type(inst).model_fields.get(key)
@@ -344,10 +344,10 @@ def to_json_not_implemented(obj: object) -> SerializedNotImplemented:
"""Serialize a "not implemented" object.
Args:
- obj: object to serialize.
+ obj: Object to serialize.
Returns:
- SerializedNotImplemented
+ `SerializedNotImplemented`
"""
id_: list[str] = []
try:
diff --git a/libs/core/langchain_core/output_parsers/openai_functions.py b/libs/core/langchain_core/output_parsers/openai_functions.py
index a971884621..b333c07ce4 100644
--- a/libs/core/langchain_core/output_parsers/openai_functions.py
+++ b/libs/core/langchain_core/output_parsers/openai_functions.py
@@ -31,13 +31,13 @@ class OutputFunctionsParser(BaseGenerationOutputParser[Any]):
Args:
result: The result of the LLM call.
- partial: Whether to parse partial JSON objects. Default is False.
+ partial: Whether to parse partial JSON objects.
Returns:
The parsed JSON object.
Raises:
- OutputParserException: If the output is not valid JSON.
+ `OutputParserException`: If the output is not valid JSON.
"""
generation = result[0]
if not isinstance(generation, ChatGeneration):
@@ -56,7 +56,7 @@ class OutputFunctionsParser(BaseGenerationOutputParser[Any]):
class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):
- """Parse an output as the Json object."""
+ """Parse an output as the JSON object."""
strict: bool = False
"""Whether to allow non-JSON-compliant strings.
@@ -82,13 +82,13 @@ class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):
Args:
result: The result of the LLM call.
- partial: Whether to parse partial JSON objects. Default is False.
+ partial: Whether to parse partial JSON objects.
Returns:
The parsed JSON object.
Raises:
- OutputParserException: If the output is not valid JSON.
+ OutputParserExcept`ion: If the output is not valid JSON.
"""
if len(result) != 1:
msg = f"Expected exactly one result, but got {len(result)}"
@@ -155,7 +155,7 @@ class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):
class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):
- """Parse an output as the element of the Json object."""
+ """Parse an output as the element of the JSON object."""
key_name: str
"""The name of the key to return."""
@@ -165,7 +165,7 @@ class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):
Args:
result: The result of the LLM call.
- partial: Whether to parse partial JSON objects. Default is False.
+ partial: Whether to parse partial JSON objects.
Returns:
The parsed JSON object.
@@ -177,16 +177,15 @@ class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):
class PydanticOutputFunctionsParser(OutputFunctionsParser):
- """Parse an output as a pydantic object.
+ """Parse an output as a Pydantic object.
- This parser is used to parse the output of a ChatModel that uses
- OpenAI function format to invoke functions.
+ This parser is used to parse the output of a chat model that uses OpenAI function
+ format to invoke functions.
- The parser extracts the function call invocation and matches
- them to the pydantic schema provided.
+ The parser extracts the function call invocation and matches them to the Pydantic
+ schema provided.
- An exception will be raised if the function call does not match
- the provided schema.
+ An exception will be raised if the function call does not match the provided schema.
Example:
```python
@@ -221,7 +220,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
"""
pydantic_schema: type[BaseModel] | dict[str, type[BaseModel]]
- """The pydantic schema to parse the output with.
+ """The Pydantic schema to parse the output with.
If multiple schemas are provided, then the function name will be used to
determine which schema to use.
@@ -230,7 +229,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
@model_validator(mode="before")
@classmethod
def validate_schema(cls, values: dict) -> Any:
- """Validate the pydantic schema.
+ """Validate the Pydantic schema.
Args:
values: The values to validate.
@@ -239,7 +238,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
The validated values.
Raises:
- ValueError: If the schema is not a pydantic schema.
+ `ValueError`: If the schema is not a Pydantic schema.
"""
schema = values["pydantic_schema"]
if "args_only" not in values:
@@ -262,10 +261,10 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
Args:
result: The result of the LLM call.
- partial: Whether to parse partial JSON objects. Default is False.
+ partial: Whether to parse partial JSON objects.
Raises:
- ValueError: If the pydantic schema is not valid.
+ `ValueError`: If the Pydantic schema is not valid.
Returns:
The parsed JSON object.
@@ -288,13 +287,13 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
elif issubclass(pydantic_schema, BaseModelV1):
pydantic_args = pydantic_schema.parse_raw(args)
else:
- msg = f"Unsupported pydantic schema: {pydantic_schema}"
+ msg = f"Unsupported Pydantic schema: {pydantic_schema}"
raise ValueError(msg)
return pydantic_args
class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):
- """Parse an output as an attribute of a pydantic object."""
+ """Parse an output as an attribute of a Pydantic object."""
attr_name: str
"""The name of the attribute to return."""
@@ -305,7 +304,7 @@ class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):
Args:
result: The result of the LLM call.
- partial: Whether to parse partial JSON objects. Default is False.
+ partial: Whether to parse partial JSON objects.
Returns:
The parsed JSON object.
diff --git a/libs/core/langchain_core/output_parsers/pydantic.py b/libs/core/langchain_core/output_parsers/pydantic.py
index 13eee343cd..085faa1bce 100644
--- a/libs/core/langchain_core/output_parsers/pydantic.py
+++ b/libs/core/langchain_core/output_parsers/pydantic.py
@@ -17,10 +17,10 @@ from langchain_core.utils.pydantic import (
class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):
- """Parse an output using a pydantic model."""
+ """Parse an output using a Pydantic model."""
pydantic_object: Annotated[type[TBaseModel], SkipValidation()]
- """The pydantic model to parse."""
+ """The Pydantic model to parse."""
def _parse_obj(self, obj: dict) -> TBaseModel:
try:
@@ -45,21 +45,20 @@ class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):
def parse_result(
self, result: list[Generation], *, partial: bool = False
) -> TBaseModel | None:
- """Parse the result of an LLM call to a pydantic object.
+ """Parse the result of an LLM call to a Pydantic object.
Args:
result: The result of the LLM call.
partial: Whether to parse partial JSON objects.
If `True`, the output will be a JSON object containing
all the keys that have been returned so far.
- Defaults to `False`.
Raises:
- OutputParserException: If the result is not valid JSON
- or does not conform to the pydantic model.
+ `OutputParserException`: If the result is not valid JSON
+ or does not conform to the Pydantic model.
Returns:
- The parsed pydantic object.
+ The parsed Pydantic object.
"""
try:
json_object = super().parse_result(result)
@@ -70,13 +69,13 @@ class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):
raise
def parse(self, text: str) -> TBaseModel:
- """Parse the output of an LLM call to a pydantic object.
+ """Parse the output of an LLM call to a Pydantic object.
Args:
text: The output of the LLM call.
Returns:
- The parsed pydantic object.
+ The parsed Pydantic object.
"""
return super().parse(text)
@@ -107,7 +106,7 @@ class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):
@property
@override
def OutputType(self) -> type[TBaseModel]:
- """Return the pydantic model."""
+ """Return the Pydantic model."""
return self.pydantic_object
diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py
index 1b5ca8c8f1..842ed35f82 100644
--- a/libs/core/langchain_core/runnables/base.py
+++ b/libs/core/langchain_core/runnables/base.py
@@ -304,7 +304,7 @@ class Runnable(ABC, Generic[Input, Output]):
TypeError: If the input type cannot be inferred.
"""
# First loop through all parent classes and if any of them is
- # a pydantic model, we will pick up the generic parameterization
+ # a Pydantic model, we will pick up the generic parameterization
# from that model via the __pydantic_generic_metadata__ attribute.
for base in self.__class__.mro():
if hasattr(base, "__pydantic_generic_metadata__"):
@@ -312,7 +312,7 @@ class Runnable(ABC, Generic[Input, Output]):
if "args" in metadata and len(metadata["args"]) == 2:
return metadata["args"][0]
- # If we didn't find a pydantic model in the parent classes,
+ # If we didn't find a Pydantic model in the parent classes,
# then loop through __orig_bases__. This corresponds to
# Runnables that are not pydantic models.
for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
@@ -390,7 +390,7 @@ class Runnable(ABC, Generic[Input, Output]):
self.get_name("Input"),
root=root_type,
# create model needs access to appropriate type annotations to be
- # able to construct the pydantic model.
+ # able to construct the Pydantic model.
# When we create the model, we pass information about the namespace
# where the model is being created, so the type annotations can
# be resolved correctly as well.
@@ -433,7 +433,7 @@ class Runnable(ABC, Generic[Input, Output]):
def output_schema(self) -> type[BaseModel]:
"""Output schema.
- The type of output this `Runnable` produces specified as a pydantic model.
+ The type of output this `Runnable` produces specified as a Pydantic model.
"""
return self.get_output_schema()
@@ -468,7 +468,7 @@ class Runnable(ABC, Generic[Input, Output]):
self.get_name("Output"),
root=root_type,
# create model needs access to appropriate type annotations to be
- # able to construct the pydantic model.
+ # able to construct the Pydantic model.
# When we create the model, we pass information about the namespace
# where the model is being created, so the type annotations can
# be resolved correctly as well.
@@ -1273,22 +1273,20 @@ class Runnable(ABC, Generic[Input, Output]):
A `StreamEvent` is a dictionary with the following schema:
- - `event`: **str** - Event names are of the format:
+ - `event`: Event names are of the format:
`on_[runnable_type]_(start|stream|end)`.
- - `name`: **str** - The name of the `Runnable` that generated the event.
- - `run_id`: **str** - randomly generated ID associated with the given
- execution of the `Runnable` that emitted the event. A child `Runnable` that gets
- invoked as part of the execution of a parent `Runnable` is assigned its own
- unique ID.
- - `parent_ids`: **list[str]** - The IDs of the parent runnables that generated
- the event. The root `Runnable` will have an empty list. The order of the parent
- IDs is from the root to the immediate parent. Only available for v2 version of
- the API. The v1 version of the API will return an empty list.
- - `tags`: **list[str] | None** - The tags of the `Runnable` that generated
- the event.
- - `metadata`: **dict[str, Any] | None** - The metadata of the `Runnable` that
- generated the event.
- - `data`: **dict[str, Any]**
+ - `name`: The name of the `Runnable` that generated the event.
+ - `run_id`: Randomly generated ID associated with the given execution of the
+ `Runnable` that emitted the event. A child `Runnable` that gets invoked as
+ part of the execution of a parent `Runnable` is assigned its own unique ID.
+ - `parent_ids`: The IDs of the parent runnables that generated the event. The
+ root `Runnable` will have an empty list. The order of the parent IDs is from
+ the root to the immediate parent. Only available for v2 version of the API.
+ The v1 version of the API will return an empty list.
+ - `tags`: The tags of the `Runnable` that generated the event.
+ - `metadata`: The metadata of the `Runnable` that generated the event.
+ - `data`: The data associated with the event. The contents of this field
+ depend on the type of event. See the table below for more details.
Below is a table that illustrates some events that might be emitted by various
chains. Metadata fields have been omitted from the table for brevity.
@@ -1297,39 +1295,23 @@ class Runnable(ABC, Generic[Input, Output]):
!!! note
This reference table is for the v2 version of the schema.
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | event | name | chunk | input | output |
- +==========================+==================+=====================================+===================================================+=====================================================+
- | `on_chat_model_start` | [model name] | | `{"messages": [[SystemMessage, HumanMessage]]}` | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_chat_model_stream` | [model name] | `AIMessageChunk(content="hello")` | | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_chat_model_end` | [model name] | | `{"messages": [[SystemMessage, HumanMessage]]}` | `AIMessageChunk(content="hello world")` |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_llm_start` | [model name] | | `{'input': 'hello'}` | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_llm_stream` | [model name] | `'Hello' ` | | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_llm_end` | [model name] | | `'Hello human!'` | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_chain_start` | format_docs | | | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_chain_stream` | format_docs | `'hello world!, goodbye world!'` | | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_chain_end` | format_docs | | `[Document(...)]` | `'hello world!, goodbye world!'` |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_tool_start` | some_tool | | `{"x": 1, "y": "2"}` | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_tool_end` | some_tool | | | `{"x": 1, "y": "2"}` |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_retriever_start` | [retriever name] | | `{"query": "hello"}` | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_retriever_end` | [retriever name] | | `{"query": "hello"}` | `[Document(...), ..]` |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_prompt_start` | [template_name] | | `{"question": "hello"}` | |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
- | `on_prompt_end` | [template_name] | | `{"question": "hello"}` | `ChatPromptValue(messages: [SystemMessage, ...])` |
- +--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
+ | event | name | chunk | input | output |
+ | ---------------------- | -------------------- | ----------------------------------- | ------------------------------------------------- | --------------------------------------------------- |
+ | `on_chat_model_start` | `'[model name]'` | | `{"messages": [[SystemMessage, HumanMessage]]}` | |
+ | `on_chat_model_stream` | `'[model name]'` | `AIMessageChunk(content="hello")` | | |
+ | `on_chat_model_end` | `'[model name]'` | | `{"messages": [[SystemMessage, HumanMessage]]}` | `AIMessageChunk(content="hello world")` |
+ | `on_llm_start` | `'[model name]'` | | `{'input': 'hello'}` | |
+ | `on_llm_stream` | `'[model name]'` | `'Hello' ` | | |
+ | `on_llm_end` | `'[model name]'` | | `'Hello human!'` | |
+ | `on_chain_start` | `'format_docs'` | | | |
+ | `on_chain_stream` | `'format_docs'` | `'hello world!, goodbye world!'` | | |
+ | `on_chain_end` | `'format_docs'` | | `[Document(...)]` | `'hello world!, goodbye world!'` |
+ | `on_tool_start` | `'some_tool'` | | `{"x": 1, "y": "2"}` | |
+ | `on_tool_end` | `'some_tool'` | | | `{"x": 1, "y": "2"}` |
+ | `on_retriever_start` | `'[retriever name]'` | | `{"query": "hello"}` | |
+ | `on_retriever_end` | `'[retriever name]'` | | `{"query": "hello"}` | `[Document(...), ..]` |
+ | `on_prompt_start` | `'[template_name]'` | | `{"question": "hello"}` | |
+ | `on_prompt_end` | `'[template_name]'` | | `{"question": "hello"}` | `ChatPromptValue(messages: [SystemMessage, ...])` |
In addition to the standard events, users can also dispatch custom events (see example below).
@@ -1337,13 +1319,10 @@ class Runnable(ABC, Generic[Input, Output]):
A custom event has following format:
- +-----------+------+-----------------------------------------------------------------------------------------------------------+
- | Attribute | Type | Description |
- +===========+======+===========================================================================================================+
- | name | str | A user defined name for the event. |
- +-----------+------+-----------------------------------------------------------------------------------------------------------+
- | data | Any | The data associated with the event. This can be anything, though we suggest making it JSON serializable. |
- +-----------+------+-----------------------------------------------------------------------------------------------------------+
+ | Attribute | Type | Description |
+ | ----------- | ------ | --------------------------------------------------------------------------------------------------------- |
+ | `name` | `str` | A user defined name for the event. |
+ | `data` | `Any` | The data associated with the event. This can be anything, though we suggest making it JSON serializable. |
Here are declarations associated with the standard events shown above:
@@ -4493,7 +4472,7 @@ class RunnableLambda(Runnable[Input, Output]):
@override
def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
- """The pydantic schema for the input to this `Runnable`.
+ """The Pydantic schema for the input to this `Runnable`.
Args:
config: The config to use.
@@ -5127,7 +5106,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
None,
),
# create model needs access to appropriate type annotations to be
- # able to construct the pydantic model.
+ # able to construct the Pydantic model.
# When we create the model, we pass information about the namespace
# where the model is being created, so the type annotations can
# be resolved correctly as well.
@@ -5150,7 +5129,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
self.get_name("Output"),
root=list[schema], # type: ignore[valid-type]
# create model needs access to appropriate type annotations to be
- # able to construct the pydantic model.
+ # able to construct the Pydantic model.
# When we create the model, we pass information about the namespace
# where the model is being created, so the type annotations can
# be resolved correctly as well.
@@ -5387,13 +5366,13 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
custom_input_type: Any | None = None
"""Override the input type of the underlying `Runnable` with a custom type.
- The type can be a pydantic model, or a type annotation (e.g., `list[str]`).
+ The type can be a Pydantic model, or a type annotation (e.g., `list[str]`).
"""
# Union[Type[Output], BaseModel] + things like list[str]
custom_output_type: Any | None = None
"""Override the output type of the underlying `Runnable` with a custom type.
- The type can be a pydantic model, or a type annotation (e.g., `list[str]`).
+ The type can be a Pydantic model, or a type annotation (e.g., `list[str]`).
"""
model_config = ConfigDict(
diff --git a/libs/core/langchain_core/runnables/schema.py b/libs/core/langchain_core/runnables/schema.py
index 828085fd43..53de98df28 100644
--- a/libs/core/langchain_core/runnables/schema.py
+++ b/libs/core/langchain_core/runnables/schema.py
@@ -1,4 +1,4 @@
-"""Module contains typedefs that are used with Runnables."""
+"""Module contains typedefs that are used with `Runnable` objects."""
from __future__ import annotations
@@ -14,43 +14,43 @@ class EventData(TypedDict, total=False):
"""Data associated with a streaming event."""
input: Any
- """The input passed to the Runnable that generated the event.
+ """The input passed to the `Runnable` that generated the event.
- Inputs will sometimes be available at the *START* of the Runnable, and
- sometimes at the *END* of the Runnable.
+ Inputs will sometimes be available at the *START* of the `Runnable`, and
+ sometimes at the *END* of the `Runnable`.
- If a Runnable is able to stream its inputs, then its input by definition
- won't be known until the *END* of the Runnable when it has finished streaming
+ If a `Runnable` is able to stream its inputs, then its input by definition
+ won't be known until the *END* of the `Runnable` when it has finished streaming
its inputs.
"""
error: NotRequired[BaseException]
- """The error that occurred during the execution of the Runnable.
+ """The error that occurred during the execution of the `Runnable`.
- This field is only available if the Runnable raised an exception.
+ This field is only available if the `Runnable` raised an exception.
!!! version-added "Added in version 1.0.0"
"""
output: Any
- """The output of the Runnable that generated the event.
+ """The output of the `Runnable` that generated the event.
- Outputs will only be available at the *END* of the Runnable.
+ Outputs will only be available at the *END* of the `Runnable`.
- For most Runnables, this field can be inferred from the `chunk` field,
- though there might be some exceptions for special cased Runnables (e.g., like
+ For most `Runnable` objects, this field can be inferred from the `chunk` field,
+ though there might be some exceptions for special a cased `Runnable` (e.g., like
chat models), which may return more information.
"""
chunk: Any
"""A streaming chunk from the output that generated the event.
chunks support addition in general, and adding them up should result
- in the output of the Runnable that generated the event.
+ in the output of the `Runnable` that generated the event.
"""
class BaseStreamEvent(TypedDict):
"""Streaming event.
- Schema of a streaming event which is produced from the astream_events method.
+ Schema of a streaming event which is produced from the `astream_events` method.
Example:
```python
@@ -94,45 +94,45 @@ class BaseStreamEvent(TypedDict):
"""
event: str
- """Event names are of the format: on_[runnable_type]_(start|stream|end).
+ """Event names are of the format: `on_[runnable_type]_(start|stream|end)`.
Runnable types are one of:
- **llm** - used by non chat models
- **chat_model** - used by chat models
- - **prompt** -- e.g., ChatPromptTemplate
- - **tool** -- from tools defined via @tool decorator or inheriting
- from Tool/BaseTool
- - **chain** - most Runnables are of this type
+ - **prompt** -- e.g., `ChatPromptTemplate`
+ - **tool** -- from tools defined via `@tool` decorator or inheriting
+ from `Tool`/`BaseTool`
+ - **chain** - most `Runnable` objects are of this type
Further, the events are categorized as one of:
- - **start** - when the Runnable starts
- - **stream** - when the Runnable is streaming
- - **end* - when the Runnable ends
+ - **start** - when the `Runnable` starts
+ - **stream** - when the `Runnable` is streaming
+ - **end* - when the `Runnable` ends
start, stream and end are associated with slightly different `data` payload.
Please see the documentation for `EventData` for more details.
"""
run_id: str
- """An randomly generated ID to keep track of the execution of the given Runnable.
+ """An randomly generated ID to keep track of the execution of the given `Runnable`.
- Each child Runnable that gets invoked as part of the execution of a parent Runnable
- is assigned its own unique ID.
+ Each child `Runnable` that gets invoked as part of the execution of a parent
+ `Runnable` is assigned its own unique ID.
"""
tags: NotRequired[list[str]]
- """Tags associated with the Runnable that generated this event.
+ """Tags associated with the `Runnable` that generated this event.
- Tags are always inherited from parent Runnables.
+ Tags are always inherited from parent `Runnable` objects.
- Tags can either be bound to a Runnable using `.with_config({"tags": ["hello"]})`
+ Tags can either be bound to a `Runnable` using `.with_config({"tags": ["hello"]})`
or passed at run time using `.astream_events(..., {"tags": ["hello"]})`.
"""
metadata: NotRequired[dict[str, Any]]
- """Metadata associated with the Runnable that generated this event.
+ """Metadata associated with the `Runnable` that generated this event.
- Metadata can either be bound to a Runnable using
+ Metadata can either be bound to a `Runnable` using
`.with_config({"metadata": { "foo": "bar" }})`
@@ -146,8 +146,8 @@ class BaseStreamEvent(TypedDict):
Root Events will have an empty list.
- For example, if a Runnable A calls Runnable B, then the event generated by Runnable
- B will have Runnable A's ID in the parent_ids field.
+ For example, if a `Runnable` A calls `Runnable` B, then the event generated by
+ `Runnable` B will have `Runnable` A's ID in the `parent_ids` field.
The order of the parent IDs is from the root parent to the immediate parent.
@@ -164,7 +164,7 @@ class StandardStreamEvent(BaseStreamEvent):
The contents of the event data depend on the event type.
"""
name: str
- """The name of the Runnable that generated the event."""
+ """The name of the `Runnable` that generated the event."""
class CustomStreamEvent(BaseStreamEvent):
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index 298819e22b..ea6e10f81f 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -285,17 +285,17 @@ def create_schema_from_function(
error_on_invalid_docstring: bool = False,
include_injected: bool = True,
) -> type[BaseModel]:
- """Create a pydantic schema from a function's signature.
+ """Create a Pydantic schema from a function's signature.
Args:
- model_name: Name to assign to the generated pydantic schema.
+ model_name: Name to assign to the generated Pydantic schema.
func: Function to generate the schema from.
filter_args: Optional list of arguments to exclude from the schema.
- Defaults to FILTERED_ARGS.
+ Defaults to `FILTERED_ARGS`.
parse_docstring: Whether to parse the function's docstring for descriptions
for each argument. Defaults to `False`.
error_on_invalid_docstring: if `parse_docstring` is provided, configure
- whether to raise ValueError on invalid Google Style docstrings.
+ whether to raise `ValueError` on invalid Google Style docstrings.
Defaults to `False`.
include_injected: Whether to include injected arguments in the schema.
Defaults to `True`, since we want to include them in the schema
@@ -312,7 +312,7 @@ def create_schema_from_function(
# https://docs.pydantic.dev/latest/usage/validation_decorator/
with warnings.catch_warnings():
# We are using deprecated functionality here.
- # This code should be re-written to simply construct a pydantic model
+ # This code should be re-written to simply construct a Pydantic model
# using inspect.signature and create_model.
warnings.simplefilter("ignore", category=PydanticDeprecationWarning)
validated = validate_arguments(func, config=_SchemaConfig) # type: ignore[operator]
diff --git a/libs/core/langchain_core/tools/simple.py b/libs/core/langchain_core/tools/simple.py
index 0a662b44ed..44d922ed53 100644
--- a/libs/core/langchain_core/tools/simple.py
+++ b/libs/core/langchain_core/tools/simple.py
@@ -69,7 +69,7 @@ class Tool(BaseTool):
def _to_args_and_kwargs(
self, tool_input: str | dict, tool_call_id: str | None
) -> tuple[tuple, dict]:
- """Convert tool input to pydantic model.
+ """Convert tool input to Pydantic model.
Args:
tool_input: The input to the tool.
@@ -79,8 +79,7 @@ class Tool(BaseTool):
ToolException: If the tool input is invalid.
Returns:
- the pydantic model args and kwargs.
-
+ The Pydantic model args and kwargs.
"""
args, kwargs = super()._to_args_and_kwargs(tool_input, tool_call_id)
# For backwards compatibility. The tool must be run with a single input
diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.py
index 1ca8b0954a..7b23782814 100644
--- a/libs/core/langchain_core/utils/function_calling.py
+++ b/libs/core/langchain_core/utils/function_calling.py
@@ -713,7 +713,7 @@ def tool_example_to_messages(
"type": "function",
"function": {
# The name of the function right now corresponds to the name
- # of the pydantic model. This is implicit in the API right now,
+ # of the Pydantic model. This is implicit in the API right now,
# and will be improved over time.
"name": tool_call.__class__.__name__,
"arguments": tool_call.model_dump_json(),
diff --git a/libs/core/langchain_core/utils/pydantic.py b/libs/core/langchain_core/utils/pydantic.py
index db7bf460ff..b0c58048a8 100644
--- a/libs/core/langchain_core/utils/pydantic.py
+++ b/libs/core/langchain_core/utils/pydantic.py
@@ -206,7 +206,7 @@ def _create_subset_model_v1(
descriptions: dict | None = None,
fn_description: str | None = None,
) -> type[BaseModel]:
- """Create a pydantic model with only a subset of model's fields."""
+ """Create a Pydantic model with only a subset of model's fields."""
fields = {}
for field_name in field_names:
@@ -235,7 +235,7 @@ def _create_subset_model_v2(
descriptions: dict | None = None,
fn_description: str | None = None,
) -> type[BaseModel]:
- """Create a pydantic model with a subset of the model fields."""
+ """Create a Pydantic model with a subset of the model fields."""
descriptions_ = descriptions or {}
fields = {}
for field_name in field_names:
@@ -438,9 +438,9 @@ def create_model(
/,
**field_definitions: Any,
) -> type[BaseModel]:
- """Create a pydantic model with the given field definitions.
+ """Create a Pydantic model with the given field definitions.
- Please use create_model_v2 instead of this function.
+ Please use `create_model_v2` instead of this function.
Args:
model_name: The name of the model.
@@ -511,7 +511,7 @@ def create_model_v2(
field_definitions: dict[str, Any] | None = None,
root: Any | None = None,
) -> type[BaseModel]:
- """Create a pydantic model with the given field definitions.
+ """Create a Pydantic model with the given field definitions.
Attention:
Please do not use outside of langchain packages. This API
@@ -522,7 +522,7 @@ def create_model_v2(
module_name: The name of the module where the model is defined.
This is used by Pydantic to resolve any forward references.
field_definitions: The field definitions for the model.
- root: Type for a root model (RootModel)
+ root: Type for a root model (`RootModel`)
Returns:
The created model.
diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.py
index adc737e8fc..1e385bf74f 100644
--- a/libs/core/tests/unit_tests/test_tools.py
+++ b/libs/core/tests/unit_tests/test_tools.py
@@ -1934,11 +1934,10 @@ def test_args_schema_as_pydantic(pydantic_model: Any) -> None:
def test_args_schema_explicitly_typed() -> None:
- """This should test that one can type the args schema as a pydantic model.
-
- Please note that this will test using pydantic 2 even though BaseTool
- is a pydantic 1 model!
+ """This should test that one can type the args schema as a Pydantic model.
+ Please note that this will test using pydantic 2 even though `BaseTool`
+ is a Pydantic 1 model!
"""
class Foo(BaseModel):
@@ -1981,7 +1980,7 @@ def test_args_schema_explicitly_typed() -> None:
@pytest.mark.parametrize("pydantic_model", TEST_MODELS)
def test_structured_tool_with_different_pydantic_versions(pydantic_model: Any) -> None:
- """This should test that one can type the args schema as a pydantic model."""
+ """This should test that one can type the args schema as a Pydantic model."""
def foo(a: int, b: str) -> str:
"""Hahaha."""
diff --git a/libs/langchain/langchain_classic/chains/openai_functions/extraction.py b/libs/langchain/langchain_classic/chains/openai_functions/extraction.py
index 1230bc769f..3075bf93ea 100644
--- a/libs/langchain/langchain_classic/chains/openai_functions/extraction.py
+++ b/libs/langchain/langchain_classic/chains/openai_functions/extraction.py
@@ -155,10 +155,10 @@ def create_extraction_chain_pydantic(
prompt: BasePromptTemplate | None = None,
verbose: bool = False, # noqa: FBT001,FBT002
) -> Chain:
- """Creates a chain that extracts information from a passage using pydantic schema.
+ """Creates a chain that extracts information from a passage using Pydantic schema.
Args:
- pydantic_schema: The pydantic schema of the entities to extract.
+ pydantic_schema: The Pydantic schema of the entities to extract.
llm: The language model to use.
prompt: The prompt to use for extraction.
verbose: Whether to run in verbose mode. In verbose mode, some intermediate
diff --git a/libs/langchain/langchain_classic/chains/openai_functions/tagging.py b/libs/langchain/langchain_classic/chains/openai_functions/tagging.py
index 81021bc842..bbb21f9cb5 100644
--- a/libs/langchain/langchain_classic/chains/openai_functions/tagging.py
+++ b/libs/langchain/langchain_classic/chains/openai_functions/tagging.py
@@ -93,7 +93,7 @@ def create_tagging_chain(
kwargs: Additional keyword arguments to pass to the chain.
Returns:
- Chain (LLMChain) that can be used to extract information from a passage.
+ Chain (`LLMChain`) that can be used to extract information from a passage.
"""
function = _get_tagging_function(schema)
@@ -130,10 +130,10 @@ def create_tagging_chain_pydantic(
prompt: ChatPromptTemplate | None = None,
**kwargs: Any,
) -> Chain:
- """Create tagging chain from pydantic schema.
+ """Create tagging chain from Pydantic schema.
Create a chain that extracts information from a passage
- based on a pydantic schema.
+ based on a Pydantic schema.
This function is deprecated. Please use `with_structured_output` instead.
See example usage below:
@@ -163,13 +163,13 @@ def create_tagging_chain_pydantic(
Read more here: https://python.langchain.com/docs/how_to/structured_output/
Args:
- pydantic_schema: The pydantic schema of the entities to extract.
+ 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.
+ Chain (`LLMChain`) that can be used to extract information from a passage.
"""
if hasattr(pydantic_schema, "model_json_schema"):
diff --git a/libs/langchain/langchain_classic/output_parsers/yaml.py b/libs/langchain/langchain_classic/output_parsers/yaml.py
index d6c7bfebae..b286cf5c87 100644
--- a/libs/langchain/langchain_classic/output_parsers/yaml.py
+++ b/libs/langchain/langchain_classic/output_parsers/yaml.py
@@ -16,10 +16,10 @@ T = TypeVar("T", bound=BaseModel)
class YamlOutputParser(BaseOutputParser[T]):
- """Parse YAML output using a pydantic model."""
+ """Parse YAML output using a Pydantic model."""
pydantic_object: type[T]
- """The pydantic model to parse."""
+ """The Pydantic model to parse."""
pattern: re.Pattern = re.compile(
r"^```(?:ya?ml)?(?P<yaml>[^`]*)",
re.MULTILINE | re.DOTALL,
diff --git a/libs/langchain_v1/langchain/agents/middleware/pii.py b/libs/langchain_v1/langchain/agents/middleware/pii.py
index 00e28bfe26..6b7285fa6a 100644
--- a/libs/langchain_v1/langchain/agents/middleware/pii.py
+++ b/libs/langchain_v1/langchain/agents/middleware/pii.py
@@ -431,14 +431,12 @@ class PIIMiddleware(AgentMiddleware):
Strategy Selection Guide:
- ======== =================== =======================================
- Strategy Preserves Identity? Best For
- ======== =================== =======================================
- `block` N/A Avoid PII completely
- `redact` No General compliance, log sanitization
- `mask` No Human readability, customer service UIs
- `hash` Yes (pseudonymous) Analytics, debugging
- ======== =================== =======================================
+ | Strategy | Preserves Identity? | Best For |
+ | -------- | ------------------- | --------------------------------------- |
+ | `block` | N/A | Avoid PII completely |
+ | `redact` | No | General compliance, log sanitization |
+ | `mask` | No | Human readability, customer service UIs |
+ | `hash` | Yes (pseudonymous) | Analytics, debugging |
Example:
```python
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index 39eb5ba4a3..b9dde0a3ed 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -21,7 +21,7 @@ if TYPE_CHECKING:
from langchain.tools.tool_node import ToolCallRequest
-# needed as top level import for pydantic schema generation on AgentState
+# Needed as top level import for Pydantic schema generation on AgentState
from typing import TypeAlias
from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, ToolMessage # noqa: TC002
diff --git a/libs/standard-tests/langchain_tests/unit_tests/tools.py b/libs/standard-tests/langchain_tests/unit_tests/tools.py
index da8e9047c1..aeeaf1ef76 100644
--- a/libs/standard-tests/langchain_tests/unit_tests/tools.py
+++ b/libs/standard-tests/langchain_tests/unit_tests/tools.py
@@ -35,8 +35,8 @@ class ToolsTests(BaseStandardTests):
def tool_invoke_params_example(self) -> dict:
"""Returns a dictionary representing the "args" of an example tool call.
- This should NOT be a ToolCall dict - it should not
- have {"name", "id", "args"} keys.
+ This should NOT be a `ToolCall` dict - it should not have
+ `{"name", "id", "args"}` keys.
"""
return {}
@@ -69,9 +69,9 @@ class ToolsUnitTests(ToolsTests):
def test_init(self) -> None:
"""Test init.
- Test that the tool can be initialized with :attr:`tool_constructor` and
- :attr:`tool_constructor_params`. If this fails, check that the
- keyword args defined in :attr:`tool_constructor_params` are valid.
+ Test that the tool can be initialized with `tool_constructor` and
+ `tool_constructor_params`. If this fails, check that the
+ keyword args defined in `tool_constructor_params` are valid.
"""
if isinstance(self.tool_constructor, BaseTool):
tool = self.tool_constructor
@@ -117,7 +117,7 @@ class ToolsUnitTests(ToolsTests):
If this fails, update the `tool_invoke_params_example` attribute to match
the input schema (`args_schema`) of the tool.
"""
- # this will be a pydantic object
+ # This will be a Pydantic object
input_schema = tool.get_input_schema()
assert input_schema(**self.tool_invoke_params_example)