Skip to content

The agent engineering platform.

style(langchain): lint (#34863)

Mason Daugherty17de2a368581
diff --git a/libs/langchain_v1/README.md b/libs/langchain_v1/README.md
index 438734e94f..2796a2d40b 100644
--- a/libs/langchain_v1/README.md
+++ b/libs/langchain_v1/README.md
@@ -26,7 +26,7 @@ LangChain [agents](https://docs.langchain.com/oss/python/langchain/agents) are b
## πŸ“– Documentation
-For full documentation, see the [API reference](https://reference.langchain.com/python/langchain/langchain/). For conceptual guides, tutorials, and examples on using LangChain, see the [LangChain Docs](https://docs.langchain.com/oss/python/langchain/overview).
+For full documentation, see the [API reference](https://reference.langchain.com/python/langchain/langchain/). For conceptual guides, tutorials, and examples on using LangChain, see the [LangChain Docs](https://docs.langchain.com/oss/python/langchain/overview). You can also chat with the docs using [Chat LangChain](https://chat.langchain.com).
## πŸ“• Releases & Versioning
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index a7106fbb78..743d773e2b 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -123,13 +123,15 @@ def _chain_model_call_handlers(
]
| None
):
- """Compose multiple wrap_model_call handlers into single middleware stack.
+ """Compose multiple `wrap_model_call` handlers into single middleware stack.
- Composes handlers so first in list becomes outermost layer. Each handler
- receives a handler callback to execute inner layers.
+ Composes handlers so first in list becomes outermost layer. Each handler receives a
+ handler callback to execute inner layers.
Args:
- handlers: List of handlers. First handler wraps all others.
+ handlers: List of handlers.
+
+ First handler wraps all others.
Returns:
Composed handler, or `None` if handlers empty.
@@ -238,7 +240,9 @@ def _chain_async_model_call_handlers(
"""Compose multiple async `wrap_model_call` handlers into single middleware stack.
Args:
- handlers: List of async handlers. First handler wraps all others.
+ handlers: List of async handlers.
+
+ First handler wraps all others.
Returns:
Composed async handler, or `None` if handlers empty.
@@ -341,7 +345,7 @@ def _resolve_schema(schemas: set[type], schema_name: str, omit_flag: str | None
def _extract_metadata(type_: type) -> list[Any]:
- """Extract metadata from a field type, handling Required/NotRequired and Annotated wrappers."""
+ """Extract metadata from a field type, handling `Required`/`NotRequired` and `Annotated` wrappers.""" # noqa: E501
# Handle Required[Annotated[...]] or NotRequired[Annotated[...]]
if get_origin(type_) in {Required, NotRequired}:
inner_type = get_args(type_)[0]
@@ -397,8 +401,9 @@ def _supports_provider_strategy(
Args:
model: Model name string or `BaseChatModel` instance.
- tools: Optional list of tools provided to the agent. Needed because some models
- don't support structured output together with tool calling.
+ tools: Optional list of tools provided to the agent.
+
+ Needed because some models don't support structured output together with tool calling.
Returns:
`True` if the model supports provider-specific structured output, `False` otherwise.
@@ -433,7 +438,10 @@ def _handle_structured_output_error(
exception: Exception,
response_format: ResponseFormat[Any],
) -> tuple[bool, str]:
- """Handle structured output error. Returns `(should_retry, retry_tool_message)`."""
+ """Handle structured output error.
+
+ Returns `(should_retry, retry_tool_message)`.
+ """
if not isinstance(response_format, ToolStrategy):
return False, ""
@@ -468,9 +476,11 @@ def _chain_tool_call_wrappers(
Composed wrapper, or `None` if empty.
Example:
+ ```python
wrapper = _chain_tool_call_wrappers([auth, cache, retry])
# Request flows: auth -> cache -> retry -> tool
# Response flows: tool -> retry -> cache -> auth
+ ```
"""
if not wrappers:
return None
@@ -907,8 +917,8 @@ def create_agent(
Args:
output: The AI message output from the model.
- effective_response_format: The actual strategy used
- (may differ from initial if auto-detected).
+ effective_response_format: The actual strategy used (may differ from initial
+ if auto-detected).
"""
# Handle structured output with provider strategy
if isinstance(effective_response_format, ProviderStrategy):
@@ -1126,6 +1136,7 @@ def create_agent(
"""Execute model and return response.
This is the core model execution logic wrapped by `wrap_model_call` handlers.
+
Raises any exceptions that occur during model invocation.
"""
# Get the bound model (with auto-detection if needed)
@@ -1562,7 +1573,7 @@ def _make_model_to_tools_edge(
def model_to_tools(
state: dict[str, Any],
) -> str | list[Send] | None:
- # 1. if there's an explicit jump_to in the state, use it
+ # 1. If there's an explicit jump_to in the state, use it
if jump_to := state.get("jump_to"):
return _resolve_jump(
jump_to,
@@ -1573,7 +1584,7 @@ def _make_model_to_tools_edge(
last_ai_message, tool_messages = _fetch_last_ai_and_tool_messages(state["messages"])
tool_message_ids = [m.tool_call_id for m in tool_messages]
- # 2. if the model hasn't called any tools, exit the loop
+ # 2. If the model hasn't called any tools, exit the loop
# this is the classic exit condition for an agent loop
if len(last_ai_message.tool_calls) == 0:
return end_destination
@@ -1584,7 +1595,7 @@ def _make_model_to_tools_edge(
if c["id"] not in tool_message_ids and c["name"] not in structured_output_tools
]
- # 3. if there are pending tool calls, jump to the tool node
+ # 3. If there are pending tool calls, jump to the tool node
if pending_tool_calls:
return [
Send(
@@ -1598,12 +1609,12 @@ def _make_model_to_tools_edge(
for tool_call in pending_tool_calls
]
- # 4. if there is a structured response, exit the loop
+ # 4. If there is a structured response, exit the loop
if "structured_response" in state:
return end_destination
- # 5. AIMessage has tool calls, but there are no pending tool calls
- # which suggests the injection of artificial tool messages. jump to the model node
+ # 5. AIMessage has tool calls, but there are no pending tool calls which suggests
+ # the injection of artificial tool messages. Jump to the model node
return model_destination
return model_to_tools
@@ -1629,8 +1640,8 @@ def _make_model_to_model_edge(
if "structured_response" in state:
return end_destination
- # 3. Default: Continue the loop, there may have been an issue
- # with structured output generation, so we need to retry
+ # 3. Default: Continue the loop, there may have been an issue with structured
+ # output generation, so we need to retry
return model_destination
return model_to_model
diff --git a/libs/langchain_v1/langchain/agents/structured_output.py b/libs/langchain_v1/langchain/agents/structured_output.py
index 11e283b7c5..fda470bcee 100644
--- a/libs/langchain_v1/langchain/agents/structured_output.py
+++ b/libs/langchain_v1/langchain/agents/structured_output.py
@@ -81,8 +81,8 @@ def _parse_with_schema(
Args:
schema: The schema type (Pydantic model, `dataclass`, or `TypedDict`)
- schema_kind: One of `"pydantic"`, `"dataclass"`, `"typeddict"`, or
- `"json_schema"`
+ schema_kind: One of `'pydantic'`, `'dataclass'`, `'typeddict'`, or
+ `'json_schema'`
data: The data to parse
Returns:
@@ -108,13 +108,16 @@ class _SchemaSpec(Generic[SchemaT]):
schema: type[SchemaT] | dict[str, Any]
"""The schema for the response, can be a Pydantic model, `dataclass`, `TypedDict`,
- or JSON schema dict."""
+ or JSON schema dict.
+ """
name: str
"""Name of the schema, used for tool calling.
If not provided, the name will be the class name for models/dataclasses/TypedDicts,
- or the `title` field for JSON schemas. Falls back to a generated name if unavailable.
+ or the `title` field for JSON schemas.
+
+ Falls back to a generated name if unavailable.
"""
description: str
@@ -200,7 +203,8 @@ class ToolStrategy(Generic[SchemaT]):
tool_message_content: str | None
"""The content of the tool message to be returned when the model calls
- an artificial structured output tool."""
+ an artificial structured output tool.
+ """
handle_errors: (
bool | str | type[Exception] | tuple[type[Exception], ...] | Callable[[Exception], str]
@@ -304,14 +308,15 @@ class ProviderStrategy(Generic[SchemaT]):
class OutputToolBinding(Generic[SchemaT]):
"""Information for tracking structured output tool metadata.
- This contains all necessary information to handle structured responses
- generated via tool calls, including the original schema, its type classification,
- and the corresponding tool implementation used by the tools strategy.
+ This contains all necessary information to handle structured responses generated via
+ tool calls, including the original schema, its type classification, and the
+ corresponding tool implementation used by the tools strategy.
"""
schema: type[SchemaT] | dict[str, Any]
- """The original schema provided for structured output
- (Pydantic model, dataclass, TypedDict, or JSON schema dict)."""
+ """The original schema provided for structured output (Pydantic model, dataclass,
+ TypedDict, or JSON schema dict).
+ """
schema_kind: SchemaKind
"""Classification of the schema type for proper response construction."""
@@ -358,14 +363,15 @@ class OutputToolBinding(Generic[SchemaT]):
class ProviderStrategyBinding(Generic[SchemaT]):
"""Information for tracking native structured output metadata.
- This contains all necessary information to handle structured responses
- generated via native provider output, including the original schema,
- its type classification, and parsing logic for provider-enforced JSON.
+ This contains all necessary information to handle structured responses generated via
+ native provider output, including the original schema, its type classification, and
+ parsing logic for provider-enforced JSON.
"""
schema: type[SchemaT] | dict[str, Any]
- """The original schema provided for structured output
- (Pydantic model, `dataclass`, `TypedDict`, or JSON schema dict)."""
+ """The original schema provided for structured output (Pydantic model, `dataclass`,
+ `TypedDict`, or JSON schema dict).
+ """
schema_kind: SchemaKind
"""Classification of the schema type for proper response construction."""
@@ -415,7 +421,7 @@ class ProviderStrategyBinding(Generic[SchemaT]):
@staticmethod
def _extract_text_content_from_message(message: AIMessage) -> str:
- """Extract text content from an AIMessage.
+ """Extract text content from an `AIMessage`.
Args:
message: The AI message to extract text from
diff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.py
index d7ed506869..7148bd44b5 100644
--- a/libs/langchain_v1/langchain/chat_models/base.py
+++ b/libs/langchain_v1/langchain/chat_models/base.py
@@ -209,6 +209,7 @@ def init_chat_model(
changing your code
!!! note "Installation requirements"
+
Requires the integration package for the chosen model provider to be installed.
See the `model_provider` parameter below for specific package names
diff --git a/libs/langchain_v1/langchain/embeddings/__init__.py b/libs/langchain_v1/langchain/embeddings/__init__.py
index fd87dabbf9..3b0ab2982b 100644
--- a/libs/langchain_v1/langchain/embeddings/__init__.py
+++ b/libs/langchain_v1/langchain/embeddings/__init__.py
@@ -1,6 +1,7 @@
"""Embeddings models.
!!! warning "Modules moved"
+
With the release of `langchain 1.0.0`, several embeddings modules were moved to
`langchain-classic`, such as `CacheBackedEmbeddings` and all community
embeddings. See [list](https://github.com/langchain-ai/langchain/blob/bdf1cd383ce36dc18381a3bf3fb0a579337a32b5/libs/langchain/langchain/embeddings/__init__.py)
diff --git a/libs/langchain_v1/langchain/embeddings/base.py b/libs/langchain_v1/langchain/embeddings/base.py
index 18359de430..6d8205c4d8 100644
--- a/libs/langchain_v1/langchain/embeddings/base.py
+++ b/libs/langchain_v1/langchain/embeddings/base.py
@@ -99,13 +99,14 @@ def _parse_model_string(model_name: str) -> tuple[str, str]:
Returns:
A tuple of (provider, model_name)
- ```python
- _parse_model_string("openai:text-embedding-3-small")
- # Returns: ("openai", "text-embedding-3-small")
+ Example:
+ ```python
+ _parse_model_string("openai:text-embedding-3-small")
+ # Returns: ("openai", "text-embedding-3-small")
- _parse_model_string("bedrock:amazon.titan-embed-text-v1")
- # Returns: ("bedrock", "amazon.titan-embed-text-v1")
- ```
+ _parse_model_string("bedrock:amazon.titan-embed-text-v1")
+ # Returns: ("bedrock", "amazon.titan-embed-text-v1")
+ ```
Raises:
ValueError: If the model string is not in the correct format or
@@ -183,6 +184,7 @@ def init_embeddings(
"""Initialize an embedding model from a model name and optional provider.
!!! note
+
Requires the integration package for the chosen model provider to be installed.
See the `model_provider` parameter below for specific package names