diff --git a/libs/core/langchain_core/chat_history.py b/libs/core/langchain_core/chat_history.py index 2dbd170f49a..47b32e0dff7 100644 --- a/libs/core/langchain_core/chat_history.py +++ b/libs/core/langchain_core/chat_history.py @@ -152,7 +152,7 @@ class BaseChatMessageHistory(ABC): message: A BaseMessage object to store. Raises: - `NotImplementedError`: If the sub-class has not implemented an efficient + NotImplementedError: If the sub-class has not implemented an efficient `add_messages` method. """ if type(self).add_messages != BaseChatMessageHistory.add_messages: diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.py index ea367aa43ad..4776ec44d86 100644 --- a/libs/core/langchain_core/documents/base.py +++ b/libs/core/langchain_core/documents/base.py @@ -184,7 +184,7 @@ class Blob(BaseMedia): """Read data as a byte stream. Raises: - `NotImplementedError`: If the blob cannot be represented as a byte stream. + NotImplementedError: If the blob cannot be represented as a byte stream. Yields: The data as a byte stream. diff --git a/libs/core/langchain_core/language_models/__init__.py b/libs/core/langchain_core/language_models/__init__.py index 6e2770ecf10..966b42e1220 100644 --- a/libs/core/langchain_core/language_models/__init__.py +++ b/libs/core/langchain_core/language_models/__init__.py @@ -1,43 +1,29 @@ """Language models. -**Language Model** is a type of model that can generate text or complete -text prompts. +LangChain has two main classes to work with language models: chat models and +"old-fashioned" LLMs. -LangChain has two main classes to work with language models: **Chat Models** -and "old-fashioned" **LLMs**. - -**Chat Models** +**Chat models** Language models that use a sequence of messages as inputs and return chat messages -as outputs (as opposed to using plain text). These are traditionally newer models ( -older models are generally LLMs, see below). Chat models support the assignment of +as outputs (as opposed to using plain text). Chat models support the assignment of distinct roles to conversation messages, helping to distinguish messages from the AI, users, and instructions such as system messages. The key abstraction for chat models is `BaseChatModel`. Implementations -should inherit from this class. Please see LangChain how-to guides with more -information on how to implement a custom chat model. +should inherit from this class. -To implement a custom Chat Model, inherit from `BaseChatModel`. See -the following guide for more information on how to implement a custom Chat Model: - -https://python.langchain.com/docs/how_to/custom_chat_model/ +See existing [chat model integrations](https://docs.langchain.com/oss/python/integrations/chat). **LLMs** Language models that takes a string as input and returns a string. -These are traditionally older models (newer models generally are Chat Models, -see below). +These are traditionally older models (newer models generally are chat models). -Although the underlying models are string in, string out, the LangChain wrappers -also allow these models to take messages as input. This gives them the same interface -as Chat Models. When messages are passed in as input, they will be formatted into a -string under the hood before being passed to the underlying model. - -To implement a custom LLM, inherit from `BaseLLM` or `LLM`. -Please see the following guide for more information on how to implement a custom LLM: - -https://python.langchain.com/docs/how_to/custom_llm/ +Although the underlying models are string in, string out, the LangChain wrappers also +allow these models to take messages as input. This gives them the same interface as +chat models. When messages are passed in as input, they will be formatted into a string +under the hood before being passed to the underlying model. """ from typing import TYPE_CHECKING diff --git a/libs/core/langchain_core/language_models/base.py b/libs/core/langchain_core/language_models/base.py index 0d28d50ead8..7091ccc5217 100644 --- a/libs/core/langchain_core/language_models/base.py +++ b/libs/core/langchain_core/language_models/base.py @@ -96,9 +96,16 @@ def _get_token_ids_default_method(text: str) -> list[int]: LanguageModelInput = PromptValue | str | Sequence[MessageLikeRepresentation] +"""Input to a language model.""" + LanguageModelOutput = BaseMessage | str +"""Output from a language model.""" + LanguageModelLike = Runnable[LanguageModelInput, LanguageModelOutput] +"""Input/output interface for a language model.""" + LanguageModelOutputVar = TypeVar("LanguageModelOutputVar", AIMessage, str) +"""Type variable for the output of a language model.""" def _get_verbosity() -> bool: diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py index 1b9b84fa8ff..c01b11b28d0 100644 --- a/libs/core/langchain_core/language_models/chat_models.py +++ b/libs/core/langchain_core/language_models/chat_models.py @@ -264,21 +264,21 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): 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`. | + | 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 | + | Method/Property | Description | Required | | -------------------------------- | ------------------------------------------------------------------ | ----------------- | | `_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 | @@ -287,9 +287,6 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): | `_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: - [Guide](https://python.langchain.com/docs/how_to/custom_chat_model/). - """ # noqa: E501 rate_limiter: BaseRateLimiter | None = Field(default=None, exclude=True) @@ -325,11 +322,12 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): Supported values: - `'v0'`: provider-specific format in content (can lazily-parse with - `.content_blocks`) - - `'v1'`: standardized format in content (consistent 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 - new content formats in a backward-compatible way. + Partner packages (e.g., + [`langchain-openai`](https://pypi.org/project/langchain-openai)) can also use this + field to roll out new content formats in a backward-compatible way. !!! version-added "Added in version 1.0" @@ -1525,8 +1523,8 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC): with keys `'raw'`, `'parsed'`, and `'parsing_error'`. Raises: - `ValueError`: If there are any unsupported `kwargs`. - `NotImplementedError`: If the model does not implement + ValueError: If there are any unsupported `kwargs`. + NotImplementedError: If the model does not implement `with_structured_output()`. Returns: diff --git a/libs/core/langchain_core/load/load.py b/libs/core/langchain_core/load/load.py index 8fe8bbdfebb..ed832e69dbb 100644 --- a/libs/core/langchain_core/load/load.py +++ b/libs/core/langchain_core/load/load.py @@ -100,10 +100,10 @@ class Reviver: The revived value. Raises: - `ValueError`: If the namespace is invalid. - `ValueError`: If trying to deserialize something that cannot + ValueError: If the namespace is invalid. + ValueError: If trying to deserialize something that cannot be deserialized in the current version of langchain-core. - `NotImplementedError`: If the object is not implemented and + NotImplementedError: If the object is not implemented and `ignore_unserializable_fields` is False. """ if ( diff --git a/libs/core/langchain_core/messages/ai.py b/libs/core/langchain_core/messages/ai.py index 167a99ee6c2..96981f7b2f6 100644 --- a/libs/core/langchain_core/messages/ai.py +++ b/libs/core/langchain_core/messages/ai.py @@ -148,23 +148,22 @@ class UsageMetadata(TypedDict): class AIMessage(BaseMessage): """Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. """ tool_calls: list[ToolCall] = [] - """If provided, tool calls associated with the message.""" + """If present, tool calls associated with the message.""" invalid_tool_calls: list[InvalidToolCall] = [] - """If provided, tool calls with parsing errors associated with the message.""" + """If present, tool calls with parsing errors associated with the message.""" usage_metadata: UsageMetadata | None = None - """If provided, usage metadata for a message, such as token counts. + """If present, usage metadata for a message, such as token counts. This is a standard representation of token usage that is consistent across models. - """ type: Literal["ai"] = "ai" @@ -191,7 +190,7 @@ class AIMessage(BaseMessage): content_blocks: list[types.ContentBlock] | None = None, **kwargs: Any, ) -> None: - """Initializes an `AIMessage`. + """Initialize an `AIMessage`. Specify `content` as positional arg or `content_blocks` for typing. @@ -217,7 +216,11 @@ class AIMessage(BaseMessage): @property def lc_attributes(self) -> dict: - """Attrs to be serialized even if they are derived from other init args.""" + """Attributes to be serialized. + + Includes all attributes, even if they are derived from other initialization + arguments. + """ return { "tool_calls": self.tool_calls, "invalid_tool_calls": self.invalid_tool_calls, @@ -225,7 +228,7 @@ class AIMessage(BaseMessage): @property def content_blocks(self) -> list[types.ContentBlock]: - """Return content blocks of the message. + """Return standard, typed `ContentBlock` dicts from the message. If the message has a known model provider, use the provider-specific translator first before falling back to best-effort parsing. For details, see the property @@ -331,7 +334,7 @@ class AIMessage(BaseMessage): @override def pretty_repr(self, html: bool = False) -> str: - """Return a pretty representation of the message. + """Return a pretty representation of the message for display. Args: html: Whether to return an HTML-formatted string. @@ -371,7 +374,7 @@ class AIMessage(BaseMessage): class AIMessageChunk(AIMessage, BaseMessageChunk): - """Message chunk from an AI.""" + """Message chunk from an AI (yielded when streaming).""" # Ignoring mypy re-assignment here since we're overriding the value # to make sure that the chunk variant can be discriminated from the @@ -391,7 +394,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk): @property def lc_attributes(self) -> dict: - """Attrs to be serialized even if they are derived from other init args.""" + """Attributes to be serialized, even if they are derived from other initialization args.""" # noqa: E501 return { "tool_calls": self.tool_calls, "invalid_tool_calls": self.invalid_tool_calls, @@ -399,7 +402,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk): @property def content_blocks(self) -> list[types.ContentBlock]: - """Return content blocks of the message.""" + """Return standard, typed `ContentBlock` dicts from the message.""" if self.response_metadata.get("output_version") == "v1": return cast("list[types.ContentBlock]", self.content) diff --git a/libs/core/langchain_core/messages/base.py b/libs/core/langchain_core/messages/base.py index 793c3551102..0ff93095f20 100644 --- a/libs/core/langchain_core/messages/base.py +++ b/libs/core/langchain_core/messages/base.py @@ -96,7 +96,7 @@ class BaseMessage(Serializable): """ content: str | list[str | dict] - """The string contents of the message.""" + """The contents of the message.""" additional_kwargs: dict = Field(default_factory=dict) """Reserved for additional payload data associated with the message. @@ -164,7 +164,7 @@ class BaseMessage(Serializable): Specify `content` as positional arg or `content_blocks` for typing. Args: - content: The string contents of the message. + content: The contents of the message. content_blocks: Typed standard content. **kwargs: Additional arguments to pass to the parent class. """ @@ -262,7 +262,7 @@ class BaseMessage(Serializable): Can be used as both property (`message.text`) and method (`message.text()`). !!! deprecated - As of langchain-core 1.0.0, calling `.text()` as a method is deprecated. + As of `langchain-core` 1.0.0, calling `.text()` as a method is deprecated. Use `.text` as a property instead. This method will be removed in 2.0.0. Returns: diff --git a/libs/core/langchain_core/messages/block_translators/__init__.py b/libs/core/langchain_core/messages/block_translators/__init__.py index 11419fd5b81..9d0c67ea7d2 100644 --- a/libs/core/langchain_core/messages/block_translators/__init__.py +++ b/libs/core/langchain_core/messages/block_translators/__init__.py @@ -28,7 +28,7 @@ dictionary with two keys: - `'translate_content'`: Function to translate `AIMessage` content. - `'translate_content_chunk'`: Function to translate `AIMessageChunk` content. -When calling `.content_blocks` on an `AIMessage` or `AIMessageChunk`, if +When calling `content_blocks` on an `AIMessage` or `AIMessageChunk`, if `model_provider` is set in `response_metadata`, the corresponding translator functions will be used to parse the content into blocks. Otherwise, best-effort parsing in `BaseMessage` will be used. diff --git a/libs/core/langchain_core/messages/block_translators/anthropic.py b/libs/core/langchain_core/messages/block_translators/anthropic.py index 87f9df8a392..c5178be45b9 100644 --- a/libs/core/langchain_core/messages/block_translators/anthropic.py +++ b/libs/core/langchain_core/messages/block_translators/anthropic.py @@ -31,7 +31,7 @@ def _convert_to_v1_from_anthropic_input( ) -> list[types.ContentBlock]: """Convert Anthropic format blocks to v1 format. - During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1 + During the `content_blocks` parsing process, we wrap blocks not recognized as a v1 block as a `'non_standard'` block with the original block stored in the `value` field. This function attempts to unpack those blocks and convert any blocks that might be Anthropic format to v1 ContentBlocks. diff --git a/libs/core/langchain_core/messages/block_translators/bedrock_converse.py b/libs/core/langchain_core/messages/block_translators/bedrock_converse.py index 6d5e517e49f..c44ef6ca535 100644 --- a/libs/core/langchain_core/messages/block_translators/bedrock_converse.py +++ b/libs/core/langchain_core/messages/block_translators/bedrock_converse.py @@ -35,7 +35,7 @@ def _convert_to_v1_from_converse_input( ) -> list[types.ContentBlock]: """Convert Bedrock Converse format blocks to v1 format. - During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1 + During the `content_blocks` parsing process, we wrap blocks not recognized as a v1 block as a `'non_standard'` block with the original block stored in the `value` field. This function attempts to unpack those blocks and convert any blocks that might be Converse format to v1 ContentBlocks. diff --git a/libs/core/langchain_core/messages/block_translators/google_genai.py b/libs/core/langchain_core/messages/block_translators/google_genai.py index db7954d5c69..aff955100b5 100644 --- a/libs/core/langchain_core/messages/block_translators/google_genai.py +++ b/libs/core/langchain_core/messages/block_translators/google_genai.py @@ -105,7 +105,7 @@ def _convert_to_v1_from_genai_input( Called when message isn't an `AIMessage` or `model_provider` isn't set on `response_metadata`. - During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1 + During the `content_blocks` parsing process, we wrap blocks not recognized as a v1 block as a `'non_standard'` block with the original block stored in the `value` field. This function attempts to unpack those blocks and convert any blocks that might be GenAI format to v1 ContentBlocks. diff --git a/libs/core/langchain_core/messages/block_translators/langchain_v0.py b/libs/core/langchain_core/messages/block_translators/langchain_v0.py index 2172bf6e829..f7cb03839e8 100644 --- a/libs/core/langchain_core/messages/block_translators/langchain_v0.py +++ b/libs/core/langchain_core/messages/block_translators/langchain_v0.py @@ -10,7 +10,7 @@ def _convert_v0_multimodal_input_to_v1( ) -> list[types.ContentBlock]: """Convert v0 multimodal blocks to v1 format. - During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1 + During the `content_blocks` parsing process, we wrap blocks not recognized as a v1 block as a `'non_standard'` block with the original block stored in the `value` field. This function attempts to unpack those blocks and convert any v0 format blocks to v1 format. diff --git a/libs/core/langchain_core/messages/block_translators/openai.py b/libs/core/langchain_core/messages/block_translators/openai.py index 5d60ce025ac..f70c15feca3 100644 --- a/libs/core/langchain_core/messages/block_translators/openai.py +++ b/libs/core/langchain_core/messages/block_translators/openai.py @@ -155,7 +155,7 @@ def _convert_to_v1_from_chat_completions_input( ) -> list[types.ContentBlock]: """Convert OpenAI Chat Completions format blocks to v1 format. - During the `.content_blocks` parsing process, we wrap blocks not recognized as a v1 + During the `content_blocks` parsing process, we wrap blocks not recognized as a v1 block as a `'non_standard'` block with the original block stored in the `value` field. This function attempts to unpack those blocks and convert any blocks that might be OpenAI format to v1 ContentBlocks. diff --git a/libs/core/langchain_core/messages/content.py b/libs/core/langchain_core/messages/content.py index a544e2d17e0..3d36b65e127 100644 --- a/libs/core/langchain_core/messages/content.py +++ b/libs/core/langchain_core/messages/content.py @@ -143,7 +143,7 @@ class Citation(TypedDict): not the source text. This means that the indices are relative to the model's response, not the original document (as specified in the `url`). - !!! note + !!! note "Factory function" `create_citation` may also be used as a factory to create a `Citation`. Benefits include: @@ -214,6 +214,7 @@ class NonStandardAnnotation(TypedDict): Annotation = Citation | NonStandardAnnotation +"""A union of all defined `Annotation` types.""" class TextContentBlock(TypedDict): @@ -222,7 +223,7 @@ class TextContentBlock(TypedDict): This typically represents the main text content of a message, such as the response from a language model or the text of a user message. - !!! note + !!! note "Factory function" `create_text_block` may also be used as a factory to create a `TextContentBlock`. Benefits include: @@ -258,7 +259,7 @@ class TextContentBlock(TypedDict): class ToolCall(TypedDict): - """Represents a request to call a tool. + """Represents an AI's request to call a tool. Example: ```python @@ -268,7 +269,7 @@ class ToolCall(TypedDict): This represents a request to call the tool named "foo" with arguments {"a": 1} and an identifier of "123". - !!! note + !!! note "Factory function" `create_tool_call` may also be used as a factory to create a `ToolCall`. Benefits include: @@ -303,7 +304,7 @@ class ToolCall(TypedDict): class ToolCallChunk(TypedDict): - """A chunk of a tool call (e.g., as part of a stream). + """A chunk of a tool call (yielded when streaming). When merging `ToolCallChunks` (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -385,7 +386,10 @@ class InvalidToolCall(TypedDict): class ServerToolCall(TypedDict): - """Tool call that is executed server-side.""" + """Tool call that is executed server-side. + + For example: code execution, web search, etc. + """ type: Literal["server_tool_call"] """Used for discrimination.""" @@ -407,7 +411,7 @@ class ServerToolCall(TypedDict): class ServerToolCallChunk(TypedDict): - """A chunk of a tool call (as part of a stream).""" + """A chunk of a server-side tool call (yielded when streaming).""" type: Literal["server_tool_call_chunk"] """Used for discrimination.""" @@ -456,7 +460,7 @@ class ServerToolResult(TypedDict): class ReasoningContentBlock(TypedDict): """Reasoning output from a LLM. - !!! note + !!! note "Factory function" `create_reasoning_block` may also be used as a factory to create a `ReasoningContentBlock`. Benefits include: @@ -499,7 +503,7 @@ class ReasoningContentBlock(TypedDict): class ImageContentBlock(TypedDict): """Image data. - !!! note + !!! note "Factory function" `create_image_block` may also be used as a factory to create a `ImageContentBlock`. Benefits include: @@ -547,7 +551,7 @@ class ImageContentBlock(TypedDict): class VideoContentBlock(TypedDict): """Video data. - !!! note + !!! note "Factory function" `create_video_block` may also be used as a factory to create a `VideoContentBlock`. Benefits include: @@ -595,7 +599,7 @@ class VideoContentBlock(TypedDict): class AudioContentBlock(TypedDict): """Audio data. - !!! note + !!! note "Factory function" `create_audio_block` may also be used as a factory to create an `AudioContentBlock`. Benefits include: * Automatic ID generation (when not provided) @@ -652,7 +656,7 @@ class PlainTextContentBlock(TypedDict): Title and context are optional fields that may be passed to the model. See Anthropic [example](https://docs.anthropic.com/en/docs/build-with-claude/citations#citable-vs-non-citable-content). - !!! note + !!! note "Factory function" `create_plaintext_block` may also be used as a factory to create a `PlainTextContentBlock`. Benefits include: @@ -703,7 +707,7 @@ class PlainTextContentBlock(TypedDict): class FileContentBlock(TypedDict): - """File data that doesn't fit into other multimodal blocks. + """File data that doesn't fit into other multimodal block types. This block is intended for files that are not images, audio, or plaintext. For example, it can be used for PDFs, Word documents, etc. @@ -712,7 +716,7 @@ class FileContentBlock(TypedDict): content block type (e.g., `ImageContentBlock`, `AudioContentBlock`, `PlainTextContentBlock`). - !!! note + !!! note "Factory function" `create_file_block` may also be used as a factory to create a `FileContentBlock`. Benefits include: @@ -775,7 +779,7 @@ class NonStandardContentBlock(TypedDict): Has no `extras` field, as provider-specific data should be included in the `value` field. - !!! note + !!! note "Factory function" `create_non_standard_block` may also be used as a factory to create a `NonStandardContentBlock`. Benefits include: @@ -812,6 +816,7 @@ DataContentBlock = ( | PlainTextContentBlock | FileContentBlock ) +"""A union of all defined multimodal data `ContentBlock` types.""" ToolContentBlock = ( ToolCall | ToolCallChunk | ServerToolCall | ServerToolCallChunk | ServerToolResult @@ -825,6 +830,7 @@ ContentBlock = ( | DataContentBlock | ToolContentBlock ) +"""A union of all defined `ContentBlock` types and aliases.""" KNOWN_BLOCK_TYPES = { diff --git a/libs/core/langchain_core/messages/human.py b/libs/core/langchain_core/messages/human.py index 7aa55ad5610..338e2213700 100644 --- a/libs/core/langchain_core/messages/human.py +++ b/libs/core/langchain_core/messages/human.py @@ -7,9 +7,9 @@ from langchain_core.messages.base import BaseMessage, BaseMessageChunk class HumanMessage(BaseMessage): - """Message from a human. + """Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python diff --git a/libs/core/langchain_core/messages/tool.py b/libs/core/langchain_core/messages/tool.py index 4a6bfc9f1e2..6993ad61c6a 100644 --- a/libs/core/langchain_core/messages/tool.py +++ b/libs/core/langchain_core/messages/tool.py @@ -31,33 +31,31 @@ class ToolMessage(BaseMessage, ToolOutputMixin): Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -78,21 +76,15 @@ class ToolMessage(BaseMessage, ToolOutputMixin): a subset of the full tool output is being passed as message content but the full output is needed in other parts of the code. - !!! version-added "Added in version 0.2.17" - """ status: Literal["success", "error"] = "success" - """Status of the tool invocation. - - !!! version-added "Added in version 0.2.24" - - """ + """Status of the tool invocation.""" additional_kwargs: dict = Field(default_factory=dict, repr=False) - """Currently inherited from BaseMessage, but not used.""" + """Currently inherited from `BaseMessage`, but not used.""" response_metadata: dict = Field(default_factory=dict, repr=False) - """Currently inherited from BaseMessage, but not used.""" + """Currently inherited from `BaseMessage`, but not used.""" @model_validator(mode="before") @classmethod @@ -165,7 +157,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin): Specify `content` as positional arg or `content_blocks` for typing. Args: - content: The string contents of the message. + content: The contents of the message. content_blocks: Typed standard content. **kwargs: Additional fields. """ @@ -211,7 +203,7 @@ class ToolMessageChunk(ToolMessage, BaseMessageChunk): class ToolCall(TypedDict): - """Represents a request to call a tool. + """Represents an AI's request to call a tool. Example: ```python @@ -257,7 +249,7 @@ def tool_call( class ToolCallChunk(TypedDict): - """A chunk of a tool call (e.g., as part of a stream). + """A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py index 489f2daa781..c5bdf2fe6b9 100644 --- a/libs/core/langchain_core/messages/utils.py +++ b/libs/core/langchain_core/messages/utils.py @@ -86,6 +86,7 @@ AnyMessage = Annotated[ | Annotated[ToolMessageChunk, Tag(tag="ToolMessageChunk")], Field(discriminator=Discriminator(_get_type)), ] +""""A type representing any defined `Message` or `MessageChunk` type.""" def get_buffer_string( @@ -209,6 +210,7 @@ def message_chunk_to_message(chunk: BaseMessage) -> BaseMessage: MessageLikeRepresentation = ( BaseMessage | list[str] | tuple[str, str] | str | dict[str, Any] ) +"""A type representing the various ways a message can be represented.""" def _create_message_from_message_type( @@ -320,8 +322,8 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage: An instance of a message or a message template. Raises: - `NotImplementedError`: if the message type is not supported. - `ValueError`: if the message dict does not contain the required keys. + NotImplementedError: if the message type is not supported. + ValueError: if the message dict does not contain the required keys. """ if isinstance(message, BaseMessage): @@ -700,7 +702,7 @@ def trim_messages( r"""Trim messages to be below a token count. `trim_messages` can be used to reduce the size of a chat history to a specified - token count or specified message count. + token or message count. In either case, if passing the trimmed chat history back into a chat model directly, the resulting chat history should usually satisfy the following @@ -711,8 +713,6 @@ def trim_messages( followed by a `HumanMessage`. To achieve this, set `start_on='human'`. In addition, generally a `ToolMessage` can only appear after an `AIMessage` that involved a tool call. - Please see the following link for more information about messages: - https://python.langchain.com/docs/concepts/#messages 2. It includes recent messages and drops old messages in the chat history. To achieve this set the `strategy='last'`. 3. Usually, the new chat history should include the `SystemMessage` if it @@ -764,8 +764,8 @@ def trim_messages( as `BaseMessage` classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...). Can be a single type or a list of types. - include_system: Whether to keep the SystemMessage if there is one at index 0. - Should only be specified if `strategy="last"`. + include_system: Whether to keep the `SystemMessage` if there is one at index + `0`. Should only be specified if `strategy="last"`. text_splitter: Function or `langchain_text_splitters.TextSplitter` for splitting the string contents of a message. Only used if `allow_partial=True`. If `strategy='last'` then the last split tokens @@ -776,7 +776,7 @@ def trim_messages( newlines. Returns: - list of trimmed `BaseMessage`. + List of trimmed `BaseMessage`. Raises: ValueError: if two incompatible arguments are specified or an unrecognized diff --git a/libs/core/langchain_core/output_parsers/openai_functions.py b/libs/core/langchain_core/output_parsers/openai_functions.py index b333c07ce46..71e55d798d8 100644 --- a/libs/core/langchain_core/output_parsers/openai_functions.py +++ b/libs/core/langchain_core/output_parsers/openai_functions.py @@ -238,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: @@ -264,7 +264,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser): 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. diff --git a/libs/core/langchain_core/prompts/base.py b/libs/core/langchain_core/prompts/base.py index 415fc92b62c..941c4ec7266 100644 --- a/libs/core/langchain_core/prompts/base.py +++ b/libs/core/langchain_core/prompts/base.py @@ -343,9 +343,9 @@ class BasePromptTemplate( file_path: Path to directory to save prompt to. Raises: - `ValueError`: If the prompt has partial variables. - `ValueError`: If the file path is not json or yaml. - `NotImplementedError`: If the prompt type is not implemented. + ValueError: If the prompt has partial variables. + ValueError: If the file path is not json or yaml. + NotImplementedError: If the prompt type is not implemented. Example: ```python diff --git a/libs/core/langchain_core/prompts/prompt.py b/libs/core/langchain_core/prompts/prompt.py index 9c763e11a56..6d486dc3aea 100644 --- a/libs/core/langchain_core/prompts/prompt.py +++ b/libs/core/langchain_core/prompts/prompt.py @@ -140,9 +140,9 @@ class PromptTemplate(StringPromptTemplate): """Override the + operator to allow for combining prompt templates. Raises: - `ValueError`: If the template formats are not f-string or if there are + ValueError: If the template formats are not f-string or if there are conflicting partial variables. - `NotImplementedError`: If the other object is not a `PromptTemplate` or str. + NotImplementedError: If the other object is not a `PromptTemplate` or str. Returns: A new `PromptTemplate` that is the combination of the two. diff --git a/libs/core/langchain_core/prompts/structured.py b/libs/core/langchain_core/prompts/structured.py index d1eb89a9517..7ae138cf05b 100644 --- a/libs/core/langchain_core/prompts/structured.py +++ b/libs/core/langchain_core/prompts/structured.py @@ -150,7 +150,7 @@ class StructuredPrompt(ChatPromptTemplate): A RunnableSequence object. Raises: - `NotImplementedError`: If the first element of `others` + NotImplementedError: If the first element of `others` is not a language model. """ if (others and isinstance(others[0], BaseLanguageModel)) or hasattr( diff --git a/libs/core/langchain_core/rate_limiters.py b/libs/core/langchain_core/rate_limiters.py index 2c1a77d2d88..986d3ff63b7 100644 --- a/libs/core/langchain_core/rate_limiters.py +++ b/libs/core/langchain_core/rate_limiters.py @@ -23,9 +23,6 @@ class BaseRateLimiter(abc.ABC): - Rate limiting information is not surfaced in tracing or callbacks. This means that the total time it takes to invoke a chat model will encompass both the time spent waiting for tokens and the time spent making the request. - - - !!! version-added "Added in version 0.2.24" """ @abc.abstractmethod @@ -118,9 +115,6 @@ class InMemoryRateLimiter(BaseRateLimiter): toc = time.time() print(toc - tic) ``` - - !!! version-added "Added in version 0.2.24" - """ # noqa: E501 def __init__( diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py index 3b83d5452e2..93c7413e068 100644 --- a/libs/core/langchain_core/runnables/base.py +++ b/libs/core/langchain_core/runnables/base.py @@ -1448,7 +1448,7 @@ class Runnable(ABC, Generic[Input, Output]): An async stream of `StreamEvent`. Raises: - `NotImplementedError`: If the version is not `'v1'` or `'v2'`. + NotImplementedError: If the version is not `'v1'` or `'v2'`. """ # noqa: E501 if version == "v2": diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py index 87f06e6f2ec..e016344ba93 100644 --- a/libs/core/langchain_core/tools/base.py +++ b/libs/core/langchain_core/tools/base.py @@ -248,7 +248,7 @@ def _function_annotations_are_pydantic_v1( True if all Pydantic annotations are from V1, `False` otherwise. Raises: - `NotImplementedError`: If the function contains mixed V1 and V2 annotations. + NotImplementedError: If the function contains mixed V1 and V2 annotations. """ any_v1_annotations = any( _is_pydantic_annotation(parameter.annotation, pydantic_version="v1") diff --git a/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr b/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr index 0958f2ff241..9533f631d34 100644 --- a/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr +++ b/libs/core/tests/unit_tests/prompts/__snapshots__/test_chat.ambr @@ -7,10 +7,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -111,7 +111,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -518,9 +518,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -981,7 +981,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -1027,7 +1027,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -1114,33 +1114,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -1428,10 +1426,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -1532,7 +1530,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -1939,9 +1937,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -2402,7 +2400,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -2448,7 +2446,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -2535,33 +2533,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able diff --git a/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr b/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr index 6c957e613fc..e227d761f77 100644 --- a/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr +++ b/libs/core/tests/unit_tests/runnables/__snapshots__/test_graph.ambr @@ -431,10 +431,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -535,7 +535,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -942,9 +942,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -1405,7 +1405,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -1451,7 +1451,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -1538,33 +1538,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able diff --git a/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr b/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr index 618a9147eb5..aa1f908cb8b 100644 --- a/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr +++ b/libs/core/tests/unit_tests/runnables/__snapshots__/test_runnable.ambr @@ -1963,10 +1963,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -2066,7 +2066,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -2467,9 +2467,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -2925,7 +2925,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -2970,7 +2970,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -3056,33 +3056,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -3364,10 +3362,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -3467,7 +3465,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -3931,9 +3929,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -4408,7 +4406,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -4453,7 +4451,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -4539,33 +4537,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -4859,10 +4855,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -4962,7 +4958,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -5426,9 +5422,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -5903,7 +5899,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -5948,7 +5944,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -6034,33 +6030,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -6292,10 +6286,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -6395,7 +6389,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -6796,9 +6790,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -7254,7 +7248,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -7299,7 +7293,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -7385,33 +7379,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -7735,10 +7727,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -7838,7 +7830,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -8302,9 +8294,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -8779,7 +8771,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -8824,7 +8816,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -8910,33 +8902,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -9213,10 +9203,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -9316,7 +9306,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -9717,9 +9707,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -10175,7 +10165,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -10220,7 +10210,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -10306,33 +10296,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -10564,10 +10552,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -10667,7 +10655,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -11131,9 +11119,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -11619,7 +11607,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -11664,7 +11652,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -11750,33 +11738,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able @@ -12020,10 +12006,10 @@ 'description': ''' Message from an AI. - `AIMessage` is returned from a chat model as a response to a prompt. + An `AIMessage` is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both - the raw output as returned by the model together standardized fields + the raw output as returned by the model and standardized fields (e.g., tool calls, usage metadata) added by the LangChain framework. ''', 'properties': dict({ @@ -12123,7 +12109,7 @@ }), 'AIMessageChunk': dict({ 'additionalProperties': True, - 'description': 'Message chunk from an AI.', + 'description': 'Message chunk from an AI (yielded when streaming).', 'properties': dict({ 'additional_kwargs': dict({ 'title': 'Additional Kwargs', @@ -12587,9 +12573,9 @@ 'HumanMessage': dict({ 'additionalProperties': True, 'description': ''' - Message from a human. + Message from the user. - `HumanMessage`s are messages that are passed in from a human to the model. + A `HumanMessage` is a message that is passed in from a user to the model. Example: ```python @@ -13064,7 +13050,7 @@ }), 'ToolCall': dict({ 'description': ''' - Represents a request to call a tool. + Represents an AI's request to call a tool. Example: ```python @@ -13109,7 +13095,7 @@ }), 'ToolCallChunk': dict({ 'description': ''' - A chunk of a tool call (e.g., as part of a stream). + A chunk of a tool call (yielded when streaming). When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`), all string attributes are concatenated. Chunks are only merged if their @@ -13195,33 +13181,31 @@ Example: A `ToolMessage` representing a result of `42` from a tool call with id - ```python - from langchain_core.messages import ToolMessage + ```python + from langchain_core.messages import ToolMessage - ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") - ``` + ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL") + ``` Example: A `ToolMessage` where only part of the tool output is sent to the model - and the full output is passed in to artifact. + and the full output is passed in to artifact. - !!! version-added "Added in version 0.2.17" + ```python + from langchain_core.messages import ToolMessage - ```python - from langchain_core.messages import ToolMessage + tool_output = { + "stdout": "From the graph we can see that the correlation between " + "x and y is ...", + "stderr": None, + "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, + } - tool_output = { - "stdout": "From the graph we can see that the correlation between " - "x and y is ...", - "stderr": None, - "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."}, - } - - ToolMessage( - content=tool_output["stdout"], - artifact=tool_output, - tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", - ) - ``` + ToolMessage( + content=tool_output["stdout"], + artifact=tool_output, + tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL", + ) + ``` The `tool_call_id` field is used to associate the tool call request with the tool call response. Useful in situations where a chat model is able diff --git a/libs/langchain/langchain_classic/agents/agent.py b/libs/langchain/langchain_classic/agents/agent.py index 180f9ab0374..786fd3921c7 100644 --- a/libs/langchain/langchain_classic/agents/agent.py +++ b/libs/langchain/langchain_classic/agents/agent.py @@ -328,8 +328,8 @@ class BaseMultiActionAgent(BaseModel): file_path: Path to file to save the agent to. Raises: - `NotImplementedError`: If agent does not support saving. - `ValueError`: If `file_path` is not json or yaml. + NotImplementedError: If agent does not support saving. + ValueError: If `file_path` is not json or yaml. Example: ```python diff --git a/libs/langchain/langchain_classic/chat_models/base.py b/libs/langchain/langchain_classic/chat_models/base.py index b0d28fd2648..8fac6261676 100644 --- a/libs/langchain/langchain_classic/chat_models/base.py +++ b/libs/langchain/langchain_classic/chat_models/base.py @@ -88,63 +88,66 @@ def init_chat_model( for supported model parameters. Args: - model: The name of the model, e.g. `'o3-mini'`, `'claude-sonnet-4-5-20250929'`. You can - also specify model and model provider in a single argument using - `'{model_provider}:{model}'` format, e.g. `'openai:o1'`. - model_provider: The model provider if not specified as part of model arg (see - above). Supported model_provider values and the corresponding integration - package are: + model: The name of the model, e.g. `'o3-mini'`, `'claude-sonnet-4-5-20250929'`. - - `openai` -> `langchain-openai` - - `anthropic` -> `langchain-anthropic` - - `azure_openai` -> `langchain-openai` - - `azure_ai` -> `langchain-azure-ai` - - `google_vertexai` -> `langchain-google-vertexai` - - `google_genai` -> `langchain-google-genai` - - `bedrock` -> `langchain-aws` - - `bedrock_converse` -> `langchain-aws` - - `cohere` -> `langchain-cohere` - - `fireworks` -> `langchain-fireworks` - - `together` -> `langchain-together` - - `mistralai` -> `langchain-mistralai` - - `huggingface` -> `langchain-huggingface` - - `groq` -> `langchain-groq` - - `ollama` -> `langchain-ollama` - - `google_anthropic_vertex` -> `langchain-google-vertexai` - - `deepseek` -> `langchain-deepseek` - - `ibm` -> `langchain-ibm` - - `nvidia` -> `langchain-nvidia-ai-endpoints` - - `xai` -> `langchain-xai` - - `perplexity` -> `langchain-perplexity` + You can also specify model and model provider in a single argument using: + + `'{model_provider}:{model}'` format, e.g. `'openai:o1'`. + model_provider: The model provider if not specified as part of the model arg + (see above). Supported `model_provider` values and the corresponding + integration package are: + + - `openai` -> [`langchain-openai`](https://docs.langchain.com/oss/python/integrations/providers/openai) + - `anthropic` -> [`langchain-anthropic`](https://docs.langchain.com/oss/python/integrations/providers/anthropic) + - `azure_openai` -> [`langchain-openai`](https://docs.langchain.com/oss/python/integrations/providers/openai) + - `azure_ai` -> [`langchain-azure-ai`](https://docs.langchain.com/oss/python/integrations/providers/microsoft) + - `google_vertexai` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google) + - `google_genai` -> [`langchain-google-genai`](https://docs.langchain.com/oss/python/integrations/providers/google) + - `bedrock` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws) + - `bedrock_converse` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws) + - `cohere` -> [`langchain-cohere`](https://docs.langchain.com/oss/python/integrations/providers/cohere) + - `fireworks` -> [`langchain-fireworks`](https://docs.langchain.com/oss/python/integrations/providers/fireworks) + - `together` -> [`langchain-together`](https://docs.langchain.com/oss/python/integrations/providers/together) + - `mistralai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai) + - `huggingface` -> [`langchain-huggingface`](https://docs.langchain.com/oss/python/integrations/providers/huggingface) + - `groq` -> [`langchain-groq`](https://docs.langchain.com/oss/python/integrations/providers/groq) + - `ollama` -> [`langchain-ollama`](https://docs.langchain.com/oss/python/integrations/providers/ollama) + - `google_anthropic_vertex` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google) + - `deepseek` -> [`langchain-deepseek`](https://docs.langchain.com/oss/python/integrations/providers/deepseek) + - `ibm` -> [`langchain-ibm`](https://docs.langchain.com/oss/python/integrations/providers/deepseek) + - `nvidia` -> [`langchain-nvidia-ai-endpoints`](https://docs.langchain.com/oss/python/integrations/providers/nvidia) + - `xai` -> [`langchain-xai`](https://docs.langchain.com/oss/python/integrations/providers/xai) + - `perplexity` -> [`langchain-perplexity`](https://docs.langchain.com/oss/python/integrations/providers/perplexity) Will attempt to infer `model_provider` from model if not specified. The following providers will be inferred based on these model prefixes: - `gpt-...` | `o1...` | `o3...` -> `openai` - - `claude...` -> `anthropic` - - `amazon...` -> `bedrock` - - `gemini...` -> `google_vertexai` - - `command...` -> `cohere` - - `accounts/fireworks...` -> `fireworks` - - `mistral...` -> `mistralai` - - `deepseek...` -> `deepseek` - - `grok...` -> `xai` - - `sonar...` -> `perplexity` + - `claude...` -> `anthropic` + - `amazon...` -> `bedrock` + - `gemini...` -> `google_vertexai` + - `command...` -> `cohere` + - `accounts/fireworks...` -> `fireworks` + - `mistral...` -> `mistralai` + - `deepseek...` -> `deepseek` + - `grok...` -> `xai` + - `sonar...` -> `perplexity` configurable_fields: Which model parameters are configurable: - `None`: No configurable fields. - - `'any'`: All fields are configurable. **See Security Note below.** + - `'any'`: All fields are configurable. **See security note below.** - `list[str] | Tuple[str, ...]`: Specified fields are configurable. Fields are assumed to have `config_prefix` stripped if there is a `config_prefix`. If model is specified, then defaults to `None`. If model is not specified, then defaults to `("model", "model_provider")`. - **Security Note**: Setting `configurable_fields="any"` means fields like - `api_key`, `base_url`, etc. can be altered at runtime, potentially redirecting - model requests to a different service/user. Make sure that if you're - accepting untrusted configurations that you enumerate the - `configurable_fields=(...)` explicitly. + !!! warning "Security note" + Setting `configurable_fields="any"` means fields like `api_key`, + `base_url`, etc. can be altered at runtime, potentially redirecting + model requests to a different service/user. Make sure that if you're + accepting untrusted configurations that you enumerate the + `configurable_fields=(...)` explicitly. config_prefix: If `'config_prefix'` is a non-empty string then model will be configurable at runtime via the @@ -170,10 +173,10 @@ def init_chat_model( config is passed in. Raises: - `ValueError`: If `model_provider` cannot be inferred or isn't supported. - `ImportError`: If the model provider integration package is not installed. + ValueError: If `model_provider` cannot be inferred or isn't supported. + ImportError: If the model provider integration package is not installed. - ???+ note "Init non-configurable model" + ???+ note "Initialize a non-configurable model" ```python # pip install langchain langchain-openai langchain-anthropic langchain-google-vertexai @@ -242,7 +245,7 @@ def init_chat_model( ??? note "Bind tools to a configurable model" You can call any chat model declarative methods on a configurable model in the - same way that you would with a normal model. + same way that you would with a normal model: ```python # pip install langchain langchain-openai langchain-anthropic diff --git a/libs/langchain/langchain_classic/evaluation/string_distance/base.py b/libs/langchain/langchain_classic/evaluation/string_distance/base.py index ee72d933289..88e91cffefe 100644 --- a/libs/langchain/langchain_classic/evaluation/string_distance/base.py +++ b/libs/langchain/langchain_classic/evaluation/string_distance/base.py @@ -22,7 +22,7 @@ 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: The `rapidfuzz.distance` module. diff --git a/libs/langchain/langchain_classic/model_laboratory.py b/libs/langchain/langchain_classic/model_laboratory.py index fef007bb4ae..31700b5bafc 100644 --- a/libs/langchain/langchain_classic/model_laboratory.py +++ b/libs/langchain/langchain_classic/model_laboratory.py @@ -26,10 +26,10 @@ class ModelLaboratory: 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): diff --git a/libs/langchain_v1/langchain/agents/__init__.py b/libs/langchain_v1/langchain/agents/__init__.py index 3552fa28f69..67ac01b1ac5 100644 --- a/libs/langchain_v1/langchain/agents/__init__.py +++ b/libs/langchain_v1/langchain/agents/__init__.py @@ -1,6 +1,9 @@ """Entrypoint to building [Agents](https://docs.langchain.com/oss/python/langchain/agents) with LangChain. -See [the docs](https://docs.langchain.com/oss/python/langchain/agents) for more details. +!!! warning "Reference docs" + This page contains **reference documentation** for Agents. See + [the docs](https://docs.langchain.com/oss/python/langchain/agents) for conceptual + guides, tutorials, and examples on using Agents. """ # noqa: E501 from langchain.agents.factory import create_agent diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py index e847a654535..31d560d07df 100644 --- a/libs/langchain_v1/langchain/agents/factory.py +++ b/libs/langchain_v1/langchain/agents/factory.py @@ -92,7 +92,7 @@ def _chain_model_call_handlers( handlers: List of handlers. First handler wraps all others. Returns: - Composed handler, or None if handlers empty. + Composed handler, or `None` if handlers empty. Example: ```python @@ -195,13 +195,13 @@ def _chain_async_model_call_handlers( ] | None ): - """Compose multiple async wrap_model_call handlers into single middleware stack. + """Compose multiple async `wrap_model_call` handlers into single middleware stack. Args: handlers: List of async handlers. First handler wraps all others. Returns: - Composed async handler, or None if handlers empty. + Composed async handler, or `None` if handlers empty. """ if not handlers: return None @@ -267,12 +267,13 @@ def _chain_async_model_call_handlers( def _resolve_schema(schemas: set[type], schema_name: str, omit_flag: str | None = None) -> type: - """Resolve schema by merging schemas and optionally respecting OmitFromSchema annotations. + """Resolve schema by merging schemas and optionally respecting `OmitFromSchema` annotations. Args: schemas: List of schema types to merge - schema_name: Name for the generated TypedDict - omit_flag: If specified, omit fields with this flag set ('input' or 'output') + schema_name: Name for the generated `TypedDict` + omit_flag: If specified, omit fields with this flag set (`'input'` or + `'output'`) """ all_annotations = {} @@ -312,11 +313,11 @@ def _extract_metadata(type_: type) -> list: def _get_can_jump_to(middleware: AgentMiddleware[Any, Any], hook_name: str) -> list[JumpTo]: - """Get the can_jump_to list from either sync or async hook methods. + """Get the `can_jump_to` list from either sync or async hook methods. Args: middleware: The middleware instance to inspect. - hook_name: The name of the hook ('before_model' or 'after_model'). + hook_name: The name of the hook (`'before_model'` or `'after_model'`). Returns: List of jump destinations, or empty list if not configured. @@ -350,7 +351,7 @@ def _supports_provider_strategy(model: str | BaseChatModel) -> bool: """Check if a model supports provider-specific structured output. Args: - model: Model name string or BaseChatModel instance. + model: Model name string or `BaseChatModel` instance. Returns: `True` if the model supports provider-specific structured output, `False` otherwise. @@ -373,7 +374,7 @@ def _handle_structured_output_error( exception: Exception, response_format: ResponseFormat, ) -> 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, "" @@ -408,7 +409,7 @@ def _chain_tool_call_wrappers( wrappers: Wrappers in middleware order. Returns: - Composed wrapper, or None if empty. + Composed wrapper, or `None` if empty. Example: wrapper = _chain_tool_call_wrappers([auth, cache, retry]) @@ -465,7 +466,7 @@ def _chain_async_tool_call_wrappers( wrappers: Async wrappers in middleware order. Returns: - Composed async wrapper, or None if empty. + Composed async wrapper, or `None` if empty. """ if not wrappers: return None @@ -534,7 +535,9 @@ def create_agent( # noqa: PLR0915 Args: model: The language model for the agent. Can be a string identifier - (e.g., `"openai:gpt-4"`), a chat model instance (e.g., `ChatOpenAI()`). + (e.g., `"openai:gpt-4"`) or a chat model instance (e.g., `ChatOpenAI()`). + For a full list of supported model strings, see + [`init_chat_model`][langchain.chat_models.init_chat_model(model_provider)]. tools: A list of tools, `dicts`, or `Callable`. If `None` or an empty list, the agent will consist of a model node without a tool calling loop. system_prompt: An optional system prompt for the LLM. Prompts are converted to a @@ -881,8 +884,9 @@ def create_agent( # noqa: PLR0915 request: The model request containing model, tools, and response format. Returns: - Tuple of (bound_model, effective_response_format) where `effective_response_format` - is the actual strategy used (may differ from initial if auto-detected). + Tuple of `(bound_model, effective_response_format)` where + `effective_response_format` is the actual strategy used (may differ from + initial if auto-detected). """ # Validate ONLY client-side tools that need to exist in tool_node # Build map of available client-side tools from the ToolNode @@ -988,7 +992,7 @@ def create_agent( # noqa: PLR0915 def _execute_model_sync(request: ModelRequest) -> ModelResponse: """Execute model and return response. - This is the core model execution logic wrapped by wrap_model_call handlers. + 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) @@ -1039,7 +1043,9 @@ def create_agent( # noqa: PLR0915 async def _execute_model_async(request: ModelRequest) -> ModelResponse: """Execute model asynchronously and return response. - This is the core async model execution logic wrapped by wrap_model_call handlers. + This is the core async 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) diff --git a/libs/langchain_v1/langchain/agents/middleware/__init__.py b/libs/langchain_v1/langchain/agents/middleware/__init__.py index 5c63302997a..5b40667126f 100644 --- a/libs/langchain_v1/langchain/agents/middleware/__init__.py +++ b/libs/langchain_v1/langchain/agents/middleware/__init__.py @@ -1,7 +1,9 @@ """Entrypoint to using [Middleware](https://docs.langchain.com/oss/python/langchain/middleware) plugins with [Agents](https://docs.langchain.com/oss/python/langchain/agents). -See [the docs](https://docs.langchain.com/oss/python/langchain/middleware) for more -details. +!!! warning "Reference docs" + This page contains **reference documentation** for Middleware. See + [the docs](https://docs.langchain.com/oss/python/langchain/middleware) for conceptual + guides, tutorials, and examples on using Middleware. """ # noqa: E501 from .context_editing import ( diff --git a/libs/langchain_v1/langchain/agents/middleware/pii.py b/libs/langchain_v1/langchain/agents/middleware/pii.py index 6b7285fa6a6..2e7d4d93367 100644 --- a/libs/langchain_v1/langchain/agents/middleware/pii.py +++ b/libs/langchain_v1/langchain/agents/middleware/pii.py @@ -421,7 +421,7 @@ class PIIMiddleware(AgentMiddleware): - `credit_card`: Credit card numbers (validated with Luhn algorithm) - `ip`: IP addresses (validated with stdlib) - `mac_address`: MAC addresses - - `url`: URLs (both http/https and bare URLs) + - `url`: URLs (both `http`/`https` and bare URLs) Strategies: - `block`: Raise an exception when PII is detected @@ -431,12 +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/structured_output.py b/libs/langchain_v1/langchain/agents/structured_output.py index 0893566e5ef..cd6a2fd9aed 100644 --- a/libs/langchain_v1/langchain/agents/structured_output.py +++ b/libs/langchain_v1/langchain/agents/structured_output.py @@ -39,7 +39,7 @@ class MultipleStructuredOutputsError(StructuredOutputError): """Raised when model returns multiple structured output tool calls when only one is expected.""" def __init__(self, tool_names: list[str]) -> None: - """Initialize MultipleStructuredOutputsError. + """Initialize `MultipleStructuredOutputsError`. Args: tool_names: The names of the tools called for structured output. @@ -56,7 +56,7 @@ class StructuredOutputValidationError(StructuredOutputError): """Raised when structured output tool call arguments fail to parse according to the schema.""" def __init__(self, tool_name: str, source: Exception) -> None: - """Initialize StructuredOutputValidationError. + """Initialize `StructuredOutputValidationError`. Args: tool_name: The name of the tool that failed. @@ -73,8 +73,9 @@ def _parse_with_schema( """Parse data using for any supported schema type. Args: - schema: The schema type (Pydantic model, dataclass, or TypedDict) - schema_kind: One of "pydantic", "dataclass", "typeddict", or "json_schema" + schema: The schema type (Pydantic model, `dataclass`, or `TypedDict`) + schema_kind: One of `"pydantic"`, `"dataclass"`, `"typeddict"`, or + `"json_schema"` data: The data to parse Returns: @@ -99,13 +100,14 @@ class _SchemaSpec(Generic[SchemaT]): """Describes a structured output schema.""" schema: type[SchemaT] - """The schema for the response, can be a Pydantic model, dataclass, TypedDict, + """The schema for the response, can be a Pydantic model, `dataclass`, `TypedDict`, or JSON schema dict.""" name: str """Name of the schema, used for tool calling. - If not provided, the name will be the model name or "response_format" if it's a JSON schema. + If not provided, the name will be the model name or `"response_format"` if it's a + JSON schema. """ description: str @@ -186,14 +188,15 @@ class ToolStrategy(Generic[SchemaT]): handle_errors: ( bool | str | type[Exception] | tuple[type[Exception], ...] | Callable[[Exception], str] ) - """Error handling strategy for structured output via ToolStrategy. + """Error handling strategy for structured output via `ToolStrategy`. - - True: Catch all errors with default error template - - str: Catch all errors with this custom message - - type[Exception]: Only catch this exception type with default message - - tuple[type[Exception], ...]: Only catch these exception types with default message - - Callable[[Exception], str]: Custom function that returns error message - - False: No retry, let exceptions propagate + - `True`: Catch all errors with default error template + - `str`: Catch all errors with this custom message + - `type[Exception]`: Only catch this exception type with default message + - `tuple[type[Exception], ...]`: Only catch these exception types with default + message + - `Callable[[Exception], str]`: Custom function that returns error message + - `False`: No retry, let exceptions propagate """ def __init__( @@ -207,9 +210,10 @@ class ToolStrategy(Generic[SchemaT]): | tuple[type[Exception], ...] | Callable[[Exception], str] = True, ) -> None: - """Initialize ToolStrategy. + """Initialize `ToolStrategy`. - Initialize ToolStrategy with schemas, tool message content, and error handling strategy. + Initialize `ToolStrategy` with schemas, tool message content, and error handling + strategy. """ self.schema = schema self.tool_message_content = tool_message_content @@ -285,13 +289,13 @@ class OutputToolBinding(Generic[SchemaT]): @classmethod def from_schema_spec(cls, schema_spec: _SchemaSpec[SchemaT]) -> Self: - """Create an OutputToolBinding instance from a SchemaSpec. + """Create an `OutputToolBinding` instance from a `SchemaSpec`. Args: - schema_spec: The SchemaSpec to convert + schema_spec: The `SchemaSpec` to convert Returns: - An OutputToolBinding instance with the appropriate tool created + An `OutputToolBinding` instance with the appropriate tool created """ return cls( schema=schema_spec.schema, @@ -329,20 +333,20 @@ class ProviderStrategyBinding(Generic[SchemaT]): schema: type[SchemaT] """The original schema provided for structured output - (Pydantic model, dataclass, TypedDict, or JSON schema dict).""" + (Pydantic model, `dataclass`, `TypedDict`, or JSON schema dict).""" schema_kind: SchemaKind """Classification of the schema type for proper response construction.""" @classmethod def from_schema_spec(cls, schema_spec: _SchemaSpec[SchemaT]) -> Self: - """Create a ProviderStrategyBinding instance from a SchemaSpec. + """Create a `ProviderStrategyBinding` instance from a `SchemaSpec`. Args: - schema_spec: The SchemaSpec to convert + schema_spec: The `SchemaSpec` to convert Returns: - A ProviderStrategyBinding instance for parsing native structured output + A `ProviderStrategyBinding` instance for parsing native structured output """ return cls( schema=schema_spec.schema, @@ -350,10 +354,10 @@ class ProviderStrategyBinding(Generic[SchemaT]): ) def parse(self, response: AIMessage) -> SchemaT: - """Parse AIMessage content according to the schema. + """Parse `AIMessage` content according to the schema. Args: - response: The AI message containing the structured output + response: The `AIMessage` containing the structured output Returns: The parsed response according to the schema diff --git a/libs/langchain_v1/langchain/chat_models/__init__.py b/libs/langchain_v1/langchain/chat_models/__init__.py index 7d33e942910..f52b04c4e06 100644 --- a/libs/langchain_v1/langchain/chat_models/__init__.py +++ b/libs/langchain_v1/langchain/chat_models/__init__.py @@ -1,7 +1,9 @@ """Entrypoint to using [chat models](https://docs.langchain.com/oss/python/langchain/models) in LangChain. -See [the docs](https://docs.langchain.com/oss/python/langchain/models) for more -details. +!!! warning "Reference docs" + This page contains **reference documentation** for chat models. See + [the docs](https://docs.langchain.com/oss/python/langchain/models) for conceptual + guides, tutorials, and examples on using chat models. """ # noqa: E501 from langchain_core.language_models import BaseChatModel diff --git a/libs/langchain_v1/langchain/chat_models/base.py b/libs/langchain_v1/langchain/chat_models/base.py index 2b3f8972e62..737c78d4eb0 100644 --- a/libs/langchain_v1/langchain/chat_models/base.py +++ b/libs/langchain_v1/langchain/chat_models/base.py @@ -83,63 +83,66 @@ def init_chat_model( for supported model parameters. Args: - model: The name of the model, e.g. `'o3-mini'`, `'claude-sonnet-4-5-20250929'`. You can - also specify model and model provider in a single argument using - `'{model_provider}:{model}'` format, e.g. `'openai:o1'`. - model_provider: The model provider if not specified as part of model arg (see - above). Supported model_provider values and the corresponding integration - package are: + model: The name of the model, e.g. `'o3-mini'`, `'claude-sonnet-4-5-20250929'`. - - `openai` -> `langchain-openai` - - `anthropic` -> `langchain-anthropic` - - `azure_openai` -> `langchain-openai` - - `azure_ai` -> `langchain-azure-ai` - - `google_vertexai` -> `langchain-google-vertexai` - - `google_genai` -> `langchain-google-genai` - - `bedrock` -> `langchain-aws` - - `bedrock_converse` -> `langchain-aws` - - `cohere` -> `langchain-cohere` - - `fireworks` -> `langchain-fireworks` - - `together` -> `langchain-together` - - `mistralai` -> `langchain-mistralai` - - `huggingface` -> `langchain-huggingface` - - `groq` -> `langchain-groq` - - `ollama` -> `langchain-ollama` - - `google_anthropic_vertex` -> `langchain-google-vertexai` - - `deepseek` -> `langchain-deepseek` - - `ibm` -> `langchain-ibm` - - `nvidia` -> `langchain-nvidia-ai-endpoints` - - `xai` -> `langchain-xai` - - `perplexity` -> `langchain-perplexity` + You can also specify model and model provider in a single argument using: + + `'{model_provider}:{model}'` format, e.g. `'openai:o1'`. + model_provider: The model provider if not specified as part of the model arg + (see above). Supported `model_provider` values and the corresponding + integration package are: + + - `openai` -> [`langchain-openai`](https://docs.langchain.com/oss/python/integrations/providers/openai) + - `anthropic` -> [`langchain-anthropic`](https://docs.langchain.com/oss/python/integrations/providers/anthropic) + - `azure_openai` -> [`langchain-openai`](https://docs.langchain.com/oss/python/integrations/providers/openai) + - `azure_ai` -> [`langchain-azure-ai`](https://docs.langchain.com/oss/python/integrations/providers/microsoft) + - `google_vertexai` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google) + - `google_genai` -> [`langchain-google-genai`](https://docs.langchain.com/oss/python/integrations/providers/google) + - `bedrock` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws) + - `bedrock_converse` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws) + - `cohere` -> [`langchain-cohere`](https://docs.langchain.com/oss/python/integrations/providers/cohere) + - `fireworks` -> [`langchain-fireworks`](https://docs.langchain.com/oss/python/integrations/providers/fireworks) + - `together` -> [`langchain-together`](https://docs.langchain.com/oss/python/integrations/providers/together) + - `mistralai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai) + - `huggingface` -> [`langchain-huggingface`](https://docs.langchain.com/oss/python/integrations/providers/huggingface) + - `groq` -> [`langchain-groq`](https://docs.langchain.com/oss/python/integrations/providers/groq) + - `ollama` -> [`langchain-ollama`](https://docs.langchain.com/oss/python/integrations/providers/ollama) + - `google_anthropic_vertex` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google) + - `deepseek` -> [`langchain-deepseek`](https://docs.langchain.com/oss/python/integrations/providers/deepseek) + - `ibm` -> [`langchain-ibm`](https://docs.langchain.com/oss/python/integrations/providers/deepseek) + - `nvidia` -> [`langchain-nvidia-ai-endpoints`](https://docs.langchain.com/oss/python/integrations/providers/nvidia) + - `xai` -> [`langchain-xai`](https://docs.langchain.com/oss/python/integrations/providers/xai) + - `perplexity` -> [`langchain-perplexity`](https://docs.langchain.com/oss/python/integrations/providers/perplexity) Will attempt to infer `model_provider` from model if not specified. The following providers will be inferred based on these model prefixes: - `gpt-...` | `o1...` | `o3...` -> `openai` - - `claude...` -> `anthropic` - - `amazon...` -> `bedrock` - - `gemini...` -> `google_vertexai` - - `command...` -> `cohere` - - `accounts/fireworks...` -> `fireworks` - - `mistral...` -> `mistralai` - - `deepseek...` -> `deepseek` - - `grok...` -> `xai` - - `sonar...` -> `perplexity` + - `claude...` -> `anthropic` + - `amazon...` -> `bedrock` + - `gemini...` -> `google_vertexai` + - `command...` -> `cohere` + - `accounts/fireworks...` -> `fireworks` + - `mistral...` -> `mistralai` + - `deepseek...` -> `deepseek` + - `grok...` -> `xai` + - `sonar...` -> `perplexity` configurable_fields: Which model parameters are configurable: - `None`: No configurable fields. - - `'any'`: All fields are configurable. **See Security Note below.** + - `'any'`: All fields are configurable. **See security note below.** - `list[str] | Tuple[str, ...]`: Specified fields are configurable. Fields are assumed to have `config_prefix` stripped if there is a `config_prefix`. If model is specified, then defaults to `None`. If model is not specified, then defaults to `("model", "model_provider")`. - **Security Note**: Setting `configurable_fields="any"` means fields like - `api_key`, `base_url`, etc. can be altered at runtime, potentially redirecting - model requests to a different service/user. Make sure that if you're - accepting untrusted configurations that you enumerate the - `configurable_fields=(...)` explicitly. + !!! warning "Security note" + Setting `configurable_fields="any"` means fields like `api_key`, + `base_url`, etc. can be altered at runtime, potentially redirecting + model requests to a different service/user. Make sure that if you're + accepting untrusted configurations that you enumerate the + `configurable_fields=(...)` explicitly. config_prefix: If `'config_prefix'` is a non-empty string then model will be configurable at runtime via the @@ -165,10 +168,10 @@ def init_chat_model( config is passed in. Raises: - `ValueError`: If `model_provider` cannot be inferred or isn't supported. - `ImportError`: If the model provider integration package is not installed. + ValueError: If `model_provider` cannot be inferred or isn't supported. + ImportError: If the model provider integration package is not installed. - ???+ note "Init non-configurable model" + ???+ note "Initialize a non-configurable model" ```python # pip install langchain langchain-openai langchain-anthropic langchain-google-vertexai @@ -231,7 +234,7 @@ def init_chat_model( ??? note "Bind tools to a configurable model" You can call any chat model declarative methods on a configurable model in the - same way that you would with a normal model. + same way that you would with a normal model: ```python # pip install langchain langchain-openai langchain-anthropic diff --git a/libs/langchain_v1/langchain/embeddings/__init__.py b/libs/langchain_v1/langchain/embeddings/__init__.py index b75c7a307cc..d94e53b211e 100644 --- a/libs/langchain_v1/langchain/embeddings/__init__.py +++ b/libs/langchain_v1/langchain/embeddings/__init__.py @@ -1,4 +1,10 @@ -"""Embeddings.""" +"""Embeddings. + +!!! warning "Reference docs" + This page contains **reference documentation** for Embeddings. See + [the docs](https://docs.langchain.com/oss/python/langchain/retrieval#embedding-models) + for conceptual guides, tutorials, and examples on using Embeddings. +""" from langchain_core.embeddings import Embeddings diff --git a/libs/langchain_v1/langchain/messages/__init__.py b/libs/langchain_v1/langchain/messages/__init__.py index 39c20b53991..014a27df396 100644 --- a/libs/langchain_v1/langchain/messages/__init__.py +++ b/libs/langchain_v1/langchain/messages/__init__.py @@ -1,4 +1,13 @@ -"""Message types.""" +"""Message types. + +Includes message types for different roles (e.g., human, AI, system), as well as types +for message content blocks (e.g., text, image, audio) and tool calls. + +!!! warning "Reference docs" + This page contains **reference documentation** for Messages. See + [the docs](https://docs.langchain.com/oss/python/langchain/messages) for conceptual + guides, tutorials, and examples on using Messages. +""" from langchain_core.messages import ( AIMessage, diff --git a/libs/langchain_v1/langchain/tools/__init__.py b/libs/langchain_v1/langchain/tools/__init__.py index 36f5de0c88f..190f6955c45 100644 --- a/libs/langchain_v1/langchain/tools/__init__.py +++ b/libs/langchain_v1/langchain/tools/__init__.py @@ -1,4 +1,10 @@ -"""Tools.""" +"""Tools. + +!!! warning "Reference docs" + This page contains **reference documentation** for Tools. See + [the docs](https://docs.langchain.com/oss/python/langchain/tools) for conceptual + guides, tutorials, and examples on using Tools. +""" from langchain_core.tools import ( BaseTool,